Esempio n. 1
0
def common_file_token(dev_filter, cur_account, fn, mode, ref):
    """
    获取文件上传/下载token,用于file模块认证(时效)
    :param dev_filter: redis object
    :param cur_account: 当前用户
    :param pid: 设备id
    :param fn: 上传/下载文件名
    :param share: 是否共享
    :param mode: 模式,0:上传;1:下载
    :param ref: 上传凭据
    """
    if not cur_account or not is_num(mode):
        return

    ul = int(mode) == 0
    # share = int(share)

    # if share:
    #     primary_account, is_sa = dev_filter.send_multi_cmd(
    #         *combine_redis_cmds(
    #             test_primary_bound(pid),
    #             is_dev_subaccounted(pid, cur_account)
    #         )
    #     )
    #     #主帐号必须有
    #     if primary_account:
    #         primary_account = primary_account.split(':')[-1]
    #         if not (primary_account == cur_account or is_sa):
    #             logger.warn('{0} not pa even sa {1}'.format(pid, cur_account))
    #             return
    #     else:
    #         logger.warn('{0} not bound'.format(pid))
    #         return

    if not ul:
        #下载
        _ = extract_ref(ref)
        if not _:
            logger.warn('downloading, ref extract fail: {0}'.format(ref))
            return

        ref_share, ref_by_app, ref_unique_key, ref_fn = _
        if ref_fn != fn:
            logger.warn('downloading, fn {0} not match {1}'.format(ref_fn, fn))
            return
    else:
        ref_by_app = True
        # ref_share = share

    return {
        'tk': gen_file_tk(cur_account, fn, ul, ref_by_app
                          # ref_share
                          ),
        'by': rc4_encrypt(cur_account, BY_CIPHER_KEY),
    }
Esempio n. 2
0
def down_file(http_rpc_client, user_name, fn, ref):
    """
    下载贝启文件
    :param http_rpc_client: http连接
    :param user_name: 用户名
    :param fn:  文件名
    :param ref: 文件ref
    :return:  file_body
    """
    tk = gen_file_tk(user_name, fn, 0, 0)
    url = 'down?tk={tk}&r={ref}'.format(tk=urllib.quote(tk),
                                        ref=urllib.quote(ref))
    return http_rpc_client.fetch_async(url)
Esempio n. 3
0
def down_beiqi_file(
        user_name,
        fn,
        ref,
        down_file_url='http://localhost:8106/down?tk={tk}&r={ref}'):
    """
    下载贝启文件
    :param user_name: 用户名
    :param fn:  文件名
    :param ref: 文件ref
    :param down_file_url: 贝启文件下载地址
    :return:  file_body
    """
    tk = gen_file_tk(user_name, fn, 0, 0)
    file_url = down_file_url.format(tk=tk, ref=ref)
    return urllib2.urlopen(file_url).read()
Esempio n. 4
0
def msg_2_wechat(cli_user, file_type, fn, ref, thumb_fn, thumb_ref, text):
    """
    客户端发送消息给微信用户
    :param cli_user: 客户端用户
    :param file_type:文件类型
    :param fn: 文件名
    :param ref: 文件标识符
    :param thumb_fn: 快照文件名
    :param thumb_ref: 快照文件标识符
    :param text: 文本
    :return: None
    """
    # 查找微信用户
    groups = get_user_gids(cli_user)
    logger.error('msg_2_wechat:cli_user=%s, groups=%r', cli_user, groups)

    followers = set([])
    [
        followers.update(dev_filter.send_cmd(*get_group_followers(gid)))
        for gid in groups
    ]

    wechat_followers = filter(
        lambda user: user[:3] == 'wx#' and user != cli_user, followers)
    logger.error('msg_2_wechat:cli_user=%s, ref=%r, wechat_followers= %r',
                 cli_user, ref, wechat_followers)

    if not wechat_followers:
        return

    msg_type = file_type_2_msg_type_dic.get(file_type, "")
    if not msg_type:
        logger.error('msg_2_wechat not msg_type, file_type=%s', file_type)
        return

    sender = msg_type_2_wechat_msg_sender.get(msg_type)
    if not sender:
        logger.debug('msg_2_wechat not sender:msg_type=%s', msg_type)
        return

    logger.debug('msg_2_wechat sender:sender=%s', sender.__name__)

    tk = gen_file_tk(cli_user, fn, 0, 0)
    file_url = SSP_DOWNLOAD_FILE_URL % (tk, ref)
    [sender(wc_user.split("#")[1], file_url) for wc_user in wechat_followers]
Esempio n. 5
0
def gen_leveldb_file(CalcRdsInts, user_name, file_type, fn):
    """
    获取leveldb的文件名
    :param CalcRdsInts: rds对象
    :param user_name: 用户名
    :param file_type: 文件类型
    :param fn: 文件名
    :return: file
    """
    ul = 1
    by_app = 0
    usage = 'share'
    tk = gen_file_tk(user_name, fn, ul, by_app)

    tk_params, file_source, usage, unique_sn = ul_args_ok(
        CalcRdsInts, *(bs2utf8(tk), file_type, usage))
    leveldb_fn = gen_lvl_fn(*tk_params)
    return leveldb_fn
Esempio n. 6
0
def up_file(http_rpc_client, user_name, file_type, fn, file_body):
    """
    上传贝启文件
    :param http_rpc_client: http连接
    :param user_name:  发送者用户名
    :param file_type: 文件类型
    :param fn:  文件名
    :param file_body:  文件内容,二进制
    :param up_file_url: 贝启文件上传地址
    :return: ref: 文件ref
    """
    ul = 1
    by_app = 0
    tk = gen_file_tk(user_name, fn, ul, by_app)
    up_args = {'tk': tk, 'src': file_type, 'by': user_name, 'usage': 'share'}

    url = "up?%s" % urllib.urlencode(up_args)

    headers = {'Content-Type': 'application/octet-stream'}
    return ujson.loads(
        http_rpc_client.fetch_async(url, headers=headers, body=file_body))
    def test_upload_file_to_wechat(self):
        access_token = gen_wechat_access_token(GCalcRdsInts)
        print "access_token,",access_token
        self.assertTrue(access_token)

        mp3_path = "test.mp3"
        mp3_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), mp3_path)

        up_file_data = open(mp3_path, 'rb').read()
        fn = str(mp3_path.split('\\')[-1])
        up_resp = up_file(FileSvrHttpRpcClt,TEST_USER_NAME, 3, fn, up_file_data)

        down_url = 'http://{ip}:{port}/down?tk={tk}&r={ref}'.format(
            ip=SERVER_IP,
            port=FILE_SERVER_PORT,
            tk=urllib.quote(gen_file_tk(TEST_USER_NAME, fn, 0, 0)), ref=urllib.quote(up_resp['r']))

        wechat_up_res = wechat_file_up(access_token, down_url, fn)
        print "wechat_up_res,",wechat_up_res
        self.assertTrue('media_id' in wechat_up_res)
        wechat_down_res = wechat_file_down(access_token, wechat_up_res['media_id'])
        self.assertTrue(len(wechat_down_res) > 0)
Esempio n. 8
0
def up_beiqi_file(user_name,
                  file_type,
                  fn,
                  file_body,
                  up_file_url='http://localhost:8106/up?'):
    """
    上传贝启文件
    :param user_name:  发送者用户名
    :param file_type: 文件类型
    :param fn:  文件名
    :param file_body:  文件内容,二进制
    :param up_file_url: 贝启文件上传地址
    :return: ref: 文件ref
    """
    ul = 1
    by_app = 0
    tk = gen_file_tk(user_name, fn, ul, by_app)
    up_args = {'tk': tk, 'src': file_type, 'by': user_name, 'usage': 'share'}
    resp = urllib2.urlopen(
        urllib2.Request(up_file_url + urllib.urlencode(up_args),
                        file_body)).read()
    resp = json.loads(resp)
    return resp.get('r')
Esempio n. 9
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}
Esempio n. 10
0
        logger.error(u'get wechat file failed: {0}'.format(ex), exc_info=True)

    if media_id:
        fn = bs2utf8(
            img.headers.get('Content-disposition').split(';')[1].split('=')
            [1].strip('"'))
        logger.debug('fn = %r', fn)
        content_type = img.headers.get('Content-Type')
        logger.debug(u'content_type = %s' % content_type)
        if content_type.split('/')[0] == 'image':
            file_type = '1'

    logger.debug(u'from_user_name=%s, fn=%s', from_user_name, fn)
    ul = 0
    by_app = 0
    tk = gen_file_tk(from_user_name, fn, ul, by_app)
    logger.debug(u'save wechat file. tk = %r' % tk)
    up_args = {
        'tk': tk,
        'src': file_type,
        'by': from_user_name,
        'usage': 'share'
    }
    for _ in xrange(3):
        logger.debug(u'save wechat file. up_url = %s' %
                     (BEIQI_FILE_UP_URL + urllib.urlencode(up_args)))
        resp = HttpRpcClient().fetch_async(url=BEIQI_FILE_UP_URL +
                                           urllib.urlencode(up_args),
                                           body=img.body)
        if resp.code == 200:
            break