Beispiel #1
0
    def get(self, username, gid, userinfo='', *args, **kwargs):
        sn = GDevRdsInts.send_cmd(*get_sn_of_gid(gid))

        logger.debug('username = %r, gid = %r, sn = %r, userinfo = %r',
                     username, gid, sn, userinfo)
        GDevRdsInts.send_cmd(*hdel_wechat_gid(username, gid))
        GDevRdsInts.send_multi_cmd(
            *combine_redis_cmds(unfollow_group(gid, sn, username)))

        accounts = GDevRdsInts.send_cmd(*get_group_followers(gid))
        logger.debug('share, accounts={0}'.format(accounts))
        # accounts is set object
        primary_account = GDevRdsInts.send_cmd(*get_group_primary(gid))

        accounts.add(primary_account)
        sn = GDevRdsInts.send_cmd(*get_sn_of_gid(gid))
        accounts.add(sn)

        logger.debug('share, accounts={0}'.format(accounts))

        for acc in accounts:
            if acc[:3] == 'wx#':
                continue

            GMQDispRdsInts.send_cmd(*shortcut_mq(
                'cloud_push',
                # sourcer, cb, from, description
                push_pack(username,
                          'unfollow',
                          2,
                          ':'.join((username, gid)),
                          account=acc)))
        return 'success'
Beispiel #2
0
    def get(self, user_name, sn, lon, lat, radius, name, action, *args,
            **kwargs):
        primary = GDevRdsInts.send_cmd(*get_dev_primary(sn))
        if user_name != primary:
            return {'status': 1}

        gid = GDevRdsInts.send_cmd(*get_gid_of_sn(sn))
        payload = ujson.dumps({
            'lon': lon,
            'lat': lat,
            'rad': radius,
            'name': name,
            'creator': user_name,
            'action': action
        })

        GDevRdsInts.send_multi_cmd(*combine_redis_cmds(
            set_user_group_msglist(sn, gid, 'geo_fence', payload)))

        GMQDispRdsInts.send_cmd(*shortcut_mq(
            'cloud_push',
            push_pack(user_name, 'set_geo_fence', 2, payload, account=sn)))

        if action == 'add':
            GDevRdsInts.send_cmd(
                *save_geo_fence(sn, user_name, lon, lat, radius, name))
        elif action == 'del':
            GDevRdsInts.send_cmd(*del_geo_fence(sn, lon, lat, radius))
        return {'status': 0}
Beispiel #3
0
    def post(self, user_name, gid, share_to, location, text, type, files,
             *args, **kwargs):
        primary_account = GDevRdsInts.send_cmd(*get_group_primary(gid))
        if primary_account is None:
            return {'status': 1}

        ts = float('%0.2f' % time.time())
        share_id = ':'.join(('share', str(ts), gid, user_name))
        GDevRdsInts.send_cmd(*add_self_share(user_name, ts, share_id))
        GDevRdsInts.send_cmd(*save_share_info(
            share_id, user_name, gid, share_to, location, text, type, files))

        accounts = GDevRdsInts.send_cmd(*get_group_followers(gid))
        logger.debug('share, accounts={0}'.format(accounts))
        # accounts is set object
        accounts.add(primary_account)
        sn = GDevRdsInts.send_cmd(*get_sn_of_gid(gid))
        accounts.add(sn)

        logger.debug('share, accounts={0}'.format(accounts))

        for acc in accounts:
            GDevRdsInts.send_cmd(*add_share(acc, share_id, ts))
            if acc == user_name:
                continue
            elif acc[:3] == 'wx#':
                continue
            GMQDispRdsInts.send_cmd(*shortcut_mq(
                'cloud_push',
                push_pack(user_name,
                          'share',
                          2,
                          ':'.join((share_id, text, type, files)),
                          account=acc)))
        return {'share_id': share_id}
Beispiel #4
0
    def post(self, account, val, pwd, *args, **kwargs):
        cur_account = fix_account_postfix(account)
        review_val = GAccRdsInts.send_multi_cmd(
            *combine_redis_cmds(review_lostpwd_val(cur_account)))
        if not review_val:
            return {'status': 3}

        if val != review_val:
            return {'status': 4}

        GAccRdsInts.send_multi_cmd(*combine_redis_cmds(
            pass_lostpwd_val(cur_account),
            set_account_pwd(cur_account, cipher_pwd(pwd), False)))

        GMQDispRdsInts.send_cmd(*[
            shortcut_mq(
                'gen_mysql',
                mysql_pack(
                    DB_TBL_SSP_USR_LOGIN,
                    {
                        'username': cur_account,
                        'password': cipher_pwd(pwd),
                        'mobile': cur_account.split('@')[0],
                        # 'api_key': '840ebe7c2bfe4d529181063433ece0ef',
                    },
                    2))
        ])
        return {'status': 0}
Beispiel #5
0
    def get(self, gid, nice_gid, *args, **kwargs):
        old_gid = GDevRdsInts.send_cmd(*get_old_gid(nice_gid))
        if old_gid:
            return {'status': 1}

        # sn & gid mapping
        sn = GDevRdsInts.send_cmd(*get_sn_of_gid(gid))
        if sn is None:
            sn = GDevRdsInts.send_cmd(*get_sn_of_gid(nice_gid))
            if sn is None:
                return {'status': 2}

        GDevRdsInts.send_multi_cmd(*combine_redis_cmds(set_gid_of_sn(sn, nice_gid), set_sn_of_gid(nice_gid, sn), del_sn_of_gid(gid)))

        # gid & primary mapping
        primary = GDevRdsInts.send_cmd(*get_group_primary(gid))
        GDevRdsInts.send_multi_cmd(*combine_redis_cmds(set_group_primary(nice_gid, primary), del_group_primary(gid)))

        followers = GDevRdsInts.send_cmd(*get_group_followers(gid))
        for follower in followers:
            GDevRdsInts.send_multi_cmd(*combine_redis_cmds(follow_group(gid, sn, follower)))

        GDevRdsInts.send_multi_cmd(*combine_redis_cmds(set_nice_gid(gid, nice_gid), set_old_gid(nice_gid, gid)))
        user_info, nickname = GDevRdsInts.send_multi_cmd(*combine_redis_cmds(get_user_info(gid), get_user_nickname(gid)))
        if user_info:
            GDevRdsInts.send_cmd(*set_user_info(nice_gid, user_info))
        if nickname:
            GDevRdsInts.send_cmd(*set_user_nickname(nice_gid, nickname))

        GMQDispRdsInts.send_multi_cmd(*combine_redis_cmds(
                shortcut_mq('gen_mysql', mysql_pack(DB_TBL_GID_INFO, {'sn': sn, 'status': 'used'}, action=2, ref_kvs={'gid': nice_gid})),
                shortcut_mq('gen_mysql', mysql_pack(DB_TBL_DEVICE_INFO, {'nice_gid': nice_gid}, action=2, ref_kvs={'sn': sn}))
            ))
        return {'status': 0}
Beispiel #6
0
    def post(self, user_name, sn, payload, *args, **kwargs):
        logger.debug(u'event report -- acc={0}, sn={1}, payload={2}'.format(
            user_name, sn, bs2unicode(payload)))
        payload = ujson.loads(payload)
        reason = payload.get('reason')
        if reason == 'geo_fence_alert':
            attr = payload.get('attr')
            ts = payload.get('ts')
            longitude = attr.get('lon')
            latitude = attr.get('lat')
            radius = attr.get('rad')

            _ = GDevRdsInts.send_cmd(
                *get_geo_fence(user_name, longitude, latitude, radius))
            creator, name = _.split(':')

            GMQDispRdsInts.send_multi_cmd(*combine_redis_cmds([
                shortcut_mq(
                    'cloud_push',
                    push_pack(user_name,
                              'geo_fence_alertqqq',
                              2,
                              payload,
                              account=creator))
            ]))
        sample_freq = 600
        next_latency = 3600
        return {
            'state': 0,
            'next_latency': next_latency,
            'sample_freq': sample_freq
        }
Beispiel #7
0
    def post(self, user_name, share_id, *args, **kwargs):
        gid = ''
        sl = share_id.split(':')
        author = ''
        if len(sl) == 4:
            _, _, gid, author = sl
        elif len(sl) == 3:
            _, _, author = sl

        logger.debug(u'delete share, gid={0}, author={1}, acc={2}'.format(
            gid, author, user_name))

        if not self.can_delete(gid, author, user_name):
            return {'status': 1}

        share_info = GDevRdsInts.send_cmd(*retrieve_share_info(share_id))
        if share_info is None:
            return {'status': 2}

        files = share_info.get('files')
        if files:
            fns = json.loads(files)
            logger.debug(
                u'delete share, share_id={0}, gid={1}, fns={2}'.format(
                    share_id, gid, fns))
            for k, v in fns.items():
                urllib2.urlopen(BEIQI_FILE_DELETE_URL.format(file=bs2utf8(v)))

        comment_id_list = GDevRdsInts.send_cmd(*get_comment(share_id))
        if comment_id_list is not None:
            for comment_id in comment_id_list:
                fn = GDevRdsInts.send_cmd(
                    *get_comment_file(share_id, comment_id))
                urllib2.urlopen(BEIQI_FILE_DELETE_URL.format(file=fn))
                GDevRdsInts.send_cmd(*del_comment_info(share_id, comment_id))

        GDevRdsInts.send_multi_cmd(*combine_redis_cmds(
            del_share(user_name, share_id), del_comment(share_id),
            del_share_info(share_id)))

        if gid:
            sn = GDevRdsInts.send_cmd(*get_sn_of_gid(gid))

            accounts = GDevRdsInts.send_cmd(*get_group_followers(gid))
            primary_account = GDevRdsInts.send_cmd(*get_group_primary(gid))
            accounts.add(primary_account)
            accounts.add(sn)

            logger.debug(u'accounts={0}'.format(accounts))
            for user in accounts:
                if user_name == user:
                    continue
                GDevRdsInts.send_cmd(*del_share(user, share_id))
                GMQDispRdsInts.send_cmd(*shortcut_mq(
                    'cloud_push',
                    push_pack(
                        user_name, 'delete_share', 2, share_id, account=user)))

        return {'status': 0}
Beispiel #8
0
 def get(self, new_nick, username, gid, *args, **kwargs):
     GDevRdsInts.send_cmd(*hset_wechat_gid(username, gid, new_nick))
     GMQDispRdsInts.send_cmd(*shortcut_mq(
         'gen_mysql',
         mysql_pack(DB_TBL_USER_INFO, {'nickname': new_nick},
                    action=2,
                    ref_kvs={'username': username})))
     return
Beispiel #9
0
    def get(self, user_name, file_type, fn, ref, thumb_fn="", thumb_ref="", text="", *args, **kwargs):
        des = bs2utf8(':'.join([urllib2.quote(bs2utf8(v)) for v in (user_name,  file_type, fn, ref, thumb_fn, thumb_ref,text)]))

        GMQDispRdsInts.send_cmd(*
            shortcut_mq('chat_msg',
                        push_pack(user_name, 'msg', 2, desc=des)
                        )
        )
Beispiel #10
0
    def get(self, user_name, sn, action, *args, **kwargs):
        primary = GDevRdsInts.send_cmd(*get_dev_primary(sn))
        if not primary:
            return {'state': 1}

        logger.debug('dev ctrl sn: {0}, action: {1}, acc: {2}'.format(
            sn, action, user_name))
        GMQDispRdsInts.send_cmd(*shortcut_mq(
            'cloud_push',
            push_pack(user_name, 'dev_ctrl', 2, action, account=sn)))
        return {'state': 0}
Beispiel #11
0
def wechat_msg_bcast(author, file_type, fn, ref, thumb_fn="", thumb_ref="", text=""):
    logger.debug('wechat_msg_bcast author={0}, type={1}, fn={2}, ref={3}, thumb_fn={4}, thumb_ref={5}, text={6}'.format(author, file_type, fn, ref, thumb_fn, thumb_ref, text))

    des = bs2utf8(':'.join([urllib2.quote(bs2utf8(v)) for v in (author,  file_type, fn, ref, thumb_fn, thumb_ref, text)]))

    GMQDispRdsInts.send_cmd(
        *shortcut_mq(
            'chat_msg',
            push_pack(author, 'msg', 2, des)
        )
    )
Beispiel #12
0
    def get(self, user_name, dev_sn, name, ref, *args, **kwargs):
        version = "1"
        logic = "play"
        type = "audio"
        payload = ':'.join([
            bs2utf8(urllib.quote_plus(v))
            for v in (version, logic, type, name, ref)
        ])

        GMQDispRdsInts.send_cmd(*shortcut_mq(
            'dev_msg', push_pack(user_name, 'msg', 2, payload,
                                 account=dev_sn)))
Beispiel #13
0
    def get(self, user_name, receiver, app, payload, *args, **kwargs):
        now = str(time.time())
        payload = '$'.join((user_name, payload))
        result = GDevRdsInts.send_cmd(
            *set_app_data(receiver, app, now, payload))
        logger.debug(u'result = %r', result)

        GMQDispRdsInts.send_cmd(*shortcut_mq(
            'cloud_push',
            push_pack(user_name, 'set_app_data', 2, payload,
                      account=receiver)))
        return {'status': 0}
Beispiel #14
0
    def post(self, account, pwd, val, *args, **kwargs):
        """
        检查注册验证码
        """
        user_agent = urllib.unquote(bs2utf8(
            self.request.headers['user-agent']))

        reg_ip = bs2utf8(self.request.remote_ip)
        if not is_email(account):
            return {'status': 1}

        mobile = account.partition('@')[0]
        if not is_mobile(mobile):
            return {'status': 2}

        if not is_reg_val_code(val):
            return {'status': 3}

        expect_code = GAccRdsInts.send_cmd(*get_newacc_reg_val(mobile))
        if not expect_code:
            return {'status': 4}
        expect_code = expect_code.split(':')[0]
        if expect_code != val:
            return {'status': 4}

        pwd_mask = cipher_pwd(pwd)
        ok = GAccRdsInts.send_cmd(*set_account_pwd(account, pwd_mask))
        if not ok:
            return {'status': 5}

        reg_ts = time.strftime(fmt, time.gmtime())
        GMQDispRdsInts.send_multi_cmd(*combine_redis_cmds(
            shortcut_mq(
                'gen_mysql',
                mysql_pack(DB_TBL_SSP_USR_LOGIN, {
                    'username': account,
                    'password': pwd_mask,
                    'mobile': mobile,
                }, 0)),
            shortcut_mq(
                'gen_mysql',
                mysql_pack(
                    DB_TBL_SSP_USR_LOGIN,
                    {
                        'username': account,
                        'reg_agent': user_agent,
                        'reg_ts': reg_ts,
                        'reg_ip': reg_ip,
                    },
                    action=0,
                ))))
        return {'status': 0}
Beispiel #15
0
    def get(self, user_name, applicant, gid, allowed, msg='', *args, **kwargs):
        primary = GDevRdsInts.send_cmd(*get_group_primary(gid))
        if not primary:
            return {'status': 1}

        if primary != user_name:
            return {'status': 2}

        sn = GDevRdsInts.send_cmd(*get_sn_of_gid(gid))
        if allowed:
            GDevRdsInts.send_multi_cmd(
                *combine_redis_cmds(follow_group(gid, sn, applicant)))
            if applicant[:3] == 'wx#':
                # applicant from wechat
                logger.debug(u'wechat user follow: ', applicant)
                GDevRdsInts.send_cmd(*hset_wechat_gid(applicant, gid))
                token = gen_wechat_access_token(GAccRdsInts)
                customerServiceUrl = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' + token
                payload = \
                {
                    "touser": applicant[3:],
                    "msgtype": "text",
                    "text":
                        {
                            "content": "恭喜你设备添加成功。可以给平板发送照片了!"
                        }
                }
                resp = HttpRpcClient().fetch_async(url=customerServiceUrl,
                                                   body=ujson.dumps(
                                                       payload,
                                                       ensure_ascii=False))
                logger.debug('wechat resp.code = %r, body = %r', resp.code,
                             resp.body)
                return {'status': 0}

        payload = ujson.dumps({
            'reviewer': user_name,
            'allowed': allowed,
            'msg': msg,
            'gid': gid
        })
        logger.debug(u'follow review, applicant=%r, payload=%r' %
                     (applicant, payload))
        # 把关注验证结果放到申请人的消息列表里
        GDevRdsInts.send_multi_cmd(*combine_redis_cmds(
            set_user_group_msglist(applicant, gid, 'follow_review', payload)))

        GMQDispRdsInts.send_cmd(*shortcut_mq(
            'cloud_push',
            push_pack(
                user_name, 'follow_review', 2, payload, account=applicant)))
        return {'status': 0}
Beispiel #16
0
    def post(self, user_name, receivers, duplicate_to, topic, text, type,
             files, *args, **kwargs):
        ts = float('%0.2f' % time.time())
        letter_id = ':'.join(('letter', str(ts), user_name, receivers))

        GDevRdsInts.send_cmd(
            *save_letter_info(letter_id, ':'.join((topic, text, type, files))))
        GDevRdsInts.send_cmd(*add_letter_outbox(user_name, letter_id, ts))

        receivers = ujson.loads(receivers)
        logger.debug('receivers={0}'.format(receivers))
        acc_noexist_list = []
        for acc in receivers:
            acc = bs2utf8(acc)

            account_exist = GAccRdsInts.send_cmd(*exist_account(acc))
            if not account_exist:
                # not in redis, check mysql
                sql = "select * from {db} where user_name='{user_name}'".format(
                    db='ssp_user_login', user_name=acc)
                res = DBBeiqiSspInst.query(sql)
                if len(res) == 0:
                    # not in mysql, so we check if it's a sn
                    if not is_email(acc):
                        primary = GDevRdsInts.send_cmd(*get_dev_primary(acc))
                        if not primary:
                            # no primary, illegal
                            logger.debug('acc={0} not exist'.format(acc))
                            acc_noexist_list.append(acc)
                            continue
                else:
                    # exist in mysql, so we cache it in redis
                    pwd = res[0].get('password').encode('utf8')
                    GAccRdsInts.send_cmd(*set_account_pwd(acc, pwd))

            GDevRdsInts.send_cmd(*add_letter_inbox(acc, letter_id, ts))
            GMQDispRdsInts.send_cmd(*shortcut_mq(
                'cloud_push',
                # sourcer, cb, from, description
                push_pack(user_name,
                          'letter',
                          2,
                          ':'.join((letter_id, topic, text, type, files)),
                          account=acc)))

        return acc_noexist_list
Beispiel #17
0
    def get(self, user_name, sn, *args, **kwargs):
        sql = "SELECT 1 FROM {db} WHERE sn = '{sn}'".format(
            db=DB_TBL_DEVICE_INFO, sn=sn)
        ret_list = DBBeiqiSspInst.query(sql)
        if len(ret_list) == 0:
            return {'status': 1}

        primary = GDevRdsInts.send_cmd(*get_dev_primary(sn))
        if primary is None:
            return {'status': 1}

        logger.debug('check dev args: pid: {0}, acc: {1}'.format(
            sn, user_name))

        GMQDispRdsInts.send_cmd(*shortcut_mq(
            'cloud_push',
            push_pack(user_name, 'check_dev_args', 2, '', account=sn)))
        return {'status': 0}
Beispiel #18
0
    def post(self, account, api_key, *args, **kwargs):
        """
        密码丢失
        :param account:
        :param args:
        :param kwargs:
        :return:
        """
        cur_account = fix_account_postfix(account)
        if not GAccRdsInts.send_cmd(*exist_account(cur_account)):
            sql = "select password from {db} where username='******'".format(
                db=DB_TBL_SSP_USR_LOGIN, username=cur_account)
            expect_pwd = DBBeiqiSspInst.query(sql)
            if len(expect_pwd) == 0:
                return {'status': 1}

        mobile = get_mobile(GAccRdsInts, api_key, cur_account)
        if not mobile:
            return {'status': 2}

        sms_speed = GDevRdsInts.send_cmd(*get_sms_speed())
        if sms_speed is None:
            GDevRdsInts.send_multi_cmd(*combine_redis_cmds(init_sms_speed()))
        elif sms_speed >= SMS_SPEED_MAX:
            return {'status': 3}
        else:
            GDevRdsInts.send_cmd(*incr_sms_speed())

        ts = GDevRdsInts.send_cmd(*get_user_veri_sms_time(mobile))
        if ts is not None:
            logger.debug('veri sms, ts={0}'.format(ts))
            return {'status': 4}
        else:
            GDevRdsInts.send_multi_cmd(*combine_redis_cmds(
                set_user_veri_sms_time(mobile, time.time())))

        val = ''.join((str(random.randint(0, 9)) for _ in xrange(6)))
        logger.debug('lost pwd val: {0}'.format(val))
        GAccRdsInts.send_multi_cmd(
            *combine_redis_cmds(gen_lostpwd_val(cur_account, val)))
        GMQDispRdsInts.send_cmd(
            *shortcut_mq('sms_notify',
                         sms_notify_pack(mobile, 2, cur_account, mobile, val)))
        return {'status': 0}
Beispiel #19
0
    def get(self, user_name, sn, f, d, payload, *args, **kwargs):
        logger.debug('cmd_rpt_v1 sn: {0}, d: {1}, f: {2}'.format(sn, d, f))
        primary = GDevRdsInts.send_cmd(*get_dev_primary(sn))

        logger.debug('cmd rpt primary: {0}'.format(primary))
        if not primary:
            logger.debug('cmd rpt sn={0} no primary'.format(sn))
            self.set_status(400)
            return

        if f != primary:
            followers = GDevRdsInts.send_cmd(*get_dev_followers(sn))
            if f not in followers:
                logger.debug(
                    'cmd rpt primary = {0}, f = {1}, sn = {2}, followers = {3]'
                    .format(primary, f, sn, followers))
                self.set_status(400)
                return

        m = FEEDBACK_PATTERN.search(d)
        if not m:
            self.set_status(400)
            return

        user_cmd, cmd_ord, error_state = [
            m.groupdict().get(k) for k in REPORT_KEYS
        ]

        if payload:
            description = payload
        else:
            description = errno_map.get(error_state) or 'fb_dft'

        logger.debug('cmd rpt desc: {0}'.format(description))

        GMQDispRdsInts.send_cmd(*shortcut_mq(
            'cloud_push',
            push_pack(sn,
                      '{0}:{1}:{2}'.format(error_state, 'cmd_report',
                                           int(cmd_ord, 16)),
                      0,
                      description,
                      account=f)))
        return ''
Beispiel #20
0
def add_device(username, code, user_info=None):
    primary = GDevRdsInts.send_cmd(*get_group_primary(code))
    if not primary:
        return {'status': 3}

    if username == primary:
        return {'status': 9}

    following = GDevRdsInts.send_cmd(*test_user_follow_group(username, code))
    if following:
        return {'status': 8}

    payload = ujson.dumps({'applicant': username, 'pid': code, 'msg': '', 'file': '', 'time': str(time.time())})

    # put follow request into primary msglist
    GDevRdsInts.send_multi_cmd(*combine_redis_cmds(set_user_group_msglist(primary, code, 'follow', payload)))

    # set user info
    if user_info is None:
        user_info = get_userinfo(username)

    nickname = bs2utf8(user_info.get('nickname'))
    user_info = ujson.dumps(user_info)
    GDevRdsInts.send_cmd(*set_user_info(username, user_info))
    GDevRdsInts.send_cmd(*set_user_nickname(username, nickname))

    GMQDispRdsInts.send_cmd(
        *shortcut_mq('gen_mysql',
            mysql_pack(DB_TBL_USER_INFO,
                       {'nickname': nickname},
                       action=2,
                       ref_kvs={'username': username}
                       )
        )
    )
    logger.debug('set user info, username={0}, user_info={1}'.format(username, user_info))

    GMQDispRdsInts.send_cmd(
        # sourcer, cb, from, description
        *shortcut_mq('cloud_push', push_pack(username, 'follow', 2, payload, account=primary))
    )

    logger.debug('follow, acc={0}, followee={1}, msg={2}, file={3}'.format(username, code, '', ''))
    return {'status': 1}
Beispiel #21
0
    def get(self, user_name, master, gid, reply, *args, **kwargs):
        primary = GDevRdsInts.send_cmd(*get_group_primary(gid))
        if primary != master:
            return {'status': 1}

        if reply == 'Y':
            sn = GDevRdsInts.send_cmd(*get_sn_of_gid(gid))
            GDevRdsInts.send_multi_cmd(
                *combine_redis_cmds(follow_group(gid, sn, user_name)))

        GDevRdsInts.send_cmd(*del_invite_follow(gid, master, user_name))
        GMQDispRdsInts.send_cmd(*shortcut_mq(
            'cloud_push',
            push_pack(user_name,
                      'reply_invite_follow',
                      2,
                      'reply={0}'.format(reply),
                      account=master)))
        return {'status': 0}
Beispiel #22
0
    def post(self, user_name, sn, payload, dev_type='', *args, **kwargs):
        logger.debug(u'loc v1 -- acc={0}, sn={1}, payload={2}'.format(
            user_name, sn, payload))

        payload = ujson.loads(payload)
        for k, v in payload.iteritems():
            k = bs2utf8(k)
            v = bs2utf8(v)

        GMQDispRdsInts.send_multi_cmd(*combine_redis_cmds(
            *build_mq_package(user_name, sn, dev_type, payload)))

        sample_freq = 600
        next_latency = 3600
        return {
            'state': 0,
            'next_latency': next_latency,
            'sample_freq': sample_freq
        }
Beispiel #23
0
def reg_via_mobile(account, api_key):
    """
    通过手机号注册
    :param account: 用户帐号
    :param api_key:
    :return:
    """
    mobile = account.split('@')[0]
    if not is_mobile(mobile):
        return

    val_code = ''.join((str(randint(0, 9)) for _ in xrange(6)))
    logger.debug('val_code %s sent' % val_code)
    #该接口需兼容oem,故填入空api_key
    GAccRdsInts.send_multi_cmd(*combine_redis_cmds(
        gen_newacc_reg_val(mobile, val_code, api_key or '')))
    GMQDispRdsInts.send_cmd(*shortcut_mq(
        'sms_notify',
        sms_notify_pack(
            mobile, SmsType.REGISTER, account, val_code, api_key=api_key)))

    logger.debug('account %s val_code %s sent' % (account, val_code))
    return True
Beispiel #24
0
    def post(self, user_name, sn, payload, *args, **kwargs):
        logger.debug('change dev args: sn: {0}, payload: {1}, acc: {2}'.format(
            sn, payload, user_name))
        if not user_name or not sn or not payload:
            self.set_status(400)
            return

        sql = "SELECT 1 FROM {db} WHERE sn = '{sn}'".format(
            db=DB_TBL_DEVICE_INFO, sn=sn)
        ret_list = DBBeiqiSspInst.query(sql)
        if len(ret_list) == 0:
            return {'status': 1}

        primary = GDevRdsInts.send_cmd(*get_dev_primary(sn))
        if primary is None:
            return {'status': 1}

        GMQDispRdsInts.send_cmd(*shortcut_mq(
            'cloud_push',
            push_pack(user_name, 'change_dev_args', 2, payload, account=sn)))
        logger.debug('cloud_push doing')

        return {'state': 0}
Beispiel #25
0
    def get(self, user_name, guest, gid, msg, file, *args, **kwargs):
        primary = GDevRdsInts.send_cmd(*get_group_primary(gid))
        if primary != user_name:
            return {'status': 1}

        account_exist = GAccRdsInts.send_cmd(*exist_account(guest))
        if not account_exist:
            sql = "select * from {db} where user_name='{user_name}'".format(
                db='ssp_user_login', user_name=guest)
            res = self.settings.get('mysql_db').query(sql)
            if len(res) == 0:
                return {'status': 2}
            else:
                # exist in mysql, so we cache it in redis
                pwd = res[0].get('password').encode('utf8')
                GAccRdsInts.send_cmd(*set_account_pwd(guest, pwd))

        sn = GDevRdsInts.send_cmd(*get_sn_of_gid(gid))
        GDevRdsInts.send_cmd(*follow_group(gid, sn, guest))

        payload = ujson.dumps({
            'master': user_name,
            'gid': gid,
            'msg': msg,
            'file': file,
            'action': 'invite_follow'
        })
        GDevRdsInts.send_multi_cmd(*combine_redis_cmds(
            set_user_group_msglist(guest, gid, 'invite_follow', payload)))
        logger.debug('invite follow, guest={0}, gid={1}, payload={2}'.format(
            guest, gid, payload))

        GMQDispRdsInts.send_cmd(*shortcut_mq(
            'cloud_push',
            push_pack(user_name, 'invite_follow', 2, payload, account=guest)))
        return {'status': 0}
Beispiel #26
0
    def post(self, user_name, payload, sn='', gid='',*args, **kwargs):
        logger.debug('user_name=%r, sn=%r, gid=%r, payload=%r' % (user_name, sn, gid, payload))
        nickname = bs2utf8(ujson.loads(payload).get('nickname'))

        if gid != '':
            primary = GDevRdsInts.send_cmd(*get_group_primary(gid))
            if user_name != primary:
                return {'status': 2}

            GDevRdsInts.send_cmd(*set_user_info(gid, payload))
            GDevRdsInts.send_cmd(*set_user_nickname(gid, nickname))
            return {'status': 0}

        if sn != '':
            primary = GDevRdsInts.send_cmd(*get_dev_primary(sn))
            if user_name != primary:
                return {'status': 3}

            GDevRdsInts.send_cmd(*set_user_info(sn, payload))
            GDevRdsInts.send_cmd(*set_user_nickname(sn, nickname))
            return {'status': 0}

        GDevRdsInts.send_cmd(*set_user_info(user_name, payload))
        GDevRdsInts.send_cmd(*set_user_nickname(user_name, nickname))

        GMQDispRdsInts.send_cmd(
            *shortcut_mq('gen_mysql',
                mysql_pack(DB_TBL_USER_INFO,
                           {'nickname': nickname},
                           action=2,
                           ref_kvs={'user_name': user_name}
                           )
            )
        )

        return {'status': 0}
Beispiel #27
0
    def get(self, user_name, sn, *args, **kwargs):
        sql = "SELECT 1 FROM {db_name} WHERE sn = '{sn}'".format(
            db_name=DB_TBL_DEVICE_INFO, sn=sn)
        ret_list = DBBeiqiSspInst.query(sql)
        if len(ret_list) == 0:
            return {'status': 1}

        gid = GDevRdsInts.send_cmd(*get_gid_of_sn(sn))
        primary = GDevRdsInts.send_cmd(
            *get_group_primary(gid)) if gid is not None else None
        if primary is None:
            # unbound
            if gid is None:
                # generate gid
                while True:
                    tmp_gid = str(randint(1, 9))
                    tmp_gid = tmp_gid + ''.join(
                        [str(randint(0, 9)) for i in xrange(5)])

                    sn_of_gid = GDevRdsInts.send_cmd(*get_sn_of_gid(tmp_gid))
                    if sn_of_gid is None:
                        # tmp_pid is not used.
                        sql = 'select * from {db} WHERE gid = {gid}'.format(
                            db=DB_TBL_GID_INFO, gid=tmp_gid)
                        query_result = DBBeiqiSspInst.query(sql)
                        if query_result and query_result[0].get(
                                'gid_kind') == 1:
                            # tmp_pid is a nice number
                            continue
                        gid = tmp_gid
                        GDevRdsInts.send_multi_cmd(
                            *combine_redis_cmds(set_gid_of_sn(sn, tmp_gid),
                                                set_sn_of_gid(tmp_gid, sn)))
                        break
                #update mysql data
                GMQDispRdsInts.send_multi_cmd(*combine_redis_cmds(
                    shortcut_mq(
                        'gen_mysql',
                        mysql_pack(DB_TBL_DEVICE_INFO, {'gid': gid},
                                   action=2,
                                   ref_kvs={'sn': sn})),
                    shortcut_mq(
                        'gen_mysql',
                        mysql_pack(DB_TBL_GID_INFO, {
                            'sn': sn,
                            'status': 'used'
                        },
                                   action=2,
                                   ref_kvs={'gid': gid}))))

            ic = GDevRdsInts.send_cmd(*get_sn_ic(sn))
            if not ic:
                # no ic in storage.
                while True:
                    ic = ''.join([str(randint(0, 9)) for i in xrange(9)])
                    ic_exist = GDevRdsInts.send_cmd(*get_ic_sn(ic))
                    if not ic_exist:
                        break
            logger.debug('sign in, gid={0}, ic={1}'.format(gid, ic))
            GDevRdsInts.send_multi_cmd(
                *combine_redis_cmds(set_sn_ic(sn, ic), set_ic_sn(ic, sn)))

            return {'binding': 0, 'ic': ic, 'gid': gid, 'status': 0}
        else:
            logger.debug('sign in, pid={0}, sn={1}, binded'.format(gid, sn))
            return {'binding': 1, 'gid': gid, 'status': 0}
Beispiel #28
0
    def get(self, username, api_key, pwd="", *args, **kwargs):
        """
        生成SSO认证token
        :param username:
        :param api_key:
        :param pwd: device no pwd, app account has pwd
        :param args:
        :param kwargs:
        :return:
        """

        user_agent = urllib.unquote(bs2utf8(
            self.request.headers['user-agent']))
        api_ob = beiqi_keys.get(api_key)
        if not api_ob:
            logger.warn("gen_tk api_ob:%s, api_key:%s" % (api_ob, api_key))
            self.set_status(401)
            return

        remote_ip = bs2utf8(self.request.remote_ip)

        if not is_email(username):
            # 设备没有pid时登录
            rc4_key = api_ob.get('rc4_key')
            if rc4_key is None:
                logger.debug(
                    'api_key={0}, username={1} rc4_key not exists'.format(
                        api_key, username))
                self.set_status(400)
                return

            sn, ts = decrypt_username(username, rc4_key)
            sql = "SELECT 1 FROM {db} WHERE sn = '{sn}'".format(
                db=DB_TBL_DEVICE_INFO, sn=sn)
            ret_list = DBBeiqiSspInst.query(sql)
            if len(ret_list) == 0:
                logger.debug('ret_list={0}, sn={1}'.format(ret_list, sn))
                self.set_status(400)
                return

            saved_ts = GDevRdsInts.send_cmd(*get_tk_time(sn))
            if saved_ts == ts:
                logger.debug('ts={0} the same with saved_ts'.format(ts))
                self.set_status(400)
                return

            GDevRdsInts.send_cmd(*set_tk_time(sn, ts))

            login_ts = time.strftime(fmt, time.gmtime())
            GMQDispRdsInts.send_cmd(*shortcut_mq(
                'gen_mysql',
                mysql_pack(DB_TBL_USER_INFO, {
                    'last_login_ts': login_ts,
                    'last_login_ip': remote_ip,
                    'last_login_agent': user_agent
                },
                           action=2,
                           ref_kvs={'username': sn})))
            return gen_token(api_ob.get('s'), sn, 1, account_rds=GAccRdsInts)

        gid = username.split('@')[0]
        if len(gid) == 6:
            # 设备登录
            sn = GDevRdsInts.send_cmd(*get_sn_of_gid(gid))
            logger.debug('beiqi sso, username=%r, gid=%r, sn=%r' %
                         (username, gid, sn))
            # primary = dev_filter.send_cmd(*get_dev_primary(pid))
            if sn:
                # django used gmttime, so we'd better use gmttime.
                login_ts = time.strftime(fmt, time.gmtime())
                GMQDispRdsInts.send_cmd(*shortcut_mq(
                    'gen_mysql',
                    mysql_pack(DB_TBL_USER_INFO, {
                        'last_login_ts': login_ts,
                        'last_login_ip': remote_ip,
                        'last_login_agent': user_agent
                    },
                               action=2,
                               ref_kvs={'username': username})))
                return gen_token(api_ob.get('s'),
                                 username,
                                 1,
                                 account_rds=GAccRdsInts)
            else:
                logger.debug('gid={0} invalid no sn'.format(gid))
                self.set_status(403)
                return

        expect_pwd = GAccRdsInts.send_cmd(*get_pwd(username))

        if expect_pwd is not None:
            if expect_pwd != cipher_pwd(pwd):
                logger.warn(
                    'pwd incorrect: username = {0}, pwd={1}, expect_pwd={2}'.
                    format(username, cipher_pwd(pwd), expect_pwd))
                self.set_status(401)
                return
        else:
            # not in redis, check mysql
            sql = "select password from {db} where username='******'".format(
                db='ssp_user_login', username=username)
            expect_pwd = DBBeiqiSspInst.query(sql)
            if len(expect_pwd) == 0:
                logger.debug('account={0} not exist'.format(username))
                self.set_status(401)
                return
            else:
                pwd_inmysql = expect_pwd[0].get('password')
                pwd_inmysql = pwd_inmysql.encode(
                    'utf8') if pwd_inmysql is not None else pwd_inmysql
                if pwd_inmysql != cipher_pwd(pwd):
                    logger.debug(
                        'pwd incorrect: username = {0}, pwd={1}, expect_pwd={2}'
                        .format(username, cipher_pwd(pwd), expect_pwd))
                    self.set_status(401)
                    return

        login_ts = time.strftime(fmt, time.gmtime())
        GMQDispRdsInts.send_cmd(*shortcut_mq(
            'gen_mysql',
            mysql_pack(DB_TBL_USER_INFO, {
                'last_login_ts': login_ts,
                'last_login_ip': remote_ip,
                'last_login_agent': user_agent
            },
                       action=2,
                       ref_kvs={'username': username})))
        return gen_token(api_ob.get('s'), username, 1, account_rds=GAccRdsInts)
Beispiel #29
0
    def post(self,
             user_name,
             share_id,
             reply_to='',
             comment_id='',
             text='',
             type='',
             file='',
             *args,
             **kwargs):
        share_info = GDevRdsInts.send_cmd(*retrieve_share_info(share_id))
        if share_info is None:
            return {'status': 1}

        comment_id_list = GDevRdsInts.send_cmd(*get_comment(share_id))
        if comment_id != '' and comment_id not in comment_id_list:
            logger.debug('comment, comment_id={0}'.format(comment_id))
            return {'status': 2}

        now = str(time.time())
        new_comment_id = ':'.join(('comment', now, user_name))

        GDevRdsInts.send_multi_cmd(*combine_redis_cmds(
            add_comment(share_id, new_comment_id),
            save_comment_info(share_id, new_comment_id, reply_to, comment_id,
                              text, type, file)))

        accounts = [reply_to] if reply_to is not None else []
        accounts += [share_id.split(':')[-1]]
        like_list = GDevRdsInts.send_cmd(*get_like(share_id))

        accounts += like_list

        for acc in accounts:
            if acc[:3] == 'wx#':
                files = json.loads(share_info.get('files'))
                fn, ref = files.popitem()
                fn = bs2utf8(fn)
                ref = bs2utf8(ref)
                logger.debug('files = %r, fn = %r, ref = %r', files, fn, ref)

                tk = gen_file_tk(acc, fn, 0, 0)
                if fn[-4:] == '.jpg':
                    pic_url = BEIQI_FILE_DOWN_URL + urllib.urlencode({
                        'tk': tk,
                        'r': ref
                    })

                url = ""
                if not file:
                    url = WECHAT_COMMENT_PAGE_URL + urllib.urlencode(
                        {'text': text})

                token = gen_wechat_access_token(GAccRdsInts)
                customerServiceUrl = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' + token
                nickname = GDevRdsInts.send_cmd(*get_user_nickname(user_name))
                payload = {
                    "touser": acc[3:],
                    "msgtype": "news",
                    "news": {
                        "articles": [{
                            "title": nickname + "评论了你的回复",
                            "description": text,
                            "url": url,
                            "picurl": pic_url
                        }]
                    }
                }
                logger.debug('pic_url = %r', pic_url)
                resp = HttpRpcClient().fetch_async(url=customerServiceUrl,
                                                   body=ujson.dumps(
                                                       payload,
                                                       ensure_ascii=False))
                logger.debug('custom service send. resp = %r, payload = %r',
                             resp.body, payload)

            else:
                GMQDispRdsInts.send_cmd(*shortcut_mq(
                    'cloud_push',
                    # sourcer, cb, from, description
                    push_pack(user_name,
                              'comment',
                              2,
                              ':'.join((user_name, share_id, reply_to,
                                        comment_id, text, type, file)),
                              account=acc)))

        return {'comment_id': new_comment_id}
Beispiel #30
0
    def post(self, user_name, gid, *args, **kwargs):
        primary = GDevRdsInts.send_cmd(*get_group_primary(gid))
        if not primary:
            return {'status': 3}

        followers = GDevRdsInts.send_cmd(*get_group_followers(gid))
        sn = GDevRdsInts.send_cmd(*get_sn_of_gid(gid))

        if primary != user_name and user_name not in followers:
            return {'status': 4}

        # 账号:增加设备和主账号,减少wx账号和操作者账号
        followers.add(primary)
        followers.add(sn)
        followers = filter(lambda u: u[:3] != 'wx#' and u != user_name,
                           followers)

        if primary == user_name:
            for follow in followers:
                GDevRdsInts.send_multi_cmd(
                    *combine_redis_cmds(unfollow_group(gid, sn, follow)))

                if follow[:3] == 'wx#':
                    GDevRdsInts.send_cmd(*hdel_wechat_gid(follow, gid))
                    logger.debug(u'del wechat follow=%r, gid=%r', follow, gid)
                else:
                    GMQDispRdsInts.send_cmd(*shortcut_mq(
                        'cloud_push',
                        # sourcer, cb, from, description
                        push_pack(
                            user_name, 'del_device', 2, '', account=follow)))

            # clean up data
            GDevRdsInts.send_multi_cmd(
                *combine_redis_cmds(unbind_group_primary(gid, sn, primary)))

            old_gid = GDevRdsInts.send_cmd(*get_old_gid(gid))
            if old_gid:
                logger.debug('gid={0}, old_gid={1}'.format(gid, old_gid))
                # gid belonged to nice_gid, keep binding with sn
                GMQDispRdsInts.send_cmd(*shortcut_mq(
                    'gen_mysql',
                    mysql_pack(DB_TBL_DEVICE_INFO, {
                        'primary': '',
                        'status': 'unbound',
                        'mobile': ''
                    },
                               action=2,
                               ref_kvs={'sn': sn})))
            else:
                GMQDispRdsInts.send_cmd(*shortcut_mq(
                    'gen_mysql',
                    mysql_pack(DB_TBL_DEVICE_INFO, {
                        'primary': '',
                        'status': 'unbound',
                        'mobile': ''
                    },
                               action=2,
                               ref_kvs={'sn': sn})))
            GDevRdsInts.send_cmd(*del_all_self_share(sn))
            all_letters_in = GDevRdsInts.send_cmd(*get_letter_inbox(sn, 0, -1))
            for letter_id in all_letters_in:
                GDevRdsInts.send_multi_cmd(
                    *combine_redis_cmds(del_letter_info(letter_id),
                                        del_letter_inbox(sn, letter_id)))

            logger.debug('sn={0}'.format(sn))

            return {'status': 1}
        elif user_name in followers:
            GDevRdsInts.send_multi_cmd(
                *combine_redis_cmds(unfollow_group(gid, sn, user_name)))

            if user_name[:3] == 'wx#':
                GDevRdsInts.send_cmd(*hdel_wechat_gid(user_name, gid))

            logger.debug('send apns followers:%s' % followers)
            for user in followers:
                GMQDispRdsInts.send_cmd(*shortcut_mq(
                    'cloud_push',
                    # sourcer, cb, from, description
                    push_pack(user_name,
                              'unfollow',
                              2,
                              ':'.join((user_name, gid)),
                              account=user)))
            return {'status': 2}