From 020dc76640eff747ed3422d292ab7ac74fa9f233 Mon Sep 17 00:00:00 2001 From: strawmanbobi Date: Fri, 11 Nov 2016 16:20:31 +0800 Subject: [PATCH] update 2016-11-11 b1 1. transplanted mini-poem baas framework to web-console 2. created npm install bshell script --- src/ir_encoder/irda_ac_encode.py | 2 + src/ir_encoder/irda_tv_encode.py | 4 +- src/ir_encoder/irda_tv_merge.py | 2 + src/ir_encoder/irda_tv_protocol.py | 2 + src/ir_encoder/irda_tv_protocol_hex.py | 2 + src/web_console/.gitignore | 3 +- src/web_console/authority/admin_auth.js | 6 +- .../configuration/system_configs.js | 2 +- src/web_console/irext_console.js | 8 +- src/web_console/mini-poem/cache/base_cache.js | 22 + src/web_console/mini-poem/cache/memcached.js | 67 +++ src/web_console/mini-poem/cache/redis.js | 74 +++ .../mini-poem/configuration/constants.js | 70 +++ .../mini-poem/configuration/enums.js | 36 ++ .../mini-poem/configuration/error_code.js | 24 + src/web_console/mini-poem/data_set/ali_oss.js | 108 ++++ .../mini-poem/external/python_caller.js | 83 ++++ src/web_console/mini-poem/http/request.js | 131 +++++ src/web_console/mini-poem/libs/JPush/JPush.js | 430 ++++++++++++++++ .../mini-poem/libs/JPush/JPushError.js | 33 ++ .../mini-poem/libs/JPush/PushPayload.js | 468 ++++++++++++++++++ src/web_console/mini-poem/libs/JPush/util.js | 79 +++ .../mini-poem/logging/logger4js.js | 121 +++++ src/web_console/mini-poem/mem/map.js | 120 +++++ .../msg_service/notification_helper.js | 283 +++++++++++ src/web_console/mini-poem/security/md5.js | 192 +++++++ src/web_console/mini-poem/sns/weixin.js | 167 +++++++ src/web_console/mini-poem/timing/scheduler.js | 25 + src/web_console/mini-poem/utils/date_utils.js | 111 +++++ src/web_console/mini-poem/utils/map.js | 120 +++++ .../mini-poem/utils/object_reflection.js | 22 + .../mini-poem/utils/string_utils.js | 38 ++ .../mini-poem/utils/system_utils.js | 32 ++ src/web_console/model/admin_dao.js | 6 +- src/web_console/model/brand_dao.js | 8 +- src/web_console/model/category_dao.js | 8 +- src/web_console/model/city_dao.js | 6 +- src/web_console/model/ir_protocol_dao.js | 6 +- src/web_console/model/remote_index_dao.js | 6 +- src/web_console/model/stb_operator_dao.js | 6 +- src/web_console/model/virtual_remote_dao.js | 6 +- src/web_console/routes/certificate_routes.js | 2 +- src/web_console/routes/index.js | 3 +- src/web_console/routes/internal_routes.js | 2 +- src/web_console/routes/stat_routes.js | 2 +- src/web_console/script_npm.sh | 46 ++ .../services/certificate_service.js | 4 +- src/web_console/services/internal_service.js | 6 +- src/web_console/services/stat_service.js | 4 +- .../work_unit/certificate_logic.js | 8 +- src/web_console/work_unit/internal_logic.js | 16 +- src/web_console/work_unit/stat_logic.js | 8 +- 52 files changed, 2974 insertions(+), 66 deletions(-) create mode 100644 src/web_console/mini-poem/cache/base_cache.js create mode 100644 src/web_console/mini-poem/cache/memcached.js create mode 100644 src/web_console/mini-poem/cache/redis.js create mode 100644 src/web_console/mini-poem/configuration/constants.js create mode 100644 src/web_console/mini-poem/configuration/enums.js create mode 100644 src/web_console/mini-poem/configuration/error_code.js create mode 100644 src/web_console/mini-poem/data_set/ali_oss.js create mode 100644 src/web_console/mini-poem/external/python_caller.js create mode 100644 src/web_console/mini-poem/http/request.js create mode 100644 src/web_console/mini-poem/libs/JPush/JPush.js create mode 100644 src/web_console/mini-poem/libs/JPush/JPushError.js create mode 100644 src/web_console/mini-poem/libs/JPush/PushPayload.js create mode 100644 src/web_console/mini-poem/libs/JPush/util.js create mode 100644 src/web_console/mini-poem/logging/logger4js.js create mode 100644 src/web_console/mini-poem/mem/map.js create mode 100644 src/web_console/mini-poem/msg_service/notification_helper.js create mode 100644 src/web_console/mini-poem/security/md5.js create mode 100644 src/web_console/mini-poem/sns/weixin.js create mode 100644 src/web_console/mini-poem/timing/scheduler.js create mode 100644 src/web_console/mini-poem/utils/date_utils.js create mode 100644 src/web_console/mini-poem/utils/map.js create mode 100644 src/web_console/mini-poem/utils/object_reflection.js create mode 100644 src/web_console/mini-poem/utils/string_utils.js create mode 100644 src/web_console/mini-poem/utils/system_utils.js create mode 100644 src/web_console/script_npm.sh diff --git a/src/ir_encoder/irda_ac_encode.py b/src/ir_encoder/irda_ac_encode.py index 8b9ef1c..be51dab 100644 --- a/src/ir_encoder/irda_ac_encode.py +++ b/src/ir_encoder/irda_ac_encode.py @@ -2,6 +2,8 @@ # coding=utf-8 # for protocol version V1.0 # 29 tags are supported +# +# created by strawmanbobi 2016-11-10 import sys import xml.dom.minidom diff --git a/src/ir_encoder/irda_tv_encode.py b/src/ir_encoder/irda_tv_encode.py index 7fc41e3..3e400f9 100644 --- a/src/ir_encoder/irda_tv_encode.py +++ b/src/ir_encoder/irda_tv_encode.py @@ -1,5 +1,7 @@ #!/usr/bin/env python # coding = utf-8 +# +# created by strawmanbobi 2016-11-10 import sys import xml.dom.minidom @@ -42,7 +44,7 @@ keymap_dict_air_cleaner = ("POWER", "UP", "DOWN", "LEFT", "RIGHT", "ION", "PLUS" keymap_dicts = [keymap_dict_ac, keymap_dict_tv, keymap_dict_stb, keymap_dict_nw, keymap_dict_iptv, keymap_dict_dvd, keymap_dict_fan, keymap_dict_stereo, keymap_dict_projector, keymap_dict_light, keymap_dict_clean_robot, - keymap_dict_ac]; + keymap_dict_ac] class CKeyMap: def __init__(self, name, value): diff --git a/src/ir_encoder/irda_tv_merge.py b/src/ir_encoder/irda_tv_merge.py index f874515..bcca24e 100644 --- a/src/ir_encoder/irda_tv_merge.py +++ b/src/ir_encoder/irda_tv_merge.py @@ -1,5 +1,7 @@ #!/usr/bin/env python # coding=utf-8 +# +# created by strawmanbobi 2016-11-10 import sys import os diff --git a/src/ir_encoder/irda_tv_protocol.py b/src/ir_encoder/irda_tv_protocol.py index 6f20009..83d02b5 100644 --- a/src/ir_encoder/irda_tv_protocol.py +++ b/src/ir_encoder/irda_tv_protocol.py @@ -1,5 +1,7 @@ #!/usr/bin/env python # coding=utf-8 +# +# created by strawmanbobi 2016-11-10 import struct import sys diff --git a/src/ir_encoder/irda_tv_protocol_hex.py b/src/ir_encoder/irda_tv_protocol_hex.py index 6af00f3..f6b6432 100644 --- a/src/ir_encoder/irda_tv_protocol_hex.py +++ b/src/ir_encoder/irda_tv_protocol_hex.py @@ -1,5 +1,7 @@ #!/usr/bin/env python # coding=utf-8 +# +# created by strawmanbobi 2016-11-10 import struct import sys diff --git a/src/web_console/.gitignore b/src/web_console/.gitignore index 1ad6898..f6b2905 100644 --- a/src/web_console/.gitignore +++ b/src/web_console/.gitignore @@ -6,4 +6,5 @@ tools/ .idea/workspace.xml *.DS_Store -nohup.out \ No newline at end of file +nohup.out +node_modules/ \ No newline at end of file diff --git a/src/web_console/authority/admin_auth.js b/src/web_console/authority/admin_auth.js index d9d1c46..ecfff25 100644 --- a/src/web_console/authority/admin_auth.js +++ b/src/web_console/authority/admin_auth.js @@ -3,15 +3,15 @@ * 2015-01-24 */ -require('../../../Infrastructure/BackEnd/configuration/constants'); -var Cache = require('../../../Infrastructure/BackEnd/cache/memcached.js'); +require('../mini-poem/configuration/constants'); +var Cache = require('../mini-poem/cache/memcached.js'); var Enums = require('../configuration/enums'); var ErrorCode = require('../configuration/error_code'); var enums = new Enums(); var errorCode = new ErrorCode(); -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; +var logger = require('../mini-poem/logging/logger4js').helper; var AdminAuth = function(_cacheHost, _cachePort, _cacheAdmin, _cachePassword) { this.cache = new Cache(_cacheHost, _cachePort, _cacheAdmin, _cachePassword); diff --git a/src/web_console/configuration/system_configs.js b/src/web_console/configuration/system_configs.js index 5d0e7d7..1756c32 100644 --- a/src/web_console/configuration/system_configs.js +++ b/src/web_console/configuration/system_configs.js @@ -2,7 +2,7 @@ * Created by strawmanbobi on 14-10-17. */ -require('../../../Infrastructure/BackEnd/configuration/constants'); +require('../mini-poem/configuration/constants'); var Enums = require('./enums'); var enums = new Enums(); diff --git a/src/web_console/irext_console.js b/src/web_console/irext_console.js index e3cbd56..94ed868 100644 --- a/src/web_console/irext_console.js +++ b/src/web_console/irext_console.js @@ -10,8 +10,8 @@ var bodyParser = require('body-parser'); var methodOverride = require('method-override'); // global inclusion -require('../../Infrastructure/BackEnd/configuration/constants'); -var System = require('../../Infrastructure/BackEnd/utils/system_utils'); +require('./mini-poem/configuration/constants'); +var System = require('./mini-poem/utils/system_utils'); var systemConfig = require('./configuration/system_configs'); // local inclusion @@ -35,13 +35,13 @@ app.use("/", express.static(__dirname + '/web/')); systemConfig.setupEnvironment(); serverListenPort = LISTEN_PORT; -var dbConn = require('../../Infrastructure/BackEnd/db/mysql/mysql_connection'); +var dbConn = require('./mini-poem/db/mysql/mysql_connection'); console.log("initializing MySQL connection to : " + MYSQL_DB_SERVER_ADDRESS + ":" + MYSQL_DB_NAME); dbConn.setMySQLParameter(MYSQL_DB_SERVER_ADDRESS, MYSQL_DB_NAME, MYSQL_DB_USER, MYSQL_DB_PASSWORD); // the following statements is automatically generated according to system configuration -var kvConn = require('../../Infrastructure/BackEnd/db/mongodb/mongodb_connection'); +var kvConn = require('./mini-poem/db/mongodb/mongodb_connection'); console.log('initializing MongoDB connection to : ' + MONGO_DB_SERVER_ADDRESS + ":" + MONGO_DB_NAME); kvConn.setMongoDBParameter(MONGO_DB_SERVER_ADDRESS, MONGO_DB_NAME, MONGO_DB_USER, MONGO_DB_PASSWORD); diff --git a/src/web_console/mini-poem/cache/base_cache.js b/src/web_console/mini-poem/cache/base_cache.js new file mode 100644 index 0000000..c297f91 --- /dev/null +++ b/src/web_console/mini-poem/cache/base_cache.js @@ -0,0 +1,22 @@ +/** + * Created by strawmanbobi + * 2014-12-01. + */ + +var BaseCache = function(_cacheType, _host, _port, _user, _password) { + throw new Error("Abstract class"); +}; + +BaseCache.prototype.set = function(key, value, ttl, callback) { + throw new Error("Could not implemented"); +}; + +BaseCache.prototype.get = function(key, callback) { + throw new Error("Could not implemented"); +}; + +BaseCache.prototype.delete = function(key, callback) { + throw new Error("Could not implemented"); +}; + +module.exports = BaseCache; \ No newline at end of file diff --git a/src/web_console/mini-poem/cache/memcached.js b/src/web_console/mini-poem/cache/memcached.js new file mode 100644 index 0000000..8218962 --- /dev/null +++ b/src/web_console/mini-poem/cache/memcached.js @@ -0,0 +1,67 @@ +/** + * Created by strawmanbobi + * 2014-12-02. + */ + +require('../configuration/constants'); +var ErrorCode = require('../configuration/error_code'); +var Enums = require('../configuration/enums'); +var BaseCache = require('./base_cache.js'); + +var AliOCS = require('aliyun-sdk').MEMCACHED; +var logger = require('../logging/logger4js').helper; + +var errorCode = new ErrorCode(); +var enums = new Enums(); + +var Cache = function(_host, _port, _user, _password) { + this.memcached = AliOCS.createClient(_port, _host, { + username: _user, + password: _password + }); + + this.memcached.on('error', function(err) { + logger.error("OCS connection error : " + err); + }); +}; + +Cache.prototype = Object.create(BaseCache.prototype); + +Cache.prototype.set = function(key, value, ttl, callback) { + this.memcached.set(key, value, ttl, function(err, data) { + var error = errorCode.SUCCESS; + if(err) { + logger.error("error occurred when setting " + value + " for " + key); + error = errorCode.FAILED; + } + callback(error, data); + }); +}; + +Cache.prototype.get = function(key, callback) { + this.memcached.get(key, function(err, result) { + var error = errorCode.SUCCESS; + if(err) { + logger.error("error occurred when getting value for " + key); + error = errorCode.FAILED; + } + if(result && result.val) { + callback(error, result.val.toString()); + } else { + callback(error, null); + } + }); +}; + +Cache.prototype.delete = function(key, callback) { + this.memcached.delete(key, function(err) { + var error = errorCode.SUCCESS; + if(err) { + logger.error("error occurred when deleting value for " + key); + error = errorCode.FAILED; + } + callback(error); + }); +}; + +module.exports = Cache; \ No newline at end of file diff --git a/src/web_console/mini-poem/cache/redis.js b/src/web_console/mini-poem/cache/redis.js new file mode 100644 index 0000000..7d2f6b8 --- /dev/null +++ b/src/web_console/mini-poem/cache/redis.js @@ -0,0 +1,74 @@ +/** + * Created by strawmanbobi + * 2015-06-24. + */ + +require('../configuration/constants'); +var ErrorCode = require('../configuration/error_code'); +var Enums = require('../configuration/enums'); +var BaseCache = require('./base_cache.js'); + +var redis = require("redis"); + +var logger = require('../logging/logger4js').helper; + +var errorCode = new ErrorCode(); +var enums = new Enums(); + +var Cache = function(_host, _port, _user, _password) { + this.redisClient = redis.createClient({detect_buffers: true}); + // initialize client according to run-time ENV + // in _user indicates the redis instance:token pair value + if(null != _user) { + logger.info("Redis needs authorization"); + this.redisClient.auth(_user, redis.print); + } + logger.info("Redis client connected"); +}; + +Cache.prototype = Object.create(BaseCache.prototype); + +Cache.prototype.set = function(key, value, ttl, callback) { + this.redisClient.set(key, value, function(err) { + if(err) { + logger.error("Redis set value failed with key " + key); + callback(errorCode.FAILED); + } else { + logger.info("Redis set value successfully"); + callback(errorCode.SUCCESS); + } + }); +}; + +Cache.prototype.get = function(key, isBuffer, callback) { + if(true == isBuffer) { + this.redisClient.get(new Buffer(key), function (err, reply) { + if(err) { + logger.error("Redis get buffer failed with key " + key); + this.redisClient.end(); + callback(errorCode.FAILED, null); + } else { + logger.info("Redis get buffer successfully"); + this.redisClient.end(); + callback(errorCode.SUCCESS, reply); + } + }); + } else { + this.redisClient.get(key, function(err, reply) { + if(err) { + logger.error("Redis get value failed with key " + key); + this.redisClient.end(); + callback(errorCode.FAILED, null); + } else { + logger.info("Redis get value successfully"); + callback(errorCode.SUCCESS, reply); + } + }); + } +}; + +Cache.prototype.delete = function(key, callback) { + callback(errorCode.SUCCESS); +}; + +module.exports = Cache; \ No newline at end of file diff --git a/src/web_console/mini-poem/configuration/constants.js b/src/web_console/mini-poem/configuration/constants.js new file mode 100644 index 0000000..e649037 --- /dev/null +++ b/src/web_console/mini-poem/configuration/constants.js @@ -0,0 +1,70 @@ +/* + * Created by Strawmanbobi + * 2014-08-30 + */ + +// global constants describes the ability sets of the POEM framework + +global.VERSION = "0.0.4"; +global.ICODE = "PoEM~ V0.0.4"; + +// runtime environment +global.ENV = "dev"; +global.SERVER = 0; +global.LISTEN_PORT = "80"; + +// local environment +global.FILE_TEMP_PATH = ""; + +// db : MySQL +global.MYSQL_DB_SERVER_ADDRESS = "127.0.0.1"; +global.MYSQL_DB_NAME = "default_db"; +global.MYSQL_DB_USER = "root"; +global.MYSQL_DB_PASSWORD = "root"; + +// db : MongoDB +global.MONGO_DB_URI = ""; +global.MONGO_DB_SERVER_ADDRESS = "127.0.0.1"; +global.MONGO_DB_NAME = "default_db"; +global.MONGO_DB_USER = null; +global.MONGO_DB_PASSWORD = null; + +// data_set : Aliyun-OSS +global.OSS_HOST = "oss-cn-hangzhou.aliyuncs.com"; +global.OSS_PORT = "80"; +global.OSS_APP_ID = "T82nbipHSESmHzd8"; +global.OSS_APP_SECRET = "SOweQ8UVwCwPr2NC8EC89EOeKJc5Um"; +global.BUCKET_NAME = "strawmanbobi-beats"; + +// cache : memcached +global.MEMCACHED_HOST = ""; +global.MEMCACHED_PORT = ""; +global.MEMCACHED_SASL_USER = ""; +global.MEMCACHED_SASL_PASSWORD = ""; + +// sns : Weixin +global.WEIXIN_APP_ID = ""; +global.WEIXIN_APP_SECRET = ""; +global.WEIXIN_TOKEN = ""; + +// sns : facebook + +// external : python path +global.PYTHON_PATH = ""; + +// message : credential +global.PUSH_APP_KEY = ""; +global.PUSH_APP_SECRET = ""; + +// generic server configuration +global.SERVER_LISTEN_PORT = "8080"; +global.SERVER_ADDRESS = "127.0.0.1"; + +// OSS direct download bucket name +global.OSS_DIR_DOWN_PATH = ""; + +// incoming request security configuration +global.APP_ID = ""; +global.APP_TOKEN = ""; + +global.TOKEN_TTL = 60; diff --git a/src/web_console/mini-poem/configuration/enums.js b/src/web_console/mini-poem/configuration/enums.js new file mode 100644 index 0000000..a583330 --- /dev/null +++ b/src/web_console/mini-poem/configuration/enums.js @@ -0,0 +1,36 @@ +/* + * Created by Strawmanbobi + * 2014-08-30 + */ + +function Enums() { + this.APP_PRODUCTION_MODE = "production"; + this.APP_DEVELOPMENT_MODE = "development"; + this.APP_USERDEBUG_MODE = "userdebug"; + + this.SERVER_MAIN = 0; + + this.SCHEDULER_PERIODICAL = 0; + this.SCHEDULER_ONCE = 1; + + this.JPUSH_DEVICE_TYPE_IOS = 0; + this.JPUSH_DEVICE_TYPE_ANDROID = 1; + this.JPUSH_DEVICE_TYPE_BOTH = 2; + + this.JPUSH_DEST_TYPE_BROADCAST = 0; + this.JPUSH_DEST_TYPE_PEER = 1; + this.JPUSH_DEST_TYPE_GROUP = 2; + + this.JPUSH_PUSH_TYPE_MESSAGE = 0; + this.JPUSH_PUSH_TYPE_NOTIFICATION = 1; + + this.BC_API_MESSAGE_TYPE_MESSAGE = 0; + this.BC_API_MESSAGE_TYPE_NOTIFICATION = 1; + + this.BC_API_PUSH_TYPE_PEER = 0; + this.BC_API_PUSH_TYPE_BROADCAST = 1; + + this.ANDROID_STYPE_0 = 1; +} + +module.exports = Enums; \ No newline at end of file diff --git a/src/web_console/mini-poem/configuration/error_code.js b/src/web_console/mini-poem/configuration/error_code.js new file mode 100644 index 0000000..21dd158 --- /dev/null +++ b/src/web_console/mini-poem/configuration/error_code.js @@ -0,0 +1,24 @@ +/* + * Created by Strawmanbobi + * 2014-08-30 + */ + +function ErrorCode() { + this.SUCCESS = 0; + this.FAILED = -1; + + this.PYTHON_SCRIPT_SUCCESS = 0; + this.PYTHON_ARGUMENTS_ERROR = -1; + this.PYTHON_SCRIPT_PATH_NOT_SPECIFIED = -2; + this.PYTHON_CALLBACK_NOT_SPECIFIED = -3; + + this.WRONG_PUSH_DEVICE = -50; + this.WRONG_PUSH_TYPE = -51; + this.WRONG_PUSH_DESTINATION = -52; + + this.SNS_WEIXIN_VALIDATION_SUCCESS = 0; + this.SNS_WEIXIN_VALIDATION_FAILED = 1; + +} + +module.exports = ErrorCode; \ No newline at end of file diff --git a/src/web_console/mini-poem/data_set/ali_oss.js b/src/web_console/mini-poem/data_set/ali_oss.js new file mode 100644 index 0000000..882abf7 --- /dev/null +++ b/src/web_console/mini-poem/data_set/ali_oss.js @@ -0,0 +1,108 @@ +/* + * Created by Strawmanbobi + * 2014-08-30 + */ + +'use strict'; + +require('../configuration/constants'); +var ErrorCode = require('../configuration/error_code'); +var Enums = require('../configuration/enums'); + +var stringUtils = require('../utils/string_utils'); +var AliOSS = require('oss-client'); +var logger = require('../logging/logger4js').helper; + +var errorCode = new ErrorCode(); +var enums = new Enums(); + +var OSS = function(_host, _port, _accessKey, _accessSecret) { + this.option = { + accessKeyId: _accessKey || OSS_APP_ID, + accessKeySecret: _accessSecret || OSS_APP_SECRET, + host: _host, + port: _port + }; + this.ossClient = new AliOSS.OssClient(this.option); +}; + +OSS.prototype.saveObjectFromBinary = function(objectID, bufferContent, bucketName, contentType, callback) { + var randomID = stringUtils.randomChar(16); + console.log("object ID = " + objectID); + if(null == objectID || undefined == objectID) { + objectID = objectID || (null != contentType && + '' != contentType && + contentType.indexOf("/") >= 0) ? + randomID + '.' + contentType.substr(contentType.lastIndexOf('/') + 1) : + randomID; + } + logger.debug("save object " + objectID + " to bucket " + bucketName); + this.ossClient.putObject({ + bucket: bucketName, + object: objectID, + srcFile: bufferContent, + contentType: contentType + }, function (saveObjectErr, result) { + if(saveObjectErr) { + logger.debug("save object error : " + saveObjectErr); + callback(errorCode.FAILED, null); + } else { + logger.debug("save object successfully, result = " + JSON.stringify(result)); + logger.debug(objectID); + callback(errorCode.SUCCESS, objectID); + } + }); +}; + +OSS.prototype.getObjectByID = function(objectID, bucketName, callback) { + this.ossClient.listObject({ + bucket: bucketName, + prefix: '', + marker: objectID, + delimiter: '/', + maxKeys: 1 + }, function (getObjectErr, result) { + if(getObjectErr) { + logger.debug("get object error : " + getObjectErr); + callback(errorCode.FAILED, null); + } else { + logger.debug("list object successfully, result = " + JSON.stringify(result)); + callback(errorCode.SUCCESS, result); + } + }); +}; + +OSS.prototype.serveObjectByID = function(objectID, bucketName, res, callback) { + // pipe the binary stream to res + this.ossClient.getObject({ + bucket: bucketName, + object: objectID, + dstFile: res, + userHeaders: '' + }, function (getObjectErr, result) { + if(getObjectErr) { + callback(errorCode.FAILED, null); + } else { + callback(errorCode.SUCCESS, res); + } + }); +}; + +OSS.prototype.listObjects = function(from, count, bucketName, callback) { + this.ossClient.listObject({ + bucket: bucketName, + prefix: '', + marker: from, + delimiter: '/', + maxKeys: count + }, function (getObjectErr, result) { + if(getObjectErr) { + logger.debug("list object error : " + getObjectErr); + callback(errorCode.FAILED, null); + } else { + callback(errorCode.SUCCESS, result); + } + }); +}; + +module.exports = OSS; \ No newline at end of file diff --git a/src/web_console/mini-poem/external/python_caller.js b/src/web_console/mini-poem/external/python_caller.js new file mode 100644 index 0000000..b6f8b21 --- /dev/null +++ b/src/web_console/mini-poem/external/python_caller.js @@ -0,0 +1,83 @@ +/** + * Created by strawmanbobi + * 2015-08-03. + */ + +var pythonShell = require('python-shell'); + +var constants = require('../configuration/constants.js'); +var logger = require('../logging/logger4js').helper; + +var ErrorCode = require('../configuration/error_code.js'); + +var errorCode = new ErrorCode(); + +var PythonCaller = function() { + +}; + +/* + * Call python script from application + * + * input parameters : Script run-time base dir + * Script script filename + * User determined arguments ... + * Call back function + * + * return : Error code of python caller + */ +PythonCaller.prototype.call = function() { + var userArgIndex = 0; + var numArgs = arguments.length; + var callback = null; + var scriptPath = null; + var scriptName = null; + var userArguments = []; + if(numArgs < 3) { + logger.error("internal error while calling python script from application : no script specified"); + // TODO: specify the error code for this type of error + throw errorCode.PYTHON_ARGUMENTS_ERROR; + } else { + callback = arguments[numArgs - 1]; + if((typeof callback != 'function')) { + logger.error('internal error while calling python script from application : no callback specified'); + throw errorCode.PYTHON_CALLBACK_NOT_SPECIFIED; + } else { + scriptPath = arguments[0]; + scriptName = arguments[1]; + if(null == scriptPath || 'undefined' == scriptPath || null == scriptName || 'undefined' == scriptName) { + logger.error('internal error while calling python script from application : no script path specified'); + // TODO: specify the error code for this type of error + throw errorCode.PYTHON_SCRIPT_PATH_NOT_SPECIFIED; + } else { + // parse user arguments from python caller + var args = arguments[2]; + for(userArgIndex = 0; userArgIndex < args.length; userArgIndex++) { + userArguments.push(args[userArgIndex]); + } + // logger.info("user arguments = " + userArguments); + var options = { + mode: 'text', + pythonPath: PYTHON_PATH, + pythonOptions: ['-u'], + scriptPath: scriptPath, // the base path of python run-time + args: userArguments + }; + + pythonShell.run(scriptName, options, function (err, results) { + if (err) { + logger.error('python executing with error : ' + err); + callback(errorCode.FAILED, null); + } else { + // results is an array consisting of messages collected during execution + logger.info('python executed successfully, results = %j', results); + callback(errorCode.SUCCESS, results); + } + }); + return errorCode.PYTHON_SCRIPT_SUCCESS; + } + } + } +}; + +module.exports = PythonCaller; \ No newline at end of file diff --git a/src/web_console/mini-poem/http/request.js b/src/web_console/mini-poem/http/request.js new file mode 100644 index 0000000..03fea42 --- /dev/null +++ b/src/web_console/mini-poem/http/request.js @@ -0,0 +1,131 @@ +/** + * Created by Strawmanbobi + * 2014-08-30 + */ + +// system inclusion +var queryString = require('querystring'); +var http = require('http'); +var request = require('request'); + +// local inclusion +var Map = require('../mem/map.js'); +var ErrorCode = require('../configuration/error_code.js'); + +var errorCode = new ErrorCode(); + +var logger = require('../logging/logger4js').helper; + +/** + * + * @param _host : host of service server + * @param _port : port of service server + * @param _service : service URL parameter + * @param _queryParams : map of query parameters + * @constructor + */ +var Request = function(_host, _port, _service, _queryParams) { + this.host = _host; + this.port = _port; + this.service = _service; + this.queryParams = _queryParams; +}; + +Request.prototype.urlizeQueryParams = function() { + var i = 0; + var urlParams = ""; + var paramElement = null; + if(undefined == this.queryParams || null == this.queryParams) { + return ""; + } + if(this.queryParams instanceof Map) { + for(i = 0; i < this.queryParams.size(); i++) { + paramElement = this.queryParams.element(i); + if(0 == i) { + urlParams += "?"; + } else { + urlParams += "&"; + } + urlParams += paramElement.key + "=" + paramElement.value; + } + return urlParams; + } + return ""; +}; + +Request.prototype.sendGetRequest = function(options, callback) { + var data = ""; + var httpTag = options.https ? "https://" : "http://"; + var url = httpTag + this.host + ":" + this.port + this.service + + this.urlizeQueryParams(); + + if(options.https) { + request( + { method: 'GET' + , uri: url + }, function (error, response, body) { + if(!error && response.statusCode == '200') { + callback(errorCode.SUCCESS, JSON.parse(body)); + } else { + callback(errorCode.FAILED, null); + } + } + ) + } else { + http.get(url, function(res) { + res.on('data', function (chunk) { + data += chunk; + }); + res.on('end', function() { + if('200' == res.statusCode) { + callback(errorCode.SUCCESS, data); + } else { + console.error('HTTP request fault !!'); + callback(errorCode.FAILED, null); + } + }); + res.on('error', function(e) { + console.error("error occurred when handling response : " + e); + callback(errorCode.FAILED, null); + }); + }); + } +}; + +Request.prototype.sendPostRequest = function(bodyData, callback) { + var requestData = JSON.stringify(bodyData); + var url = this.service + + this.urlizeQueryParams(); + var options = { + host: this.host, + port: this.port, + path: url, + method: 'POST', + headers: { + 'Content-Type': 'application/json' + } + }; + + var req = http.request(options, function(res) { + var data = ''; + res.setEncoding('utf8'); + res.on('data', function (chunk) { + data += chunk; + }); + res.on('end', function() { + if('200' == res.statusCode) { + callback(errorCode.SUCCESS, data); + } else { + callback(errorCode.FAILED, null); + } + }); + }); + try { + req.write(requestData); + req.end(); + } catch(e) { + console.error("exception occurred in http request : " + e); + } +}; + +module.exports = Request; diff --git a/src/web_console/mini-poem/libs/JPush/JPush.js b/src/web_console/mini-poem/libs/JPush/JPush.js new file mode 100644 index 0000000..ba601bf --- /dev/null +++ b/src/web_console/mini-poem/libs/JPush/JPush.js @@ -0,0 +1,430 @@ +var JError = require('./JPushError'); +var Request = require('request'); +var JModel = require('./PushPayload'); + +var PUSH_API_URL = 'https://api.jpush.cn/v3/push'; +var REPORT_API_URL = 'https://report.jpush.cn/v3'; +var REPORT_RECEVIED = "/received"; +var REPORT_USER = "/users"; +var REPORT_MESSAGE = "/messages"; +var USER_AGENT = 'JPush-API-NodeJS-Client'; +var HOST_NAME_SSL = "https://device.jpush.cn"; +var DEVICE_PATH = "/v3/devices"; +var TAG_PATH = "/v3/tags"; +var ALIAS_PATH = "/v3/aliases"; +var VALIDATE = "/validate"; +var CONNECT_TIMEOUT = 5 * 1000; +var DEFAULT_MAX_RETRY_TIMES = 3; +var READ_TIMEOUT = 30 * 1000; +// Pattern +var PUSH_PATTERNS = /^[a-zA-Z0-9]{24}/; +var MSG_IDS_PATTERNS = /[^\d,]/; + +exports.buildClient = function(appKey, masterSecret, retryTimes, isDebug) { + if (arguments.length == 1 && typeof arguments[0] == 'object') { + var options = arguments[0]; + return new JPushClient(options.appKey, options.masterSecret, options.retryTimes, options.isDebug); + } else { + return new JPushClient(appKey, masterSecret, retryTimes, isDebug); + } +}; + +function JPushClient(appKey, masterSecret, retryTimes, isDebug) { + if (!appKey || !masterSecret) { + throw JError + .InvalidArgumentError('appKey and masterSecret are both required.'); + } + + if (typeof appKey !== 'string' || typeof masterSecret !== 'string' + || !PUSH_PATTERNS.test(appKey) || !PUSH_PATTERNS.test(masterSecret)) { + + throw new JError.InvalidArgumentError( + 'appKey and masterSecret format is incorrect. ' + + 'They should be 24 size, and be composed with alphabet and numbers. ' + + 'Please confirm that they are coming from JPush Web Portal.'); + + } + this.appkey = appKey; + this.masterSecret = masterSecret; + if (retryTimes) { + if (typeof retryTimes != 'number') { + throw JError.InvalidArgumentError("Invalid retryTimes."); + } + this.retryTimes = retryTimes; + } else { + this.retryTimes = DEFAULT_MAX_RETRY_TIMES; + } + if (isDebug != null) { + this.isDebug = isDebug; + } else { + this.isDebug = true; + } + +} + +/** + * create a push payload + * + * @returns {exports.PushPayload} + */ +function push() { + return new JModel.PushPayload(this); +} + +function sendPush(payload, callback) { + var header = { + 'User-Agent' : USER_AGENT, + 'Connection' : 'Keep-Alive', + 'Charset' : 'UTF-8', + 'Content-Type' : 'application/json' + }; + return _request(PUSH_API_URL, payload, header, { + user : this.appkey, + pass : this.masterSecret + }, 'POST', 1, this.retryTimes, this.isDebug, callback); +} + +function getReportReceiveds(msg_ids, callback) { + if (MSG_IDS_PATTERNS.test(msg_ids)) { + throw new JError.InvalidArgumentError( + 'Invalid msg_ids, msg_ids should be composed with alphabet and comma.'); + } + var header = { + 'User-Agent' : USER_AGENT, + 'Connection' : 'Keep-Alive', + 'Charset' : 'UTF-8', + 'Content-Type' : 'application/json' + }; + var url = REPORT_API_URL + REPORT_RECEVIED + '?msg_ids=' + msg_ids; + return _request(url, null, header, { + user : this.appkey, + pass : this.masterSecret + }, 'GET', 1, this.retryTimes, this.isDebug, callback); +} + +function getReportMessages(msg_ids, callback) { + if (MSG_IDS_PATTERNS.test(msg_ids)) { + throw new JError.InvalidArgumentError( + 'Invalid msg_ids, msg_ids should be composed with alphabet and comma.'); + } + var header = { + 'User-Agent' : USER_AGENT, + 'Connection' : 'Keep-Alive', + 'Charset' : 'UTF-8', + 'Content-Type' : 'application/json' + }; + var url = REPORT_API_URL + REPORT_MESSAGE + '?msg_ids=' + msg_ids; + return _request(url, null, header, { + user : this.appkey, + pass : this.masterSecret + }, 'GET', 1, this.retryTimes, this.isDebug, callback); +} + +function getReportUsers(timeUnit, start, duration, callback) { + var header = { + 'User-Agent' : USER_AGENT, + 'Connection' : 'Keep-Alive', + 'Charset' : 'UTF-8', + 'Content-Type' : 'application/json' + }; + var url = REPORT_API_URL + REPORT_USER + '?time_unit=' + timeUnit + '&start=' + start + '&duration=' + duration; + return _request(url, null, header, { + user : this.appkey, + pass : this.masterSecret + }, 'GET', 1, this.retryTimes, this.isDebug, callback); + +} +/** + * device api + * + * @param registrationId + */ +function getDeviceTagAlias(registrationId, callback) { + var header = { + 'User-Agent' : USER_AGENT, + 'Connection' : 'Keep-Alive', + 'Charset' : 'UTF-8', + 'Content-Type' : 'application/json' + }; + var url = HOST_NAME_SSL + DEVICE_PATH + "/" + registrationId; + return _request(url, null, header, { + user : this.appkey, + pass : this.masterSecret + }, 'GET', 1, this.retryTimes, this.isDebug, callback); +} + + +function updateDeviceTagAlias(registrationId, alias, clearTag, tagsToAdd, + tagsToRemove, callback) { + var header = { + 'User-Agent' : USER_AGENT, + 'Connection' : 'Keep-Alive', + 'Charset' : 'UTF-8', + 'Content-Type' : 'application/json' + }; + var url = HOST_NAME_SSL + DEVICE_PATH + "/" + registrationId; + if (tagsToAdd instanceof Array && tagsToRemove instanceof Array) { + var json = {}; + var tags = {}; + if (alias != null) { + json['alias'] = alias; + } + if (clearTag) { + json['tags'] = ''; + } else { + if (tagsToAdd != null && tagsToAdd.length > 0) { + tags['add'] = tagsToAdd + } + if (tagsToRemove != null && tagsToRemove.length > 0) { + tags['remove'] = tagsToRemove + } + json['tags'] = tags; + console.log(json) + } + } else { + throw new JError.InvalidArgumentError( + 'tagsToAdd or tagsToRemove type should be array'); + } + return _request(url, JSON.stringify(json), header, { + user : this.appkey, + pass : this.masterSecret + }, 'POST', 1, this.retryTimes, this.isDebug, callback); +} + +function getTagList(callback) { + var header = { + 'User-Agent' : USER_AGENT, + 'Connection' : 'Keep-Alive', + 'Charset' : 'UTF-8', + 'Content-Type' : 'application/json' + }; + var url = HOST_NAME_SSL + TAG_PATH ; + return _request(url, null, header, { + user : this.appkey, + pass : this.masterSecret + }, 'GET', 1, this.retryTimes, this.isDebug, callback); +} + +function isDeviceInTag(theTag, registrationID, callback) { + var header = { + 'User-Agent' : USER_AGENT, + 'Connection' : 'Keep-Alive', + 'Charset' : 'UTF-8', + 'Content-Type' : 'application/json' + }; + var url = HOST_NAME_SSL + TAG_PATH + "/" + theTag + + "/registration_ids/" + registrationID; + return _request(url, null, header, { + user : this.appkey, + pass : this.masterSecret + }, 'GET', 1, this.retryTimes, this.isDebug, callback); +} + +function addRemoveDevicesFromTag(theTag, toAddUsers, toRemoveUsers, callback) { + var header = { + 'User-Agent' : USER_AGENT, + 'Connection' : 'Keep-Alive', + 'Charset' : 'UTF-8', + 'Content-Type' : 'application/json' + }; + var url = HOST_NAME_SSL + TAG_PATH + "/" + theTag; + var registration_ids = {}; + if (null != toAddUsers && toAddUsers.length > 0) { + registration_ids['add'] = toAddUsers; + } + if (null != toRemoveUsers && toRemoveUsers.length > 0) { + registration_ids['remove'] = toRemoveUsers; + } + var json = {}; + json['registration_ids'] = registration_ids; + return _request(url, JSON.stringify(json), header, { + user : this.appkey, + pass : this.masterSecret + }, 'POST', 1, this.retryTimes, this.isDebug, callback); +} + +function deleteTag(theTag, platform, callback) { + var header = { + 'User-Agent' : USER_AGENT, + 'Connection' : 'Keep-Alive', + 'Charset' : 'UTF-8', + 'Content-Type' : 'application/json' + }; + var url = HOST_NAME_SSL + TAG_PATH + "/" + theTag; + if (null != platform) { + url += "/?platform=" + platform; + } + return _request(url, null, header, { + user : this.appkey, + pass : this.masterSecret + }, 'delete', 1, this.retryTimes, this.isDebug, callback); +} + +function getAliasDeviceList(alias, platform, callback) { + var header = { + 'User-Agent' : USER_AGENT, + 'Connection' : 'Keep-Alive', + 'Charset' : 'UTF-8', + 'Content-Type' : 'application/json' + }; + var url = HOST_NAME_SSL + ALIAS_PATH + "/" + alias; + if (null != platform) { + url += "/?platform=" + platform; + } + return _request(url, null, header, { + user : this.appkey, + pass : this.masterSecret + }, 'GET', 1, this.retryTimes, this.isDebug, callback); +} + +function deleteAlias(alias, platform, callback) { + var header = { + 'User-Agent' : USER_AGENT, + 'Connection' : 'Keep-Alive', + 'Charset' : 'UTF-8', + 'Content-Type' : 'application/json' + }; + var url = HOST_NAME_SSL + ALIAS_PATH + "/" + alias; + if (null != platform) { + url += "/?platform=" + platform; + } + return _request(url, null, header, { + user : this.appkey, + pass : this.masterSecret + }, 'delete', 1, this.retryTimes, this.isDebug, callback); +} + +function validate(payload, callback) { + var header = { + 'User-Agent' : USER_AGENT, + 'Connection' : 'Keep-Alive', + 'Charset' : 'UTF-8', + 'Content-Type' : 'application/json' + }; + return _request(PUSH_API_URL + VALIDATE, payload, header, { + user : this.appkey, + pass : this.masterSecret + }, 'POST', 1, this.retryTimes, this.isDebug, callback); +} + +function _request(url, body, headers, auth, method, times, maxTryTimes, isDebug, callback) { + if (isDebug) { + console.log("Push URL :" + url); + if (body) + console.log("Body :" + body); + console.log("Headers :" + JSON.stringify(headers)); + // console.log("Auth :" + JSON.stringify(auth)); + console.log("Method :" + method); + console.log("Times/MaxTryTimes : " + times + "/" + maxTryTimes); + } + + var _callback = function(err, res, body) { + if (err) { + if (err.code == 'ETIMEDOUT' && err.syscall != 'connect') { + // response timeout + return callback(new JError.APIConnectionError( + 'Response timeout. Your request to the server may have already received, please check whether or not to push', + true)); + } else if (err.code == 'ENOTFOUND') { + // unknown host + return callback(new JError.APIConnectionError('Known host : ' + + url)); + } + // other connection error + if (times < maxTryTimes) { + return _request(url, body, headers, auth, method, times + 1, + maxTryTimes, isDebug, callback); + } else { + return callback(new JError.APIConnectionError( + 'Connect timeout. Please retry later.')); + } + } + if (res.statusCode == 200) { + if (body.length != 0) { + if (isDebug) { + console.log("Push Success, response : " + body); + } + return callback(null, eval('(' + body + ')')); + } else { + if (isDebug) { + console.log("Push Success, response : " + body); + } + return callback(null, 200); + } + } else { + if (isDebug) { + console.log("Push Fail, HttpStatusCode: " + res.statusCode + + " result: " + body.toString()); + } + callback(new JError.APIRequestError(res.statusCode, body)); + } + }; + + if (method == 'POST' || method == 'post') { + Request.post({ + url : url, + body : body, + auth : { + user : auth.user, + pass : auth.pass + }, + headers : headers, + timeout : READ_TIMEOUT + }, _callback); + } + if (method == 'GET' || method == 'get') { + Request.get({ + url : url, + body : body, + auth : { + user : auth.user, + pass : auth.pass + }, + headers : headers, + timeout : READ_TIMEOUT + }, _callback); + } + + if (method == 'DELETE' || method == 'delete') { + Request.del({ + url : url, + body : body, + auth : { + user : auth.user, + pass : auth.pass + }, + headers : headers, + timeout : READ_TIMEOUT + }, _callback); + } +} + +JPushClient.prototype.sendPush = sendPush; +JPushClient.prototype.getReportReceiveds = getReportReceiveds; +JPushClient.prototype.push = push; +JPushClient.prototype.getDeviceTagAlias = getDeviceTagAlias; +JPushClient.prototype.updateDeviceTagAlias = updateDeviceTagAlias; +JPushClient.prototype.getTagList = getTagList; +JPushClient.prototype.isDeviceInTag = isDeviceInTag; +JPushClient.prototype.addRemoveDevicesFromTag = addRemoveDevicesFromTag; +JPushClient.prototype.deleteTag = deleteTag; +JPushClient.prototype.getAliasDeviceList = getAliasDeviceList; +JPushClient.prototype.deleteAlias = deleteAlias; +JPushClient.prototype.validate = validate; +JPushClient.prototype.getReportMessages = getReportMessages; +JPushClient.prototype.getReportUsers = getReportUsers; +// exports constants and methods +exports.ALL = JModel.ALL; +exports.DISABLE_SOUND = JModel.DISABLE_SOUND; +exports.DISABLE_BADGE = JModel.DISABLE_BADGE; +exports.tag = JModel.tag; +exports.tag_and = JModel.tag_and; +exports.alias = JModel.alias; +exports.registration_id = JModel.registration_id; +exports.ios = JModel.ios; +exports.android = JModel.android; +exports.winphone = JModel.winphone; +// error +exports.APIConnectionError = JError.APIConnectionError; +exports.APIRequestError = JError.APIRequestError; +exports.InvalidArgumentError = JError.InvalidArgumentError; diff --git a/src/web_console/mini-poem/libs/JPush/JPushError.js b/src/web_console/mini-poem/libs/JPush/JPushError.js new file mode 100644 index 0000000..f36cc5d --- /dev/null +++ b/src/web_console/mini-poem/libs/JPush/JPushError.js @@ -0,0 +1,33 @@ +/** + * JPush Error + */ + + +exports.APIConnectionError = APIConnectionError; +exports.APIRequestError = APIRequestError; +exports.InvalidArgumentError = InvalidArgumentError; + + +function APIConnectionError(message, isResponseTimeout) { + Error.call(this, message); + this.name = "APIConnectionError"; + this.message = message; + this.isResponseTimeout = isResponseTimeout || false; +} + +function APIRequestError(httpCode, response) { + var message = "Push Fail, HttpStatusCode: " + httpCode + " result: " + response.toString(); + Error.call(this, message); + this.name = "APIRequestError"; + this.message = message; + this.httpCode = httpCode; + this.response = response; + +} + + +function InvalidArgumentError(message) { + Error.call(this, message); + this.name = "InvalidArgumentError"; + this.message = message; +} diff --git a/src/web_console/mini-poem/libs/JPush/PushPayload.js b/src/web_console/mini-poem/libs/JPush/PushPayload.js new file mode 100644 index 0000000..15876f0 --- /dev/null +++ b/src/web_console/mini-poem/libs/JPush/PushPayload.js @@ -0,0 +1,468 @@ +/** + * PushPayload + */ + +var JError = require('./JPushError'); +var JUtil = require('./util'); + + +function PushPayload(client) { + this.client = client; + this.payload = {}; +} + + +function setPlatform() { + if (arguments.length < 1) { + throw new JError.InvalidArgumentError("platform's args cannot all be null"); + } + var platform, i; + if (arguments.length == 1 && arguments[0] === ALL) { + platform = ALL; + } else if (arguments.length == 1 && typeof arguments[0] == 'object') { + platform = []; + for(i=0; i 0) { + payload.push(tags_t[i].trim()); + } + } + if (payload.length < 1) { + throw new JError.InvalidArgumentError("Should be set at least ont " + title); + } + } else if (args.length == 1 && Array.isArray(args[0])) { + for (i=0; i< args[0].length; i++) { + if (typeof args[0][i] != 'string') { + throw new JError.InvalidArgumentError("Invalid " + title + ' at index ' + i + ', ' + title + ' can only be set to the String'); + } + payload.push(args[0][i]); + } + } else { + for (i=0; i1440 || big_push_duration <= 0) { + throw new JError.InvalidArgumentError("Invalid options.big_push_duration, it should bigger than 0 and less than 1440"); + } + options['big_push_duration'] = big_push_duration; + } + + this.payload = JUtil.extend(this.payload, {'options' : options}); + return this; + +} + +function toJSON() { + /* + if (this.payload.notification && this.payload.notification.ios) { + this.payload.notification.ios = JUtil.extend({'sound':'', badge:1}, this.payload.notification.ios); + } + */ + this.payload.options = JUtil.extend({'sendno':generateSendno(), 'apns_production':false}, this.payload.options); + + return JSON.stringify(this.payload); +} + +function send(callback) { + validate(this.payload); + var body = this.toJSON(); + return this.client.sendPush(body, callback); +} + +function sendValidate(callback) { + validate(this.payload); + var body = this.toJSON(); + return this.client.validate(body, callback); +} +/** + * Verify the payload legitimacy, it will call by this.send() + * @param payload + */ +function validate(payload) { + var notification = payload.notification, + message = payload.message; + if (!notification && !message) { + throw new JError.InvalidArgumentError('Either or both notification and message must be set.'); + } +} + +function calculateLength(str) { + var ch, st, re = []; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); + st = []; + do { + st.push( ch & 0xFF ); + ch = ch >> 8; + } + while ( ch ); + re = re.concat( st.reverse() ); + } + // return an array of bytes + return re.length; +} + +function isIosExceedLength() { + var ios, + notification = this.payload.notification, + message = this.payload.message; + var alert = notification.alert ? notification.alert : ''; + ios = calculateLength(JSON.stringify(JUtil.extend({'alert': alert}, notification.ios))); + + if (message != null) { + var msgLen = calculateLength(JSON.stringify(message)); + return msgLen >= 1000; + } + return ios >= 2000; +} + +function isGlobalExceedLength(){ + var android = 0, winphone = 0, ios = false; + var notification = this.payload.notification, + message = this.payload.message, + platform = this.payload.platform; + + var hasIOS = true; + if (platform != ALL) { + hasIOS = false; + for (var i=0; i 1000 || android > 1000; +} + + + + +// ------ PushPayload prototype +PushPayload.prototype.setPlatform = setPlatform; +PushPayload.prototype.setAudience = setAudience; +PushPayload.prototype.setNotification = setNotification; +PushPayload.prototype.setMessage = setMessage; +PushPayload.prototype.setOptions = setOptions; +PushPayload.prototype.toJSON = toJSON; +PushPayload.prototype.send = send; +PushPayload.prototype.isIosExceedLength = isIosExceedLength; +PushPayload.prototype.isGlobalExceedLength = isGlobalExceedLength; +PushPayload.prototype.sendValidate = sendValidate; +// ------ private constant define ------ +var VALID_DEVICE_TYPES = ["ios", "android", "winphone"]; +var DISABLE_SOUND = 'DISABLE_SOUND' +var DISABLE_BADGE = -1; +var MIN_SENDNO = 100000; +var MAX_SENDNO = 4294967294; +var ALL = 'all'; + +// ------ exports constants and methods ------- +exports.ALL = ALL; +exports.DISABLE_SOUND = DISABLE_SOUND; +exports.DISABLE_BADGE = DISABLE_BADGE; +exports.tag = tag; +exports.tag_and = tag_and; +exports.alias = alias; +exports.registration_id = registration_id; +exports.ios = ios; +exports.android = android; +exports.winphone = winphone; +//class +exports.PushPayload = PushPayload; + + + + diff --git a/src/web_console/mini-poem/libs/JPush/util.js b/src/web_console/mini-poem/libs/JPush/util.js new file mode 100644 index 0000000..e96c2e5 --- /dev/null +++ b/src/web_console/mini-poem/libs/JPush/util.js @@ -0,0 +1,79 @@ +/* extend start */ +var extend, + _extend, + _isObject; + +_isObject = function(o){ + return Object.prototype.toString.call(o) === '[object Object]'; +} + +_extend = function self(destination, source) { + var property; + for (property in destination) { + if (destination.hasOwnProperty(property)) { + + // 若destination[property]和sourc[property]都是对象,则递归 + if (_isObject(destination[property]) && _isObject(source[property])) { + self(destination[property], source[property]); + }; + + // 若sourc[property]已存在,则跳过 + if (source.hasOwnProperty(property)) { + continue; + } else { + source[property] = destination[property]; + } + } + } +} + +extend = function(){ + var arr = arguments, + result = {}, + i; + + if (!arr.length) return {}; + + for (i = arr.length - 1; i >= 0; i--) { + if (_isObject(arr[i])) { + _extend(arr[i], result); + }; + } + + arr[0] = result; + return result; +} + +exports.extend = extend; + +/* extend end */ + +/* sendRequest start */ + +exports.sendRequest = function(url, payload, appkey, masterSecret, callback) { + var done = function (err, res, body) { + if (err) return callback(err); + + if (res.statusCode == 200) { + callback(null, JSON.parse(payload)); + } else { + callback({ + statusCode: res.statusCode, + body: JSON.parse(body) + }) + } + + request.post({ + url: url, + body: JSON.stringify(postBody), + auth: { + user: options.appkey, + pass: options.masterSecret + }, + timeout: options.timeout || 60000 //default 1 min timeout + }, done) + + }; +} + +/* sendRequest end */ \ No newline at end of file diff --git a/src/web_console/mini-poem/logging/logger4js.js b/src/web_console/mini-poem/logging/logger4js.js new file mode 100644 index 0000000..76d76c7 --- /dev/null +++ b/src/web_console/mini-poem/logging/logger4js.js @@ -0,0 +1,121 @@ +/** + * Created by donna + * 2014-08-30 + */ + +require('../configuration/constants'); +var Enums = require('../configuration/enums'); +var log4js = require('log4js'); +var enums = new Enums(); + +var helper = helper || {}; +exports.helper = helper; + +var logRoot = "./logs/"; +var userDebugLogFolder = "user_debug/"; +var devLogFolder = "dev/"; +var productionLogFolder = "production/"; +var logFile = "common.log"; + +log4js.configure({ + "appenders": [ + { + type: 'console', + category: "console" + }, + { + type: "dateFile", + filename: logRoot + productionLogFolder + logFile, + pattern: "-yyyy-MM-dd", + alwaysIncludePattern: false, + maxLogSize: 1024, + category: 'userProductionLog' + }, + { + type: "dateFile", + filename: logRoot + userDebugLogFolder + logFile, + pattern: "-yyyy-MM-dd", + alwaysIncludePattern: false, + maxLogSize: 1024, + category: 'userDebugLog' + }, + { + type: "dateFile", + filename: logRoot + devLogFolder + logFile, + pattern: "-yyyy-MM-dd", + alwaysIncludePattern: false, + maxLogSize: 1024, + category: 'userDevelopmentLog' + } + ], + replaceConsole: true, + levels: { + userProductionLog: 'INFO', + userDebugLog: 'INFO', + userDevelopmentLog: 'INFO' + } +}); + +var userProductionLog = log4js.getLogger('userProductionLog'); +var userDebugLog = log4js.getLogger('userDebugLog'); +var userDevelopmentLog = log4js.getLogger('userDevelopmentLog'); + +helper.info = function (msg) { + if(enums.APP_DEVELOPMENT_MODE == ENV) { + console.log(msg); + } else if(enums.APP_PRODUCTION_MODE == ENV) { + userProductionLog.info(msg); + } else { + userDebugLog.info(msg); + } +}; + +helper.error = function (msg) { + if(enums.APP_DEVELOPMENT_MODE == ENV) { + console.log(msg); + } else if(enums.APP_PRODUCTION_MODE == ENV) { + userProductionLog.error(msg); + } else { + userDebugLog.error(msg); + } +}; + +helper.warn = function (msg) { + if(enums.APP_DEVELOPMENT_MODE == ENV) { + console.log(msg); + } else if(enums.APP_PRODUCTION_MODE == ENV) { + userProductionLog.warn(msg); + } else { + userDebugLog.warn(msg); + } +}; + +helper.debug = function (msg) { + if(enums.APP_DEVELOPMENT_MODE == ENV) { + console.log(msg); + } else if(enums.APP_PRODUCTION_MODE == ENV) { + userProductionLog.debug(msg); + } else { + userDebugLog.debug(msg); + } +}; + +helper.trace = function (msg) { + if(enums.APP_DEVELOPMENT_MODE == ENV) { + console.log(msg); + } else if(enums.APP_PRODUCTION_MODE == ENV) { + userProductionLog.trace(msg); + } else { + userDebugLog.trace(msg); + } +}; + +helper.fatal = function (msg) { + if(enums.APP_DEVELOPMENT_MODE == ENV) { + console.log(msg); + } else if(enums.APP_PRODUCTION_MODE == ENV) { + userProductionLog.fatal(msg); + } else { + userDebugLog.fatal(msg); + } +}; \ No newline at end of file diff --git a/src/web_console/mini-poem/mem/map.js b/src/web_console/mini-poem/mem/map.js new file mode 100644 index 0000000..cd4763d --- /dev/null +++ b/src/web_console/mini-poem/mem/map.js @@ -0,0 +1,120 @@ +/* + * Created by Strawmanbobi + * 2014-08-30 + */ + +function Map() { + this.elements = []; + + this.size = function() { + return this.elements.length; + }; + + this.isEmpty = function() { + return (this.elements.length < 1); + }; + + this.clear = function() { + this.elements = []; + }; + + this.put = function(_key, _value) { + this.elements.push( { + key : _key, + value : _value + }); + }; + + this.remove = function(_key) { + var bln = false; + try { + for (i = 0; i < this.elements.length; i++) { + if (this.elements[i].key == _key) { + this.elements.splice(i, 1); + return true; + } + } + } catch (e) { + bln = false; + } + return bln; + }; + + this.get = function(_key) { + try { + for (i = 0; i < this.elements.length; i++) { + if (this.elements[i].key == _key) { + return this.elements[i].value; + } + } + } catch (e) { + return null; + } + }; + + this.set = function(_key, _value) { + for(i = 0; i < this.elements.length; i++) { + if (this.elements[i].key == _key) { + this.elements[i].value = _value; + return; + } + } + this.elements.push({ + key : _key, + value : _value + }); + }; + + this.element = function(_index) { + if (_index < 0 || _index >= this.elements.length) { + return null; + } + return this.elements[_index]; + }; + + this.containsKey = function(_key) { + var bln = false; + try { + for (i = 0; i < this.elements.length; i++) { + if (this.elements[i].key == _key) { + bln = true; + } + } + } catch (e) { + bln = false; + } + return bln; + }; + + this.containsValue = function(_value) { + var bln = false; + try { + for (i = 0; i < this.elements.length; i++) { + if (this.elements[i].value == _value) { + bln = true; + } + } + } catch (e) { + bln = false; + } + return bln; + }; + + this.values = function() { + var arr = []; + for (i = 0; i < this.elements.length; i++) { + arr.push(this.elements[i].value); + } + return arr; + }; + + this.keys = function() { + var arr = []; + for (i = 0; i < this.elements.length; i++) { + arr.push(this.elements[i].key); + } + return arr; + } +} + +module.exports = Map; \ No newline at end of file diff --git a/src/web_console/mini-poem/msg_service/notification_helper.js b/src/web_console/mini-poem/msg_service/notification_helper.js new file mode 100644 index 0000000..5720d72 --- /dev/null +++ b/src/web_console/mini-poem/msg_service/notification_helper.js @@ -0,0 +1,283 @@ +/** + * Created by Strawmanbobi + * 2014-08-31 + */ + +require('../configuration/constants'); +var ErrorCode = require('../configuration/error_code'); +var Enums = require('../configuration/enums'); + +var ciphering = require('../security/md5'); +var stringUtils = require('../utils/string_utils'); +var Map = require('../mem/map'); +var querystring = require('querystring'); +var apn = require('apn'); +var http = require('http'); + +var logger = require('../logging/logger4js').helper; + +var errorCode = new ErrorCode(); +var enums = new Enums(); + +var JPush = require("../libs/JPush/JPush.js"); +/** + * + * @param _appKey : APP KEY for push server + * @param _port : APP SECRET for push server + * @constructor + */ +var PushClient = function(_appKey, _appMasterSecret) { + this.appKey = _appKey; + this.appMasterSecret = _appMasterSecret; + this.client = JPush.buildClient(this.appKey, this.appMasterSecret); +}; + +// global parameters +var gMessageTTL = 60 * 10; + +/** + * Push message via JPUSH + * @param conversationID + * @param pushType + * @param deviceTypes + * @param message + * @param sound + * @param badge + * @param silent + * @param title + * @param custom + * @param callback + */ +PushClient.prototype.pushMessageViaJPush = function (conversationID, destType, pushType, deviceTypes, + message, sound, badge, silent, title, custom, callback) { + logger.debug("conversationID = " + conversationID + ", destType = " + destType + ", deviceType = " + deviceTypes + + ", message = " + message); + + var devices = null; + var audience = null; + + // set target platform + if(enums.JPUSH_DEVICE_TYPE_IOS == deviceTypes) { + devices = 'ios'; + } else if(enums.JPUSH_DEVICE_TYPE_ANDROID == deviceTypes) { + devices = 'android'; + } else if(enums.JPUSH_DEVICE_TYPE_BOTH == deviceTypes) { + devices = JPush.ALL; + } else { + logger.error("Wrong push device types required"); + callback(errorCode.WRONG_PUSH_DEVICE); + } + + // set audience + if(enums.JPUSH_DEST_TYPE_BROADCAST == destType) { + audience = JPush.ALL; + } else if(enums.JPUSH_DEST_TYPE_PEER == destType) { + audience = JPush.registration_id(conversationID); + } else if(enums.JPUSH_DEST_TYPE_GROUP == destType) { + audience = JPush.tag(conversationID); + } else { + logger.error("Wrong push audience required"); + callback(errorCode.WRONG_PUSH_DESTINATION); + } + + logger.debug("devices: " + devices + ", audience: " + audience); + + if (enums.JPUSH_PUSH_TYPE_MESSAGE == pushType) { + this.client.push().setPlatform(devices) + .setAudience(audience) + .setMessage(message) + .setOptions(null, gMessageTTL, null, true, null) + .send(function(err, res) { + if (err) { + logger.error("failed to send message via JPush, error = " + err.message); + callback(errorCode.FAILED); + } else { + logger.info("succeeded to send message via JPush, sendNo = " + res.sendno + + ", messageID = " + res.msg_id); + callback(errorCode.SUCCESS); + } + }); + } else if (enums.JPUSH_PUSH_TYPE_NOTIFICATION == pushType) { + this.client.push().setPlatform(devices) + .setAudience(audience) + .setNotification( + JPush.android(message, title, enums.ANDROID_STYPE_0, custom), + JPush.ios(message, sound, badge, silent, custom) + ) + .setOptions(null, gMessageTTL, null, true, null) + .send(function(err, res) { + if (err) { + logger.error("failed to send message via JPush, error = " + err.message); + callback(errorCode.FAILED); + } else { + logger.info("succeeded to send message via JPush, sendNo = " + res.sendno + + ", messageID = " + res.msg_id); + callback(errorCode.SUCCESS); + } + }); + } else { + logger.error("invalid push type : " + pushType); + callback(errorCode.WRONG_PUSH_TYPE); + } +}; + +/** + * Push message via Baidu Channel API + * @param conversationID + * @param conversationChannel + * @param deviceType + * @param messageType + * @param pushType + * @param messageTitle + * @param messageDescription + * @param callback + * spec: exception handler needed + */ +PushClient.prototype.pushViaBaiduChannelAPI = function (conversationID, conversationChannel, deviceType, messageType, pushType, + messageTitle, messageDescription, callback) { + var messageBody = ""; + + // adjust parameters + // TODO: to fix the URIEncode issue + if(enums.BC_API_MESSAGE_TYPE_MESSAGE == messageType) { + messageBody = encodeURI(messageDescription); + } else if(enums.BC_API_MESSAGE_TYPE_NOTIFICATION == messageType) { + messageBody = "{\"title\":\"" + messageTitle + "\",\"description\":\"" + messageDescription + "\"}"; + } else { + throw "Wrong Message Type"; + } + + if(enums.BC_API_PUSH_TYPE_PEER && (null == conversationID || null == conversationChannel)) { + throw "Wrong Conversation ID or Channel"; + } + + // prepare parameter map and base URL + var parameterMap = new Map(); + var baiduChannelAPIPushMsgURL = "https://api.tuisong.baidu.com/rest/3.0/"; + + // fill parameters according to BAIDU CHANNEL API Spec + parameterMap.put("apikey", this.appKey); + parameterMap.put("method", "push_msg"); + parameterMap.put("channel_id", conversationChannel); + parameterMap.put("user_id", conversationID); + parameterMap.put("device_type", deviceType); + var timeStamp = Math.round(new Date().getTime() / 1000); + parameterMap.put("timestamp", timeStamp); + parameterMap.put("messages", messageBody); + parameterMap.put("message_type", messageType); + parameterMap.put("push_type", pushType); + parameterMap.put("msg_keys", utils.randomChar(16)); + + // sort parameters and sign + parameterMap.sortByKey('A'); + var signPlainText = "POSThttp://" + "api.tuisong.baidu.com" + "/rest/3.0/"; + var parameterArray = parameterMap.getArray(); + for (var i = 0; i < parameterArray.length; i++) { + signPlainText += parameterArray[i].key + "=" + parameterArray[i].value; + } + signPlainText += this.appMasterSecret; + // logger.debug("plain text of sign string = " + signPlainText); + + var signText = ciphering.MD5(encodeURIComponent(signPlainText)); + // logger.debug(signText); + + // construct final URL string + for (var i = 0; i < parameterArray.length; i++) { + if (0 == i) { + baiduChannelAPIPushMsgURL += "?"; + } else { + baiduChannelAPIPushMsgURL += "&"; + } + baiduChannelAPIPushMsgURL += parameterArray[i].key + "=" + parameterArray[i].value; + } + + baiduChannelAPIPushMsgURL += "&sign=" + signText; + // logger.debug("baidu push url = " + baiduChannelAPIPushMsgURL); + + var postData = querystring.stringify({ + }); + + var androidPushOptions = { + host: "api.tuisong.baidu.com", + port: "433", + path: baiduChannelAPIPushMsgURL, + method: 'POST', + headers: { + 'Content-Length': postData.length + } + }; + + var req = http.request(androidPushOptions, function (res) { + var data = ''; + res.setEncoding('utf8'); + res.on('data', function (chunk) { + data += chunk; + }); + res.on('end', function () { + if ('200' == res.statusCode) { + logger.debug("baidu push request successfully made"); + callback(errorCode.SUCCESS); + } else { + logger.debug('baidu push request failed, status code = ' + res.statusCode + " error detail = " + data); + callback(errorCode.FAILED); + } + }); + }); + + try { + req.write(postData); + req.end(); + } catch(e) { + logger.error("exception occurred while making HTTP request : " + e); + req.end(); + callback(errorCode.FAILED); + } +}; + +/** + * Push message to IOS devices via Apple official APN + * @param deviceToken + * @param expiry + * @param alert + * @param sound + * @param payload + * @param callback + * spec: exception handler needed + */ +PushClient.prototype.pushViaAppleAPN = function(deviceToken, expiry, alert, sound, payload, callback) { + var options = null; + if(enums.APP_PRODUCTION_MODE == ENV) { + option = { + "cert": "./certs/push_cert_production.pem", + "key": "./certs/push_key_production.pem", + "gateway": "gateway.sandbox.push.apple.com", + "port": "2195" + }; + } else if(enums.APP_DEVELOPMENT_MODE == ENV) { + options = { + "cert": "./certs/push_cert_dev.pem", + "key": "./certs/push_key_dev.pem", + "gateway": "gateway.sandbox.push.apple.com", + "port": "2195" + }; + } else { + throw "Wrong ENV"; + } + var apnConnection = new apn.Connection(options), + device = new apn.Device(deviceToken), + note = new apn.Notification(); + note.expiry = Math.floor(Date.now() / 1000) + (3600 | expiry); + note.badge = 3; + note.alert = alert; + note.sound = 'default' | sound; + note.payload = payload; + note.device = device; + + apnConnection.pushNotification(note, device); + + if(callback) { + callback(option, note, device); + } +}; + +module.exports = PushClient; \ No newline at end of file diff --git a/src/web_console/mini-poem/security/md5.js b/src/web_console/mini-poem/security/md5.js new file mode 100644 index 0000000..400591a --- /dev/null +++ b/src/web_console/mini-poem/security/md5.js @@ -0,0 +1,192 @@ +/** + * Created by Strawmanbobi + * 2014-08-31 + */ + +function MD5(sMessage, fullSize) { + function RotateLeft(lValue, iShiftBits) { + return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits)); + } + + function AddUnsigned(lX, lY) { + var lX4, lY4, lX8, lY8, lResult; + lX8 = (lX & 0x80000000); + lY8 = (lY & 0x80000000); + lX4 = (lX & 0x40000000); + lY4 = (lY & 0x40000000); + lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF); + if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8); + if (lX4 | lY4) { + if (lResult & 0x40000000) return (lResult ^ 0xC0000000 ^ lX8 ^ lY8); + else return (lResult ^ 0x40000000 ^ lX8 ^ lY8); + } else return (lResult ^ lX8 ^ lY8); + } + + function F(x, y, z) { + return (x & y) | ((~x) & z); + } + + function G(x, y, z) { + return (x & z) | (y & (~z)); + } + + function H(x, y, z) { + return (x ^ y ^ z); + } + + function I(x, y, z) { + return (y ^ (x | (~z))); + } + + function FF(a, b, c, d, x, s, ac) { + a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac)); + return AddUnsigned(RotateLeft(a, s), b); + } + + function GG(a, b, c, d, x, s, ac) { + a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac)); + return AddUnsigned(RotateLeft(a, s), b); + } + + function HH(a, b, c, d, x, s, ac) { + a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac)); + return AddUnsigned(RotateLeft(a, s), b); + } + + function II(a, b, c, d, x, s, ac) { + a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac)); + return AddUnsigned(RotateLeft(a, s), b); + } + + function ConvertToWordArray(sMessage) { + var lWordCount; + var lMessageLength = sMessage.length; + var lNumberOfWords_temp1 = lMessageLength + 8; + var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64; + var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16; + var lWordArray = Array(lNumberOfWords - 1); + var lBytePosition = 0; + var lByteCount = 0; + while (lByteCount < lMessageLength) { + lWordCount = (lByteCount - (lByteCount % 4)) / 4; + lBytePosition = (lByteCount % 4) * 8; + lWordArray[lWordCount] = (lWordArray[lWordCount] | (sMessage.charCodeAt(lByteCount) << lBytePosition)); + lByteCount++; + } + lWordCount = (lByteCount - (lByteCount % 4)) / 4; + lBytePosition = (lByteCount % 4) * 8; + lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition); + lWordArray[lNumberOfWords - 2] = lMessageLength << 3; + lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29; + return lWordArray; + } + + function WordToHex(lValue) { + var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount; + for (lCount = 0; lCount <= 3; lCount++) { + lByte = (lValue >>> (lCount * 8)) & 255; + WordToHexValue_temp = "0" + lByte.toString(16); + WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2); + } + return WordToHexValue; + } + + var x = Array(); + var k, AA, BB, CC, DD, a, b, c, d + var S11 = 7, S12 = 12, S13 = 17, S14 = 22; + var S21 = 5, S22 = 9 , S23 = 14, S24 = 20; + var S31 = 4, S32 = 11, S33 = 16, S34 = 23; + var S41 = 6, S42 = 10, S43 = 15, S44 = 21; +// Steps 1 and 2. Append padding bits and length and convert to words + x = ConvertToWordArray(sMessage); +// Step 3. Initialise + a = 0x67452301; + b = 0xEFCDAB89; + c = 0x98BADCFE; + d = 0x10325476; +// Step 4. Process the message in 16-word blocks + for (k = 0; k < x.length; k += 16) { + AA = a; + BB = b; + CC = c; + DD = d; + a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478); + d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756); + c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB); + b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE); + a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF); + d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A); + c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613); + b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501); + a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8); + d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF); + c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1); + b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE); + a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122); + d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193); + c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E); + b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821); + a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562); + d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340); + c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51); + b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA); + a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D); + d = GG(d, a, b, c, x[k + 10], S22, 0x2441453); + c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681); + b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8); + a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6); + d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6); + c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87); + b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED); + a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905); + d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8); + c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9); + b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A); + a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942); + d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681); + c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122); + b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C); + a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44); + d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9); + c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60); + b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70); + a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6); + d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA); + c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085); + b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05); + a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039); + d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5); + c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8); + b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665); + a = II(a, b, c, d, x[k + 0], S41, 0xF4292244); + d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97); + c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7); + b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039); + a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3); + d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92); + c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D); + b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1); + a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F); + d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0); + c = II(c, d, a, b, x[k + 6], S43, 0xA3014314); + b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1); + a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82); + d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235); + c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB); + b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391); + a = AddUnsigned(a, AA); + b = AddUnsigned(b, BB); + c = AddUnsigned(c, CC); + d = AddUnsigned(d, DD); + } +// Step 5. Output the 128 bit digest + var temp; + if (undefined != fullSize && null != fullSize) { + temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d); + } else { + temp = WordToHex(a) + WordToHex(b) + WordToHex(c); + } + return temp.toLowerCase(); +} + +exports.MD5 = MD5; \ No newline at end of file diff --git a/src/web_console/mini-poem/sns/weixin.js b/src/web_console/mini-poem/sns/weixin.js new file mode 100644 index 0000000..6b56747 --- /dev/null +++ b/src/web_console/mini-poem/sns/weixin.js @@ -0,0 +1,167 @@ +/** + * Created by strawmanbobi on 2014-11-12. + */ + +var crypto = require('crypto'); +var Map = require('../mem/map.js'); +var RequestSender = require('../http/request.js'); +var ErrorCode = require('../configuration/error_code.js'); +var errorCode = new ErrorCode(); + +var logger = require('../logging/logger4js').helper; + +var WEIXIN_API_SERVER = "api.weixin.qq.com"; +var WEIXIN_API_PORT = "443"; + +var WEIXIN_API_FETCH_ACCESS_TOKEN = "/sns/oauth2/access_token"; +var WEIXIN_API_FETCH_USER_INFO = "/sns/userinfo"; +var OPEN_WEIXIN_API_FETCH_ACCESS_TOKEN = "/cgi-bin/token"; +var OPEN_WEIXIN_API_FETCH_TICKET = "/cgi-bin/ticket/getticket"; + +var Weixin = function(_appID, _appSecret, _accessToken) { + this.appID = _appID; + this.appSecret = _appSecret; + this.accessToken = _accessToken; +}; + +Weixin.prototype.accessValidate = function(signature, timestamp, nonce, callback) { + if(this.checkSource(signature, timestamp, nonce)) { + callback(errorCode.SNS_WEIXIN_VALIDATION_SUCCESS); + } else { + callback(errorCode.SNS_WEIXIN_VALIDATION_FAILED); + } +}; + +Weixin.prototype.processUserMsg = function(message, callback) { + // TODO: + callback(errorCode.SUCCESS, ""); +}; + +Weixin.prototype.fetchAccessToken = function(code, callback) { + var queryParams = new Map(); + queryParams.put("appid", this.appID); + queryParams.put("secret", this.appSecret); + queryParams.put("code", code); + queryParams.put("grant_type", "authorization_code"); + var requestSender = new RequestSender(WEIXIN_API_SERVER, WEIXIN_API_PORT, WEIXIN_API_FETCH_ACCESS_TOKEN, queryParams); + + var options = { + https: true + }; + requestSender.sendGetRequest(options, function(error, data) { + if(errorCode.FAILED == error) { + logger.error("failed to get weixin access token"); + callback(error, null); + } else { + if(data.errcode) { + logger.error("weixin access token got error, please check the cause : " + data.errcode); + callback(errorCode.FAILED, null); + } else { + logger.info("weixin access token got : " + data); + callback(errorCode.SUCCESS, data); + } + } + }); +}; + +Weixin.prototype.fetchUserInfo = function(accessToken, openID, callback) { + var queryParams = new Map(); + queryParams.put("access_token", accessToken); + queryParams.put("openid", openID); + queryParams.put("lang", "zh_CN"); + var requestSender = new RequestSender(WEIXIN_API_SERVER, WEIXIN_API_PORT, WEIXIN_API_FETCH_USER_INFO, queryParams); + + var options = { + https: true + }; + requestSender.sendGetRequest(options, function(error, data) { + if(errorCode.FAILED == error) { + logger.error("failed to get weixin user info"); + callback(error, null); + } else { + if(data.errcode) { + logger.error("weixin user info got error, please check the cause : " + data.errcode); + callback(errorCode.FAILED, null); + } else { + logger.info("weixin user info got : " + data); + callback(errorCode.SUCCESS, data); + } + } + }); +}; + +Weixin.prototype.fetchOpenWxAccessToken = function(callback) { + var queryParams = new Map(); + queryParams.put("appid", this.appID); + queryParams.put("secret", this.appSecret); + queryParams.put("grant_type", "client_credential"); + var requestSender = new RequestSender(WEIXIN_API_SERVER, WEIXIN_API_PORT, OPEN_WEIXIN_API_FETCH_ACCESS_TOKEN, queryParams); + + var options = { + https: true + }; + requestSender.sendGetRequest(options, function(error, data) { + if(errorCode.FAILED == error) { + logger.error("failed to get weixin access token"); + callback(error, null); + } else { + if(data.errcode) { + logger.error("open weixin access token got error, please check the cause : " + data.errcode); + callback(errorCode.FAILED, null); + } else { + logger.info("open weixin access token got : " + data); + callback(errorCode.SUCCESS, data); + } + } + }); +}; + +Weixin.prototype.fetchJsApiTicket = function(accessToken, callback) { + var queryParams = new Map(); + queryParams.put("access_token", accessToken); + queryParams.put("type", "jsapi"); + var requestSender = new RequestSender(WEIXIN_API_SERVER, WEIXIN_API_PORT, OPEN_WEIXIN_API_FETCH_TICKET, queryParams); + + var options = { + https: true + }; + requestSender.sendGetRequest(options, function(error, data) { + if(errorCode.FAILED == error) { + logger.error("failed to get weixin jsapi ticket"); + callback(error, null); + } else { + if(data.errcode) { + logger.error("open weixin jsapi ticket got error, please check the cause : " + data.errcode); + callback(errorCode.FAILED, null); + } else { + logger.info("open weixin jsapi ticket got : " + data); + callback(errorCode.SUCCESS, data); + } + } + }); +}; + +Weixin.prototype.fetchSignature = function(nonceStr, timeStamp, url, jsApiTicket, callback) { + // debug on + // console.log("nonceStr = " + nonceStr); + // console.log("timeStamp = " + timeStamp); + // console.log("url = " + url); + // console.log("jsApiTicket = " + jsApiTicket); + + var shasum = crypto.createHash('sha1'); + var src = "jsapi_ticket=" + jsApiTicket + "&noncestr=" + nonceStr + "×tamp=" + timeStamp + "&url=" + url; + shasum.update(src, 'utf-8'); + var digest = shasum.digest('hex'); + + // console.log("weixin signature fetched : " + digest); + callback(errorCode.SUCCESS, digest); +}; + +Weixin.prototype.checkSource = function (signature, timestamp, nonce) { + var shasum = crypto.createHash('sha1'), + arr = [this.accessToken, timestamp, nonce]; + shasum.update(arr.sort().join(''), 'utf-8'); + return shasum.digest('hex') == signature; +}; + +module.exports = Weixin; diff --git a/src/web_console/mini-poem/timing/scheduler.js b/src/web_console/mini-poem/timing/scheduler.js new file mode 100644 index 0000000..8f7e3ca --- /dev/null +++ b/src/web_console/mini-poem/timing/scheduler.js @@ -0,0 +1,25 @@ +/** + * Created by Strawmanbobi + * 2015-11-04 + */ + +var later = require("later"); +var logger = require('../logging/logger4js').helper; +var Enums = require("../configuration/enums"); +var ErrorCode = require("../configuration/error_code"); + +var enums = new Enums(); +var errorCode = new ErrorCode(); + +var Scheduler = function() { +}; + +Scheduler.prototype.startTimer = function(timing, callback) { + setTimeout(callback, timing); +}; + +Scheduler.prototype.startPeriodicalTask = function(timing, callback) { + setInterval(callback, timing); +}; + +module.exports = Scheduler; \ No newline at end of file diff --git a/src/web_console/mini-poem/utils/date_utils.js b/src/web_console/mini-poem/utils/date_utils.js new file mode 100644 index 0000000..dabc81d --- /dev/null +++ b/src/web_console/mini-poem/utils/date_utils.js @@ -0,0 +1,111 @@ +/* + * Created by Strawmanbobi + * 2014-08-30 + */ + +function formatDate(date, fmt) { + var o = { + "M+" : date.getMonth() + 1, + "d+" : date.getDate(), + "h+" : date.getHours(), + "m+" : date.getMinutes(), + "s+" : date.getSeconds(), + "q+" : Math.floor((date.getMonth() + 3) / 3), + "S" : date.getMilliseconds() + }; + if(/(y+)/.test(fmt)) + fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length)); + for(var k in o) + if(new RegExp("("+ k +")").test(fmt)) + fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); + return fmt; +} + +function getNextDay(dateString) { + var nextDayStr; + var nextMonthStr; + var nextYearStr; + var currentDate = new Date(dateString); + var nextDate = new Date(currentDate.getTime() + 24 * 60 * 60 * 1000); + var nextDay = nextDate.getDate(); + if(nextDay < 10) { + nextDayStr = "0" + nextDay; + } else { + nextDayStr = nextDay; + } + var nextMonth = nextDate.getMonth() + 1; + if(nextMonth < 10) { + nextMonthStr = "0" + nextMonth; + } else { + nextMonthStr = nextMonth; + } + nextYearStr = nextDate.getFullYear(); + return nextYearStr + "-" + nextMonthStr + "-" + nextDayStr; +} + +function getPreviousDay(dateString) { + var lastDayStr; + var lastMonthStr; + var lastYearStr; + var currentDate = new Date(dateString); + var lastDate = new Date(currentDate.getTime() - 24 * 60 * 60 * 1000); + var lastDay = lastDate.getDate(); + if(lastDay < 10) { + lastDayStr = "0" + lastDay; + } else { + lastDayStr = lastDay; + } + var lastMonth = lastDate.getMonth() + 1; + if(lastMonth < 10) { + lastMonthStr = "0" + lastMonth; + } else { + lastMonthStr = lastMonth; + } + lastYearStr = lastDate.getFullYear(); + return lastYearStr + "-" + lastMonthStr + "-" + lastDayStr; +} + +function getDateDiffer(startTime, endTime, diffType) { + startTime = startTime.replace(/\-/g, "/"); + endTime = endTime.replace(/\-/g, "/"); + + diffType = diffType.toLowerCase(); + var sTime = new Date(startTime); + var eTime = new Date(endTime); + var divNum = 1; + switch (diffType) { + case "second": + divNum = 1000; + break; + case "minute": + divNum = 1000 * 60; + break; + case "hour": + divNum = 1000 * 3600; + break; + case "day": + divNum = 1000 * 3600 * 24; + break; + default: + break; + } + return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum)); +} + +function dateDiff(sDate1, sDate2) { + + var aDate, oDate1, oDate2, iDays; + aDate = sDate1.split("-"); + oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]); //转换为yyyy-MM-dd格式 + aDate = sDate2.split("-"); + oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]); + iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数 + + return iDays; +} + +exports.getNextDay = getNextDay; +exports.getPreviousDay = getPreviousDay; +exports.getDateDiffer = getDateDiffer; +exports.formatDate = formatDate; +exports.dateDiff = dateDiff; \ No newline at end of file diff --git a/src/web_console/mini-poem/utils/map.js b/src/web_console/mini-poem/utils/map.js new file mode 100644 index 0000000..497c24b --- /dev/null +++ b/src/web_console/mini-poem/utils/map.js @@ -0,0 +1,120 @@ +/** + * Created by Strawmanbobi + * 2014-03-14 + */ + +var Map = function() { + this.elements = []; +}; + +Map.prototype.size = function() { + return this.elements.length; +}; + +Map.prototype.isEmpty = function() { + return (this.elements.length < 1); +}; + +Map.prototype.clear = function() { + this.elements = []; +}; + +Map.prototype.put = function(_key, _value) { + this.elements.push( { + key : _key, + value : _value + }); +}; + +Map.prototype.remove = function(_key) { + var bln = false; + try { + for (i = 0; i < this.elements.length; i++) { + if (this.elements[i].key == _key) { + this.elements.splice(i, 1); + return true; + } + } + } catch (e) { + bln = false; + } + return bln; +}; + +Map.prototype.get = function(_key) { + try { + for (i = 0; i < this.elements.length; i++) { + if (this.elements[i].key == _key) { + return this.elements[i].value; + } + } + } catch (e) { + return null; + } +}; + +Map.prototype.set = function(_key, _value) { + for(i = 0; i < this.elements.length; i++) { + if (this.elements[i].key == _key) { + this.elements[i].value = _value; + return; + } + } + this.elements.push({ + key : _key, + value : _value + }); +}; + +Map.prototype.element = function(_index) { + if (_index < 0 || _index >= this.elements.length) { + return null; + } + return this.elements[_index]; +}; + +Map.prototype.containsKey = function(_key) { + var bln = false; + try { + for (i = 0; i < this.elements.length; i++) { + if (this.elements[i].key == _key) { + bln = true; + } + } + } catch (e) { + bln = false; + } + return bln; +}; + +Map.prototype.containsValue = function(_value) { + var bln = false; + try { + for (i = 0; i < this.elements.length; i++) { + if (this.elements[i].value == _value) { + bln = true; + } + } + } catch (e) { + bln = false; + } + return bln; +}; + +Map.prototype.values = function() { + var arr = []; + for (i = 0; i < this.elements.length; i++) { + arr.push(this.elements[i].value); + } + return arr; +}; + +Map.prototype.keys = function() { + var arr = []; + for (i = 0; i < this.elements.length; i++) { + arr.push(this.elements[i].key); + } + return arr; +}; + +module.exports = Map; \ No newline at end of file diff --git a/src/web_console/mini-poem/utils/object_reflection.js b/src/web_console/mini-poem/utils/object_reflection.js new file mode 100644 index 0000000..01bde4e --- /dev/null +++ b/src/web_console/mini-poem/utils/object_reflection.js @@ -0,0 +1,22 @@ +/* + * Created by Strawmanbobi + * 2014-08-30 + */ + +function objectMemberCount(conditions) { + var memberCount = 0; + for(var f in conditions) { + memberCount++; + } + var whereClause = ""; + var index = 0; + for(var field in conditions) { + whereClause += field + " = '" + conditions[field] + "'"; + if(index < memberCount - 1) { + whereClause += " AND "; + } + } + return whereClause; +} + +module.exports = objectMemberCount; \ No newline at end of file diff --git a/src/web_console/mini-poem/utils/string_utils.js b/src/web_console/mini-poem/utils/string_utils.js new file mode 100644 index 0000000..945a764 --- /dev/null +++ b/src/web_console/mini-poem/utils/string_utils.js @@ -0,0 +1,38 @@ +exports.randomChar = function(l) { + var x = "0123456789qwertyuioplkjhgfdsazxcvbnm"; + var tmp = ""; + for(var i = 0;i < l; i++) { + tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length); + } + return tmp; +}; + +exports.randomNumber = function(l) { + var x = "0123456789"; + var tmp = ""; + for(var i = 0;i < l; i++) { + tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length); + } + return tmp; +}; + +exports.validateEmail = function (email) { + var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + return re.test(email); +}; + +function rnd() { + var today = new Date(); + var seed = today.getTime(); + seed = (seed * 9301 + 49297) % 233280; + return seed / (233280.0); +} + +function cr(number) { + return Math.ceil(rnd() * number); +} + +function isNumber() { + var r = /^[0-9]*[1-9][0-9]*$/; + return r.test(str); +} \ No newline at end of file diff --git a/src/web_console/mini-poem/utils/system_utils.js b/src/web_console/mini-poem/utils/system_utils.js new file mode 100644 index 0000000..49a891d --- /dev/null +++ b/src/web_console/mini-poem/utils/system_utils.js @@ -0,0 +1,32 @@ +/* + * Created by Strawmanbobi + * 2015-03-02 + */ + +var dateUtils = require('./date_utils'); +var platform = require('platform'); +var UAParser = require('ua-parser-js'); + +function startup(expressApp, port, serverName) { + if(expressApp && expressApp.listen && typeof(expressApp.listen) == "function") { + expressApp.listen(port); + + console.log(serverName +' restful webservice server is listening at port : ' + + port + " //" + dateUtils.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss")); + console.log("driven by " + ICODE); + } +} + +function getOS() { + return platform.os; +} + +function getUAInfo(ua) { + var parser = new UAParser(); + var result = parser.setUA(ua).getResult(); + return result; +} + +exports.startup = startup; +exports.getOS = getOS; +exports.getUAInfo = getUAInfo; \ No newline at end of file diff --git a/src/web_console/model/admin_dao.js b/src/web_console/model/admin_dao.js index b2c2303..d760c2c 100644 --- a/src/web_console/model/admin_dao.js +++ b/src/web_console/model/admin_dao.js @@ -4,9 +4,9 @@ */ // global inclusion -var orm = require('../../../Infrastructure/BackEnd/node_modules/orm'); -var dbOrm = require('../../../Infrastructure/BackEnd/db/mysql/mysql_connection').mysqlDB; -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; +var orm = require('orm'); +var dbOrm = require('../mini-poem/db/mysql/mysql_connection').mysqlDB; +var logger = require('../mini-poem/logging/logger4js').helper; // local inclusion var ErrorCode = require('../configuration/error_code'); diff --git a/src/web_console/model/brand_dao.js b/src/web_console/model/brand_dao.js index 7639f62..6d1e2a9 100644 --- a/src/web_console/model/brand_dao.js +++ b/src/web_console/model/brand_dao.js @@ -4,10 +4,10 @@ */ // global inclusion -var orm = require('../../../Infrastructure/BackEnd/node_modules/orm'); -var dbOrm = require('../../../Infrastructure/BackEnd/db/mysql/mysql_connection').mysqlDB; -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; -var dateUtils = require('../../../Infrastructure/BackEnd/utils/date_utils.js'); +var orm = require('orm'); +var dbOrm = require('../mini-poem/db/mysql/mysql_connection').mysqlDB; +var logger = require('../mini-poem/logging/logger4js').helper; +var dateUtils = require('../mini-poem/utils/date_utils.js'); // local inclusion var ErrorCode = require('../configuration/error_code'); diff --git a/src/web_console/model/category_dao.js b/src/web_console/model/category_dao.js index b62c834..046c26c 100644 --- a/src/web_console/model/category_dao.js +++ b/src/web_console/model/category_dao.js @@ -4,10 +4,10 @@ */ // global inclusion -var orm = require('../../../Infrastructure/BackEnd/node_modules/orm'); -var dbOrm = require('../../../Infrastructure/BackEnd/db/mysql/mysql_connection').mysqlDB; -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; -var dateUtils = require('../../../Infrastructure/BackEnd/utils/date_utils.js'); +var orm = require('orm'); +var dbOrm = require('../mini-poem/db/mysql/mysql_connection').mysqlDB; +var logger = require('../mini-poem/logging/logger4js').helper; +var dateUtils = require('../mini-poem/utils/date_utils.js'); // local inclusion var ErrorCode = require('../configuration/error_code'); diff --git a/src/web_console/model/city_dao.js b/src/web_console/model/city_dao.js index ac9629d..7e1aa3d 100644 --- a/src/web_console/model/city_dao.js +++ b/src/web_console/model/city_dao.js @@ -4,9 +4,9 @@ */ // global inclusion -var orm = require('../../../Infrastructure/BackEnd/node_modules/orm'); -var dbOrm = require('../../../Infrastructure/BackEnd/db/mysql/mysql_connection').mysqlDB; -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; +var orm = require('orm'); +var dbOrm = require('../mini-poem/db/mysql/mysql_connection').mysqlDB; +var logger = require('../mini-poem/logging/logger4js').helper; // local inclusion var ErrorCode = require('../configuration/error_code'); diff --git a/src/web_console/model/ir_protocol_dao.js b/src/web_console/model/ir_protocol_dao.js index b8d79b6..dfa082d 100644 --- a/src/web_console/model/ir_protocol_dao.js +++ b/src/web_console/model/ir_protocol_dao.js @@ -4,9 +4,9 @@ */ // global inclusion -var orm = require('../../../Infrastructure/BackEnd/node_modules/orm'); -var dbOrm = require('../../../Infrastructure/BackEnd/db/mysql/mysql_connection').mysqlDB; -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; +var orm = require('orm'); +var dbOrm = require('../mini-poem/db/mysql/mysql_connection').mysqlDB; +var logger = require('../mini-poem/logging/logger4js').helper; // local inclusion var ErrorCode = require('../configuration/error_code'); diff --git a/src/web_console/model/remote_index_dao.js b/src/web_console/model/remote_index_dao.js index 2f10cf0..2272570 100644 --- a/src/web_console/model/remote_index_dao.js +++ b/src/web_console/model/remote_index_dao.js @@ -4,9 +4,9 @@ */ // global inclusion -var orm = require('../../../Infrastructure/BackEnd/node_modules/orm'); -var dbOrm = require('../../../Infrastructure/BackEnd/db/mysql/mysql_connection').mysqlDB; -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; +var orm = require('orm'); +var dbOrm = require('../mini-poem/db/mysql/mysql_connection').mysqlDB; +var logger = require('../mini-poem/logging/logger4js').helper; // local inclusion var ErrorCode = require('../configuration/error_code'); diff --git a/src/web_console/model/stb_operator_dao.js b/src/web_console/model/stb_operator_dao.js index 604cc6b..8d9e102 100644 --- a/src/web_console/model/stb_operator_dao.js +++ b/src/web_console/model/stb_operator_dao.js @@ -4,9 +4,9 @@ */ // global inclusion -var orm = require('../../../Infrastructure/BackEnd/node_modules/orm'); -var dbOrm = require('../../../Infrastructure/BackEnd/db/mysql/mysql_connection').mysqlDB; -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; +var orm = require('orm'); +var dbOrm = require('../mini-poem/db/mysql/mysql_connection').mysqlDB; +var logger = require('../mini-poem/logging/logger4js').helper; // local inclusion var ErrorCode = require('../configuration/error_code'); diff --git a/src/web_console/model/virtual_remote_dao.js b/src/web_console/model/virtual_remote_dao.js index 51dc047..d45eac3 100644 --- a/src/web_console/model/virtual_remote_dao.js +++ b/src/web_console/model/virtual_remote_dao.js @@ -4,9 +4,9 @@ */ // global inclusion -var kvConn = require('../../../Infrastructure/BackEnd/db/mongodb/mongodb_connection'); -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; -var Map = require('../../../Infrastructure/BackEnd/mem/map'); +var kvConn = require('../mini-poem/db/mongodb/mongodb_connection'); +var logger = require('../mini-poem/logging/logger4js').helper; +var Map = require('../mini-poem/mem/map'); // local inclusion var ErrorCode = require('../configuration/error_code'); diff --git a/src/web_console/routes/certificate_routes.js b/src/web_console/routes/certificate_routes.js index 55092b2..d363f2f 100644 --- a/src/web_console/routes/certificate_routes.js +++ b/src/web_console/routes/certificate_routes.js @@ -3,7 +3,7 @@ * 2015-11-12 */ -var app = require('../yk_console.js'); +var app = require('../irext_console.js'); var certificateService = require('../services/certificate_service.js'); app.get('/yuekong/certificate/confirm_pw', certificateService.confirmPassword); diff --git a/src/web_console/routes/index.js b/src/web_console/routes/index.js index d53efda..9d177a6 100644 --- a/src/web_console/routes/index.js +++ b/src/web_console/routes/index.js @@ -3,9 +3,8 @@ * 2015-01-22 */ -var server = require('../yk_console.js'); +var server = require('../irext_console.js'); require('./internal_routes.js'); require('./certificate_routes.js'); -require('./push_routes.js'); require('./stat_routes.js'); \ No newline at end of file diff --git a/src/web_console/routes/internal_routes.js b/src/web_console/routes/internal_routes.js index 60628e0..5289029 100644 --- a/src/web_console/routes/internal_routes.js +++ b/src/web_console/routes/internal_routes.js @@ -3,7 +3,7 @@ * 2015-01-22. */ -var app = require('../yk_console.js'); +var app = require('../irext_console.js'); var intService = require('../services/internal_service.js'); app.get('/yuekong/int/list_provinces', intService.listProvinces); diff --git a/src/web_console/routes/stat_routes.js b/src/web_console/routes/stat_routes.js index 7b612f6..71482a8 100644 --- a/src/web_console/routes/stat_routes.js +++ b/src/web_console/routes/stat_routes.js @@ -2,7 +2,7 @@ * Created by Strawmanbobi * 2016-05-29. */ -var app = require('../yk_console.js'); +var app = require('../irext_console.js'); var statService = require('../services/stat_service.js'); app.get('/yuekong/stat/generic_count', statService.genericCount); diff --git a/src/web_console/script_npm.sh b/src/web_console/script_npm.sh new file mode 100644 index 0000000..72de534 --- /dev/null +++ b/src/web_console/script_npm.sh @@ -0,0 +1,46 @@ +# run this script before you setup the irext web console +echo "running script of npm install needed by irext..." + +echo "npm install express" +npm install express + +echo "npm install body-parser" +npm install body-parser + +echo "npm install method-override" +npm install method-override + +echo "npm install platform" +npm install platform + +echo "npm install ua-parser-js" +npm install ua-parser-js + +echo "npm install log4js" +npm install log4js + +echo "npm install formidable" +npm install formidable + +echo "npm install orm" +npm install orm + +echo "npm install python-shell" +npm install python-shell + +echo "npm install oss-client" +npm install oss-client + +echo "npm install request" +npm install request + +echo "npm install async" +npm install async + +echo "npm install aliyun-sdk" +npm install aliyun-sdk + +echo "npm install nodemailer" +npm install nodemailer + +echo "npm install done" \ No newline at end of file diff --git a/src/web_console/services/certificate_service.js b/src/web_console/services/certificate_service.js index fa2eacc..ea80897 100644 --- a/src/web_console/services/certificate_service.js +++ b/src/web_console/services/certificate_service.js @@ -4,13 +4,13 @@ */ // system inclusion -var constants = require('../../../Infrastructure/BackEnd/configuration/constants'); +var constants = require('../mini-poem/configuration/constants'); // local inclusion var ServiceResponse = require('../response/service_response.js'); var LoginResponse = require('../response/login_response.js'); -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; +var logger = require('../mini-poem/logging/logger4js').helper; var certificateLogic = require('../work_unit/certificate_logic.js'); diff --git a/src/web_console/services/internal_service.js b/src/web_console/services/internal_service.js index dc5e42c..98b9ba3 100644 --- a/src/web_console/services/internal_service.js +++ b/src/web_console/services/internal_service.js @@ -4,7 +4,7 @@ */ // system inclusion -var constants = require('../../../Infrastructure/BackEnd/configuration/constants'); +var constants = require('../mini-poem/configuration/constants'); var formidable = require('formidable'); var fs = require('fs'); @@ -16,10 +16,8 @@ var ProtocolResponse = require('../response/protocol_response.js'); var CityResponse = require('../response/city_response.js'); var OperatorResponse = require('../response/operator_response.js'); var RemoteIndexResponse = require('../response/remote_index_response.js'); -var VersionResponse = require('../response/version_response.js'); -var StatResponse = require('../response/stat_response.js'); -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; +var logger = require('../mini-poem/logging/logger4js').helper; var internalLogic = require('../work_unit/internal_logic.js'); diff --git a/src/web_console/services/stat_service.js b/src/web_console/services/stat_service.js index 71b0e8d..d679d16 100644 --- a/src/web_console/services/stat_service.js +++ b/src/web_console/services/stat_service.js @@ -4,7 +4,7 @@ */ // system inclusion -var constants = require('../../../Infrastructure/BackEnd/configuration/constants'); +var constants = require('../mini-poem/configuration/constants'); var formidable = require('formidable'); var fs = require('fs'); @@ -13,7 +13,7 @@ var ServiceResponse = require('../response/service_response.js'); var StatResponse = require('../response/stat_response.js'); var IntegerResponse = require('../response/integer_response'); -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; +var logger = require('../mini-poem/logging/logger4js').helper; var statLogic = require('../work_unit/stat_logic.js'); diff --git a/src/web_console/work_unit/certificate_logic.js b/src/web_console/work_unit/certificate_logic.js index 82e111d..cb46d6e 100644 --- a/src/web_console/work_unit/certificate_logic.js +++ b/src/web_console/work_unit/certificate_logic.js @@ -3,17 +3,17 @@ * 2015-11-12 */ -var Constants = require('../../../Infrastructure/BackEnd/configuration/constants'); +var Constants = require('../mini-poem/configuration/constants'); var Admin = require('../model/admin_dao.js'); var AdminAuth = require('../authority/admin_auth.js'); -var MD5 = require('../../../Infrastructure/BackEnd/security/md5.js'); -var StringUtils = require('../../../Infrastructure/BackEnd/utils/string_utils.js'); +var MD5 = require('../mini-poem/security/md5.js'); +var StringUtils = require('../mini-poem/utils/string_utils.js'); var nodemailer = require('nodemailer'); var Enums = require('../configuration/enums.js'); var ErrorCode = require('../configuration/error_code.js'); -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; +var logger = require('../mini-poem/logging/logger4js').helper; var enums = new Enums(); var errorCode = new ErrorCode(); diff --git a/src/web_console/work_unit/internal_logic.js b/src/web_console/work_unit/internal_logic.js index 92222b3..e6fc780 100644 --- a/src/web_console/work_unit/internal_logic.js +++ b/src/web_console/work_unit/internal_logic.js @@ -8,10 +8,10 @@ fs = require('fs'); var crypto = require('crypto'); // global inclusion -var orm = require('../../../Infrastructure/BackEnd/node_modules/orm'); -var Constants = require('../../../Infrastructure/BackEnd/configuration/constants'); -var PythonCaller = require('../../../Infrastructure/BackEnd/external/python_caller'); -var OSS = require('../../../Infrastructure/BackEnd/data_set/ali_oss.js'); +var orm = require('orm'); +var Constants = require('../mini-poem/configuration/constants'); +var PythonCaller = require('../mini-poem/external/python_caller'); +var OSS = require('../mini-poem/data_set/ali_oss.js'); var Category = require('../model/category_dao.js'); var Brand = require('../model/brand_dao.js'); @@ -19,16 +19,14 @@ var IRProtocol = require('../model/ir_protocol_dao.js'); var City = require('../model/city_dao.js'); var RemoteIndex = require('../model/remote_index_dao.js'); var StbOperator = require('../model/stb_operator_dao.js'); -var Version = require('../model/version_dao.js'); var Admin = require('../model/admin_dao.js'); -var VirtualBleRemoteIndex = require('../model/virtual_ble_remote_index_dao.js'); -var RequestSender = require('../../../Infrastructure/BackEnd/http/request.js'); -var Map = require('../../../Infrastructure/BackEnd/mem/map.js'); +var RequestSender = require('../mini-poem/http/request.js'); +var Map = require('../mini-poem/mem/map.js'); var Enums = require('../configuration/enums.js'); var ErrorCode = require('../configuration/error_code.js'); -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; +var logger = require('../mini-poem/logging/logger4js').helper; var enums = new Enums(); var errorCode = new ErrorCode(); diff --git a/src/web_console/work_unit/stat_logic.js b/src/web_console/work_unit/stat_logic.js index 7634e05..a8edcfc 100644 --- a/src/web_console/work_unit/stat_logic.js +++ b/src/web_console/work_unit/stat_logic.js @@ -4,15 +4,15 @@ */ // global inclusion -require('../../../Infrastructure/BackEnd/configuration/constants'); -var RequestSender = require('../../../Infrastructure/BackEnd/http/request.js'); -var Map = require('../../../Infrastructure/BackEnd/mem/map.js'); +require('../mini-poem/configuration/constants'); +var RequestSender = require('../mini-poem/http/request.js'); +var Map = require('../mini-poem/mem/map.js'); // local inclusion var Enums = require('../configuration/enums.js'); var ErrorCode = require('../configuration/error_code.js'); -var logger = require('../../../Infrastructure/BackEnd/logging/logger4js').helper; +var logger = require('../mini-poem/logging/logger4js').helper; var enums = new Enums(); var errorCode = new ErrorCode();