Пример #1
0
 def initRedis(self):
     # set redis config and create redis pool
     host = self.config.get('redis', 'HOST')
     pwd = self.config.get('redis', 'PASSWORD')
     port = self.config.get('redis', 'PORT')
     Redis.init(host, pwd, int(port))
     log.info('redis[%s:%s:%s] init success', host, port, pwd)
Пример #2
0
 def initDb(self):
     # mongodb及oss配置
     if self.config.has_option('global', 'db'):
         Db.name = self.config.get('global', 'db')
     if self.config.has_option('mongodb', 'ADDR'):
         addr = self.config.get('mongodb', 'ADDR')
         MongoDb.init(addr)
         self.initMongodbIndex()
         log.info('mongodb[%s] init success', addr)
Пример #3
0
 def initMongodbIndex(self):
     db = MongoDb()
     haveIndex = {}
     for classname in BaseConfig.projectClass:
         try:
             haveIndex[classname] = db.listIndex(classname)
             if {"_sid": 1} not in haveIndex[classname]:
                 db.index(classname, [("_sid", 1)])
                 log.info("classname:%s, index:%s", classname, json.dumps([("_sid", 1)]))
         except Exception, e:
             log.err("Error:%s, error:%s", classname, str(e))
Пример #4
0
 def initHandlers(self):
     handlers = [
         ('/1.0/class/(\\w+)/(\\w+)',
          'mecloud.api.ClassHandler.ClassHandler'),
         ('/1.0/class/(\\w+)', 'mecloud.api.ClassHandler.ClassHandler'),
         ('/1.0/query/(\\w+)',
          'mecloud.api.QueryCountHandler.QueryCountHandler'),
         ('/1.0/query/', 'mecloud.api.QueryCountHandler.QueryCountHandler'),
         ('/1.0/user/(\\w+)', 'mecloud.api.UserHandler.UserHandler'),
         ('/1.0/user/', 'mecloud.api.UserHandler.UserHandler'),
         ('/1.0/file/', 'mecloud.api.FileHandler.FileHandler'),
         ('/1.0/file/(\\w+)', 'mecloud.api.FileHandler.FileHandler'),
         ('/1.0/upload/(\\w+)',
          'mecloud.api.CmsFileUploadHandler.CmsFileUploadHandler'),
         ('/1.0/file/download/(\\w+)',
          'mecloud.api.FileDownloadHandler.FileDownloadHandler'),
         ('/sms/(.+)', 'mecloud.api.SMSHandler.SMSHandler'),
         ('/captcha/(.+)', 'mecloud.api.CaptchaHandler.CaptchaHandler'),
         ('/wx/(\\w+)', 'mecloud.api.WxHandler.WxHandler'),
         ('/1.0/follow/(\\w+)/(\\w+)/(\\d+)',
          'mecloud.api.FollowerHandler.FollowerHandler'),
         ('/1.0/follow/(\\w+)',
          'mecloud.api.FollowerHandler.FollowerHandler'),
         ('/statcount/query',
          'mecloud.api.StatCountHandler.StatCountHandler'),
         ('/1.0/black/(\\w+)/(\\w+)/(\\d+)',
          'mecloud.api.BlacklistHandler.BlacklistHandler'),
         ('/1.0/thirdpay/(\w+)', 'mecloud.api.PayHandler.PayHandler'),
         ('/1.0/pay/(\w+)', 'mecloud.api.PayHandler.PayHandler'),
         ('/1.0/wxpaycallback',
          'mecloud.api.WxCallbackHandler.WxCallbackHandler'),
         ('/1.0/alipaycallback',
          'mecloud.api.AlipayCallbackHandler.AlipayCallbackHandler'),
         ('/1.0/manager/(\w+)',
          'mecloud.api.CmsInviteCodeHandler.CmsInviteCodeHandler')
     ]
     if self.config.has_section('handlers'):
         urls = self.config.options('handlers')
         for url in urls:
             handle = (url, self.config.get('handlers', url))
             log.info('new handler: %s' % str(handle))
             handlers.append(handle)
     return handlers
Пример #5
0
 def sentMessage(self, obj):
     item = self.autoMessage.get((self.className, self.method), None)
     if not item:
         return
     userClassHelper = ClassHelper("UserInfo")
     userInfo = userClassHelper.find_one({"user": self.userId},
                                         {'nickName': 1})
     if not userInfo:
         return
     obj.update(userInfo)
     title = item['title'].format(**obj)
     template = item['template'].format(**obj)
     # TODO
     pushData = {"userid": obj['to'], "title": title, "text": template}
     log.info("Push Data:%s", json.dumps(pushData))
     try:
         res = requests.post(self.pushUrl,
                             data=json.dumps(pushData),
                             headers={'X-MeCloud-Debug': '1'})
         print res.text
     except Exception, ex:
         log.err("Push Err:%s", ex)
Пример #6
0
    def loginWithoutPwd(self):
        obj = json.loads(self.request.body)
        if not checkKeys(obj, ['username']):
            self.write(ERR_PARA.message)
            return

        user = MeUser(self.appName, obj)
        userHelper = ClassHelper('develop', 'User')
        userInfo = userHelper.get(self.appInfo['user'])
        # library授权
        if userInfo['type'] == 2:
            if user['bundleId']:
                log.info("Library User[%s] Auth. bundleId[%s]",
                         user['username'], user['bundleId'])
            elif user['package']:
                log.info("Library User[%s] Auth. package[%s]",
                         user['username'], user['package'])
            log.info('auth app[%s]', self.appInfo['appName'])
        # 普通授权失败
        elif user['bundleId'] != None:
            if (not self.appInfo.has_key('bundleId')
                ) or self.appInfo['bundleId'] != user['bundleId']:
                log.err('[%s] bundleId[%s] not match. LoginWithoutPwd Error.',
                        self.appInfo['appName'], user['bundleId'])
                self.write(ERR_UNAUTHORIZED.message)
                return
            log.info('auth app[%s]', self.appInfo['appName'])
        elif user['package']:
            if (not self.appInfo.has_key('package')
                ) or self.appInfo['package'] != user['package']:
                log.err('[%s] package[%s] not match. LoginWithoutPwd Error.',
                        self.appInfo['appName'], user['package'])
                self.write(ERR_UNAUTHORIZED.message)
                return
            log.info('auth app[%s]', self.appInfo['appName'])
        else:
            log.err("loginWithoutPwd Error: Invalid. %s", self.request.body)
            self.write(ERR_UNAUTHORIZED.message)
            return

        # 检查数量限制
        # userHelper = ClassHelper(self.appDb, "User")
        # userUpper = self.appInfo['userUpper']
        # # userUpper=0表示无数量限制
        # if userUpper>0:
        # 	if userHelper.count() > userUpper:
        # 		log.err('[%s] over user count limit', self.appInfo['appName']);
        # 		self.write(ERR_USER_PERMISSION.message)

        try:
            user.loginWithoutPwd()
            log.info('LoginWithoutPwd: %s', user['username'])
            self.set_secure_cookie("u", user['username'])
            user['authen'] = userInfo['authen']
            self.write(json.dumps(user, cls=MeEncoder))

            # 登录日志
            loginLog = MeObject(self.appName, 'LoginLog')
            loginLog['username'] = user['username']
            if hasattr(self, 'client_ip'):
                loginLog['ip'] = self.client_ip
            loginLog.save()
        except Exception, e:
            log.err("LoginWithoutPwd Error: %s Error:%s", self.request.body,
                    str(e))
            self.write(str(e))
Пример #7
0
 def callback(response):
     log.info('Push:%s', response.body)
     self.finish()
Пример #8
0
    def createWxAppOrder(self):
        log.debug('in create wx app order json body:%s', self.jsonBody)
        obj = self.jsonBody
        coin_setting_id = obj.get('id')  # coinSettingId
        # channel = obj.get('channel', '')
        # version = obj.get('version', '')
        try:
            channel = self.request.headers.get("X-MeCloud-Channel", None)
            version = self.request.headers.get("X-MeCloud-Client", None)
        except:
            pass

        log.debug('coin_setting_id: %s', coin_setting_id)
        coin_setting = MeObject('CoinSetting').get(coin_setting_id)
        log.debug('coin_setting: %s', coin_setting)
        if coin_setting is None:
            # 未找到充值条目
            self.write(ERR_PARA.message)
            return
        out_trade_no = self.createOrderNo()
        log.debug('out_trade_no: %s', out_trade_no)
        pub = UnifiedOrder_pub()
        pub.parameters['out_trade_no'] = out_trade_no  # 设置参数自己的订单号
        pub.parameters['body'] = '黑蜜虚拟商品-黑蜜滴' + str(coin_setting['amount']) + '个'  # 设置商品描述
        # pub.parameters['total_fee'] = str(coin_setting['price'])  # 设置总金额
        if BaseConfig.mode == 'online':
            pub.parameters['total_fee'] = str(coin_setting['price'] * 100)
        else:
            pub.parameters['total_fee'] = '1'  # 设置总金额 1分用于测试
        pub.parameters['notify_url'] = WxPayConf_pub.NOTIFY_URL  # 设置回调url
        if BaseConfig.mode == 'online':
            pub.parameters['notify_url'] = WxPayConf_pub.NOTIFY_URL_RELEASE
        pub.parameters['trade_type'] = 'APP'  # 支付类型,固定为app
        wx_result = pub.getResult()
        log.info('wx create order result: %s', wx_result)

        if wx_result['return_code'] == 'SUCCESS':
            log.debug('prepay_id: %s', wx_result['prepay_id'])
            result = {}
            result['code'] = 0
            result['errCode'] = 0
            result['prepayid'] = wx_result['prepay_id']
            result['appid'] = wx_result['appid']
            result['partnerid'] = wx_result['mch_id']  # 商户号
            result['package'] = 'Sign=WXPay'
            result['noncestr'] = out_trade_no
            result['timestamp'] = str(int(time.time()))
            client_pub = UnifiedOrder_pub()
            client_pub.parameters['prepayid'] = result['prepayid']
            client_pub.parameters['appid'] = result['appid']
            client_pub.parameters['partnerid'] = result['partnerid']
            client_pub.parameters['package'] = result['package']
            client_pub.parameters['noncestr'] = result['noncestr']
            client_pub.parameters['timestamp'] = result['timestamp']
            client_sign = client_pub.getSign(client_pub.parameters)
            result['sign'] = client_sign
            # 创建充值流水记录
            rf = MeObject('RechargeFlow')
            rf['user'] = self.user['_id']
            rf['recharge'] = coin_setting['price']
            rf['amount'] = coin_setting['amount']
            rf['os'] = coin_setting['os']
            rf['platform'] = 1  # 微信APP
            if channel:
                rf['channel'] = channel
            rf['version'] = version
            rf['status'] = 0
            rf['orderNo'] = out_trade_no
            rf['order'] = ''
            rf.save()
            self.write(result)
        else:
            self.write(ERR_PARA.message)
Пример #9
0
    def __init__(self, config_path=None, env='online'):
        # 读取配置文件
        self.port = None
        self.config = ConfigParser()
        configFile = ''
        if not config_path:
            opts, args = getopt.getopt(sys.argv[1:], "c:p:")
            if opts:
                for opt, arg in opts:
                    if opt == '-c':
                        configFile = arg
                    if opt == '-p':
                        self.port = arg
            else:
                print 'mecloud.py -c <configfile>'
                sys.exit()
        else:
            configFile = config_path
        if not configFile:
            print 'mecloud.py -c <configfile>'
            sys.exit()

        self.config.read(configFile)
        self.version = self.config.get('global', 'version')
        self.project = self.config.get('global', 'project')
        if not self.port:
            self.port = self.config.get('global', 'PORT')

        self.initOSS()
        self.initSMS()
        self.initRedis()
        self.initDb()

        if env == 'offline':
            return
        log.info("version:%s project:%s", self.version, self.project)
        self.initWx()

        self.handlers = [
            ('/1.0/class/(\\w+)/(\\w+)',
             'mecloud.api.ClassHandler.ClassHandler'),
            ('/1.0/class/(\\w+)', 'mecloud.api.ClassHandler.ClassHandler'),
            ('/1.0/query/(\\w+)',
             'mecloud.api.QueryCountHandler.QueryCountHandler'),
            ('/1.0/query/', 'mecloud.api.QueryCountHandler.QueryCountHandler'),
            ('/1.0/user/(\\w+)', 'mecloud.api.UserHandler.UserHandler'),
            ('/1.0/user/', 'mecloud.api.UserHandler.UserHandler'),
            ('/1.0/file/', 'mecloud.api.FileHandler.FileHandler'),
            ('/1.0/file/(\\w+)', 'mecloud.api.FileHandler.FileHandler'),
            ('/1.0/upload/(\\w+)',
             'mecloud.api.CmsFileUploadHandler.CmsFileUploadHandler'),
            ('/1.0/file/download/(\\w+)',
             'mecloud.api.FileDownloadHandler.FileDownloadHandler'),
            ('/sms/(.+)', 'mecloud.api.SMSHandler.SMSHandler'),
            ('/captcha/(.+)', 'mecloud.api.CaptchaHandler.CaptchaHandler'),
            ('/wx/(\\w+)', 'mecloud.api.WxHandler.WxHandler'),
            ('/1.0/follow/(\\w+)/(\\w+)/(\\d+)',
             'mecloud.api.FollowerHandler.FollowerHandler'),
            ('/1.0/follow/(\\w+)',
             'mecloud.api.FollowerHandler.FollowerHandler'),
            ('/statcount/query',
             'mecloud.api.StatCountHandler.StatCountHandler'),
            ('/1.0/black/(\\w+)/(\\w+)/(\\d+)',
             'mecloud.api.BlacklistHandler.BlacklistHandler'),
            ('/1.0/thirdpay/(\w+)', 'mecloud.api.PayHandler.PayHandler'),
            ('/1.0/pay/(\w+)', 'mecloud.api.PayHandler.PayHandler'),
            ('/1.0/wxpaycallback',
             'mecloud.api.WxCallbackHandler.WxCallbackHandler'),
            ('/1.0/alipaycallback',
             'mecloud.api.AlipayCallbackHandler.AlipayCallbackHandler'),
            ('/1.0/manager/(\w+)',
             'mecloud.api.CmsInviteCodeHandler.CmsInviteCodeHandler')
        ]

        urls = self.config.options('handlers')
        for url in urls:
            handle = (url, self.config.get('handlers', url))
            self.handlers.append(handle)

        if self.config.has_option('global', 'TEMPLATE_PATH'):
            template_path = self.config.get('global', 'TEMPLATE_PATH')
        else:
            template_path = os.path.join(os.getcwd(), "views")

        if self.config.has_option('global', 'STATIC_PATH'):
            static_path = self.config.get('global', 'STATIC_PATH')
        else:
            static_path = os.path.join(os.getcwd(), "static")

        if self.config.has_option('global', 'mode'):
            BaseConfig.mode = self.config.get('global', 'mode')
        else:
            BaseConfig.mode = "online"

        if self.config.has_option('global', 'DELETE_CLASS'):
            BaseConfig.deleteClass = self.config.get('global', 'DELETE_CLASS')

        if self.config.has_option('global', 'WSSERVER'):
            BaseConfig.wsserver = self.config.get('global', 'WSSERVER')

        settings = dict(
            cookie_secret="kr9ci0i0z$hti7YBnG7=gY6xvP&2ishfCqAAbW!sO3h0Opsd",
            # "xsrf_cookies": True,
            debug=True,
            template_path=template_path,
            static_path=static_path,
            autoreload=True,
        )
        log.info("template [%s] static [%s]", settings['template_path'],
                 settings['static_path'])

        tornado.web.Application.__init__(self, self.handlers, **settings)

        # arthur
        projectClassHelper = ClassHelper("ProjectClass")
        items = projectClassHelper.find({})
        for item in items:
            BaseConfig.projectClass[item['classname']] = item

        adminClassHelper = ClassHelper("Role")
        items = adminClassHelper.find({"role": "admin"})
        for item in items:
            BaseConfig.adminUser[item['user']] = item["role"]

        if self.config.has_option('global',
                                  'ACCESS_NO_CLASS'):  # 对外不可通过class接口读取的Class
            BaseConfig.accessNoClass = eval(
                self.config.get('global', 'ACCESS_NO_CLASS'))

        if self.config.has_option('global',
                                  'PUSHURL'):  # 对外不可通过class接口读取的Class
            BaseConfig.pushUrl = self.config.get('global', 'PUSHURL')
            log.info("Push url:%s", BaseConfig.pushUrl)

        self.initMongodbIndex()
Пример #10
0
 def start(self):
     server = tornado.httpserver.HTTPServer(self, xheaders=True)
     server.listen(self.port)
     log.info("server start on port:%s", self.port)
     tornado.ioloop.IOLoop.instance().start()
Пример #11
0
                if {"_sid": 1} not in haveIndex[classname]:
                    db.index(classname, [("_sid", 1)])
                    log.info("classname:%s, index:%s", classname,
                             json.dumps([("_sid", 1)]))
            except Exception, e:
                log.err("Error:%s, error:%s", classname, str(e))

        if self.config.has_option('global', 'mongodbIndex'):
            objs = self.config.get('global', 'mongodbIndex')
            objs = json.loads(objs)
            for obj in objs:
                try:
                    unique = obj.get("unique", False)
                    index = obj.get("index")
                    items = []
                    if index in haveIndex.get(obj["className"], []):
                        continue
                    for key, value in index.items():
                        if value == 1:
                            items.append((key, pymongo.ASCENDING))
                        elif value == -1:
                            items.append((key, pymongo.DESCENDING))
                        else:
                            items.append((key, value))
                    db.index(obj["className"], items, unique=unique)
                    log.info("classname:%s, index:%s", obj["className"],
                             json.dumps(items))
                except Exception, e:
                    log.err("JSON Error:%s, error:%s", obj["className"],
                            str(e))
Пример #12
0
    def __init__(self, config_path=None, env='online'):
        # 读取配置文件
        self.port = None
        self.config = ConfigParser()
        configFile = ''
        if not config_path:
            opts, args = getopt.getopt(sys.argv[1:], "c:p:")
            if opts:
                for opt, arg in opts:
                    if opt == '-c':
                        configFile = arg
                    if opt == '-p':
                        self.port = arg
            else:
                print 'mecloud.py -c <configfile>'
                sys.exit()
        else:
            configFile = config_path
        if not configFile:
            print 'mecloud.py -c <configfile>'
            sys.exit()

        self.config.read(configFile)
        self.version = self.config.get('global', 'version')
        self.project = self.config.get('global', 'project')

        if self.config.has_section('oss'):
            self.initOSS()
        if self.config.has_section('sms'):
            self.initSMS()
        if self.config.has_section('redis'):
            self.initRedis()
        if self.config.has_section('mongodb'):
            self.initDb()
        if self.config.has_section('wx'):
            self.initWx()
        if self.config.has_section('wxpay'):
            self.initWxPay()
        if self.config.has_section('alipay'):
            self.initAlipay()

        if env == 'offline':
            return

        log.info("version:%s project:%s", self.version, self.project)
        self.crypto = False
        if self.config.has_option(
                'global',
                'crypto') and self.config.get('global', 'crypto') != '0':
            self.crypto = True
        if not self.port:
            self.port = self.config.get('global', 'PORT')

        # handler 路径
        self.handlers = self.initHandlers()

        # 模板路径
        if self.config.has_option('global', 'TEMPLATE_PATH'):
            template_path = self.config.get('global', 'TEMPLATE_PATH')
        else:
            template_path = os.path.join(os.getcwd(), "views")
        # 静态文件路径
        if self.config.has_option('global', 'STATIC_PATH'):
            static_path = self.config.get('global', 'STATIC_PATH')
        else:
            static_path = os.path.join(os.getcwd(), "static")

        self.debug = False
        if self.config.has_option('global', 'debug'):
            self.debug = True

        settings = dict(
            cookie_secret="kr9ci0i0z$hti7YBnG7=gY6xvP&2ishfCqAAbW!sO3h0Opsd",
            # "xsrf_cookies": True,
            debug=self.debug,
            template_path=template_path,
            static_path=static_path,
            autoreload=True,
        )
        log.info("template [%s] static [%s]", settings['template_path'],
                 settings['static_path'])
        '''
        for h in self.handlers:
            log.info("handlers: %s\t%s", h[0], h[1])
        '''
        tornado.web.Application.__init__(self, self.handlers, **settings)
        '''
Пример #13
0
 def initDb(self):
     # mongodb及oss配置
     if self.config.has_option('mongodb', 'ADDR'):
         addr = self.config.get('mongodb', 'ADDR')
         MongoDb.connect(addr=addr)
         log.info('mongodb[%s] init success', addr)