Пример #1
0
    def post(self, account, *args, **kwargs):
        """
    请求发送注册验证短信
        """
        if not is_email(account):
            logger.warn('account:%s illegal' % account)
            return {'status': 1}

        mobile = account.split('@')[0]

        sms_speed = GDevRdsInts.send_cmd(*get_sms_speed())
        if sms_speed is None:
            GDevRdsInts.send_multi_cmd(*combine_redis_cmds(
                *combine_redis_cmds(init_sms_speed())))
        elif sms_speed >= SMS_SPEED_MAX:
            logger.debug('sms speed max, mobile={0}, {1}'.format(
                mobile,
                datetime.now().isoformat()))
            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())))

        if not reg_via_mobile(account, None):
            return {'status': 2}
        return {'status': 0}
Пример #2
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}
Пример #3
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'
Пример #4
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}
Пример #5
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
        }
Пример #6
0
def dev_alias(dev_filter, pid, cur_account, alias):
    """
    设置别名
    :param dev_filter:
    :param pid:
    :param cur_account:
    :param alias:
    :return:
    """
    if not (isinstance(cur_account, str) and isinstance(alias, basestring)):
        return

    pid = rawid_tuple(pid, True)
    if not pid or len(alias) > 15 or ':' in alias:
        return

    alias = bs2utf8(alias)
    pid, typ, sn, io = pid
    #子帐号是否关注,主帐号拥有
    is_sub_fo, primary_account = dev_filter.send_multi_cmd(*combine_redis_cmds(
        is_dev_subaccounted(pid, cur_account), test_primary_bound(pid)))

    if not primary_account:
        return
    _, _, primary_account = primary_account.split(':')
    if not (primary_account == cur_account or is_sub_fo):
        return
    dev_filter.send_cmd(*set_alias(pid, cur_account, alias))
    return True
Пример #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}
Пример #8
0
    def get(self, user_name, pid, *args, **kwargs):
        primary, followers = GDevRdsInts.send_multi_cmd(
            *combine_redis_cmds(get_dev_primary(pid), get_dev_followers(pid)))
        if user_name != primary and user_name not in followers:
            return {'status': 1}

        fences = GDevRdsInts.send_cmd(*get_all_geo_fences(pid))
        return fences
Пример #9
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}
Пример #10
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}
Пример #11
0
    def post(self, user_name, share_id, comment_id, *args, **kwargs):
        if user_name != comment_id.split(':')[-1]:
            logger.debug('delete comment, acc=%r, share_id=%r, comment_id=%r' %
                         (user_name, share_id, comment_id))
            return {'status': 1}

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

        GDevRdsInts.send_multi_cmd(
            *combine_redis_cmds(del_one_comment(share_id, comment_id),
                                del_comment_info(share_id, comment_id)))
        return {'status': 0}
Пример #12
0
def get_mobile(sync_account_redis, api_key, accounts):
    """
    根据帐号获取手机号
    多个accounts,返回多个

    :param accounts: 同时支持单个str和list参数
    :param api_key:
    :param sync_account_redis: 同步redis对象
    :return:
    """
    if api_key and ':' in api_key:
        raise ValueError('wrong arg: %s' % api_key)
    if not isinstance(accounts, (str, list, tuple)):
        raise ValueError('unsupported type: {0}'.format(accounts))

    if not api_key:
        return _extract_mobiles(accounts)
    if api_key in LINKTOP_PREFIX_4 or api_key in LINKTOP_ALL:
        #能命中凌拓key
        return _extract_mobiles(accounts)

    parse_result = parse_oem_options(api_key)
    if not parse_result:
        #非oem帐号
        return _extract_mobiles(accounts)

    _, _, lt_acc, sms, has_mobile, _ = parse_result
    if lt_acc:
        #是凌拓帐号
        return _extract_mobiles(accounts)

    if not has_mobile:
        if isinstance(accounts, str):
            return None
        return (None, ) * len(accounts)

    redis_result = sync_account_redis.send_multi_cmd(
        *combine_redis_cmds(_build_redis_cmd(accounts)))
    ll = tuple(
        _yield_multi((redis_result, ) if
                     (isinstance(redis_result, str)
                      or not redis_result) else redis_result,
                     (accounts, ) if isinstance(accounts, str) else accounts))
    if isinstance(accounts, (list, tuple)):
        return ll
    _ = ll[0]
    del ll
    return _
Пример #13
0
def dev_members(dev_filter, account_cache, pid, cur_account):
    """
    设备成员列表
    :param dev_filter:
    :param account_cache:
    :param pid:
    :param cur_account:
    :return:
    """
    primary, sub_accs, acc_alias_tuple = dev_filter.send_multi_cmd(
        *combine_redis_cmds(test_primary_bound(pid), list_dev_subaccounts(pid),
                            get_all_alias(pid)))
    if not primary:
        return None
    primary = primary.split(':')[-1]
    _ = _member_account(dev_filter, account_cache, pid, cur_account, primary,
                        sub_accs, acc_alias_tuple)
    return _
Пример #14
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}
Пример #15
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
        }
Пример #16
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}
Пример #17
0
def handle_msg(packet):
    """
    account为空时,推送给所有人
    :param packet:
    :return:
    """
    logger.debug('cloud push packet: {0}'.format(packet))
    packet.pop('cancel', None)
    single_account = packet.pop('account', None)
    push_body = packet.pop('p', None)
    channel = packet.pop('ch', None)

    logger.debug('cloud push single_account: {0}, push_body: {1}, channel: {2}'.format(single_account, push_body, channel))
    if channel is None:
        return
    #批量,app
    p_batch, p_app = span_bits(channel, 1, 0, 0)

    if single_account is not None:
        if p_batch:
            logger.warn('cloud_push handle_msg:: not support batch push!!!')
        #单用户,意味着仅一种推送通道,dict对象键值不会受干扰
        #没有必要deepcopy
        if p_app:
            app_1push(push_body, single_account)
        return

    pid = push_body.get('id')
    primary_account, sub_accounts = dev_filter.send_multi_cmd(
        *combine_redis_cmds(test_primary_bound(pid), list_dev_subaccounts(pid)))
    if not primary_account:
        logger.warn('{0} not bound, no push'.format(pid))
        return

    logger.debug('primary account: {0}'.format(primary_account))
    primary_account = primary_account.split(':')[-1]
    sub_accounts.add(primary_account)
    logger.debug('cloud handle_msg sub_accounts: {0}, primary_account: {1}, pid: {2}'.format(sub_accounts, primary_account, pid))
    if p_batch:
        logger.warn('cloud_push handle_msg:: not support batch push!!!')
    if p_app:
        [app_1push(deepcopy(push_body), x) for x in sub_accounts]
Пример #18
0
    def get(self, user_name, sn, *args, **kwargs):
        """
        """
        expect_pa, sub_ok = GDevRdsInts.send_multi_cmd(*combine_redis_cmds(get_dev_primary(sn), test_user_follow_group(user_name, sn)))
        if not expect_pa:
            logger.warn('{0} not bound'.format(sn))
            self.set_status(400)
            return
        if not (expect_pa.split(':')[-1] == user_name or sub_ok):
            logger.warn('{0} not bound, not sa'.format(sn))
            self.set_status(400)
            return

        sql = "select longitude, latitude, altitude, accuracy, address, ad_code," \
              "src_ts as timestamp " \
              "from {db} where sn = '{sn}'" \
              "order by src_ts desc " \
              "limit 1"
        sql = sql.format(db=DB_TBL_LOCATION, sn=sn)
        rec = DBBeiqiSspInst.query(sql)
        return mongo2utf8(rec[0]) if rec else {}
Пример #19
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
Пример #20
0
def find_all_contacts(dev_filter, account_cache, pid):
    """
    查找pid相关的所有帐号
    :param pid:
    :param dev_filter:
    :param account_cache:
    :return:
    """
    primary_account, sub_accounts = dev_filter.send_multi_cmd(
        *combine_redis_cmds(test_primary_bound(pid), list_dev_subaccounts(
            pid)))
    if not primary_account:
        return

    primary_account = primary_account.split(':')[-1]
    sub_accounts = sub_accounts or set()
    sub_accounts.add(primary_account)

    #拥有/关注某设备的用户帐号必定属于同一api_key,因此只需要查询主帐号即可
    _ = account_cache.send_cmd(*get_mb_key(primary_account)) or None
    api_key = _.split(':')[-1] if _ else None
    oem_ob = oem_accounts.get(api_key)
    if oem_ob:
        api_key = oem_ob.get('opt_mask') or api_key

    sub_accounts = tuple(sub_accounts)
    #根据get_mobile函数的约定
    #sub_accounts参数为tuple,则mobiles返回值不管有无,均为tuple/list类型
    mobiles = get_mobile(account_cache, api_key, sub_accounts)
    if isinstance(mobiles, str):
        mobiles = (mobiles, )
    if len(mobiles) != len(sub_accounts):
        logger.warn('mobile neq sub_accs: {0}, {1}'.format(
            mobiles, sub_accounts))
        return
    for x in izip(mobiles, sub_accounts):
        yield x
Пример #21
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}
Пример #22
0
    def post(self, user_name, code, msg='', file='', *args, **kwargs):
        if len(code) == 6:
            primary = GDevRdsInts.send_cmd(*get_group_primary(code))
            if not primary:
                return {'status': 3}

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

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

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

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

            GMQDispRdsInts.send_cmd(*shortcut_mq(
                'cloud_push',
                push_pack(user_name, 'follow', 2, payload, account=primary)))
            logger.debug(
                'follow, acc={0}, followee={1}, msg={2}, file={3}'.format(
                    user_name, code, msg, file))
            return {'status': 1}

        elif len(code) == 9:
            # 识别码, 绑定
            sn = GDevRdsInts.send_cmd(*get_ic_sn(code))
            if not sn:
                return {'status': 4}
            gid = GDevRdsInts.send_cmd(*get_gid_of_sn(sn))
            primary = GDevRdsInts.send_cmd(*get_dev_primary(sn))
            if primary:
                return {'status': 5}

            real_ic = GDevRdsInts.send_cmd(*get_sn_ic(sn))
            if real_ic != code:
                return {'status': 6}

            mobile = user_name.split('@')
            mobile = mobile[0] if len(mobile) > 1 else ''
            logger.debug('bind, acc={0}, sn={1}, code={2}'.format(
                user_name, sn, code))

            GMQDispRdsInts.send_multi_cmd(*combine_redis_cmds(
                # sourcer, cb, from, description
                shortcut_mq(
                    'cloud_push',
                    push_pack(user_name,
                              'bind',
                              2,
                              ':'.join((user_name, sn)),
                              account=sn)),
                shortcut_mq(
                    'gen_mysql',
                    mysql_pack(DB_TBL_DEVICE_INFO, {
                        'primary': user_name,
                        'status': 'binded',
                        'mobile': mobile
                    },
                               action=2,
                               ref_kvs={'sn': sn}))))

            logger.debug('bind push sent')
            GDevRdsInts.send_multi_cmd(
                *combine_redis_cmds(bind_group_primary(gid, sn, user_name),
                                    del_ic_sn(code), del_sn_ic(sn)))
            return {'status': 2}

        else:
            return {'status': 7}
Пример #23
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}
Пример #24
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}
Пример #25
0
 def post(self, user_name, letter_id, *args, **kwargs):
     GDevRdsInts.send_multi_cmd(
         *combine_redis_cmds(del_letter_info(letter_id),
                             del_letter_inbox(user_name, letter_id)))
     return {'status': 0}
Пример #26
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}