コード例 #1
0
ファイル: test_utils.py プロジェクト: leishenailong/picbed
 def test_utils(self):
     self.assertEqual("900150983cd24fb0d6963f7d28e17f72", md5("abc"))
     self.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d",
                      sha1("abc"))
     self.assertEqual("picbed:a:b", rsp("a", "b"))
     self.assertEqual(parse_valid_comma("a,b, c,"), ["a", "b", "c"])
     self.assertEqual(parse_valid_verticaline("a|b| c"), ["a", "b", "c"])
     self.assertTrue(is_true(1))
     self.assertTrue(is_true("on"))
     self.assertTrue(is_true("true"))
     self.assertFalse(is_true(0))
     self.assertIsInstance(get_current_timestamp(), int)
     self.assertTrue(allowed_file("test.PNG"))
     self.assertTrue(allowed_file(".jpeg"))
     self.assertFalse(allowed_file("my.psd"))
     self.assertFalse(allowed_file("ha.gif", ["jpg"]))
     self.assertFalse(allowed_file("ha.jpeg", ["jpg"]))
     self.assertFalse(allowed_file("ha.png", ["jpg"]))
     self.assertTrue(allowed_file("ha.jpg", ["jpg"]))
     v = "6afa9046a9579cad143a384c1b564b9a250d27d6f6a63f9f20bf3a7594c9e2c6"
     self.assertEqual(v, hmac_sha256('key', 'text'))
     self.assertEqual(v, hmac_sha256(b'key', b'text'))
     self.assertEqual(v, hmac_sha256(u'key', u'text'))
     self.assertEqual(
         "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
         sha256("abc"))
コード例 #2
0
ファイル: token.py プロジェクト: copyit/picbed
def verify_rule(Ld):
    """根据er、ir规则判断是否放行请求"""
    allow = Attribution(
        dict(
            ip=Attribution(
                dict(access=get_ip(), secure=parse_valid_comma(Ld["allow_ip"]) or [])
            ),
            origin=Attribution(
                dict(
                    access=get_origin(),
                    secure=parse_valid_comma(Ld["allow_origin"]) or [],
                )
            ),
            ep=Attribution(
                dict(
                    access=request.endpoint,
                    secure=parse_valid_comma(Ld["allow_ep"]) + ["api.index"],
                )
            ),
            method=Attribution(
                dict(
                    access=request.method,
                    secure=[
                        m.upper()
                        for m in parse_valid_comma(Ld["allow_method"]) or []
                        if m
                    ],
                )
            ),
        )
    )
    #: 参数 逻辑运算符 参数 逻辑运算符 参数...
    #: 参数: origin and ip and ep and method
    #: 逻辑运算符: and or not in not in
    #: er控制的是参与逻辑运算的参数及之间的逻辑运算符
    #: ir控制的是参数如何返回True
    er = Ld["exterior_relation"]
    ir = Ld["interior_relation"]
    if not er:
        er = "origin and ip and ep and method"
    #: ir定义的最终规则
    ir_cmd = _allow_ir(ir, allow)
    #: 综合er、ir构建最终执行的命令字符串
    for opt in ALLOWED_RULES:
        er = er.replace(opt, ir_cmd[opt])
    logger.debug("last er: %s" % er)
    return eval(er)
コード例 #3
0
ファイル: api.py プロジェクト: howardyan93/picbed
 def check_body():
     """校验post、put参数,返回值有效说明校验不通过"""
     allow_origin = request.form.get("allow_origin")
     allow_ip = request.form.get("allow_ip")
     allow_ep = request.form.get("allow_ep")
     allow_method = request.form.get("allow_method")
     er = request.form.get("exterior_relation")
     ir = request.form.get("interior_relation")
     if allow_origin:
         origins = parse_valid_comma(allow_origin)
         if not origins or not isinstance(origins, (tuple, list)):
             return "Invalid url address"
         for url in origins:
             if url and not check_origin(url):
                 return "Invalid url address"
     if allow_ip:
         ips = parse_valid_comma(allow_ip)
         if not ips or not isinstance(ips, (tuple, list)):
             return "Invalid IP address"
         for ip in ips:
             if ip and not check_ip(ip):
                 return "Invalid IP address"
     if allow_ep:
         eps = parse_valid_comma(allow_ep)
         if not eps or not isinstance(eps, (tuple, list)):
             return "Not found the endpoint"
         for ep in eps:
             if ep and ep not in current_app.view_functions.keys():
                 return "Not found the endpoint"
     if allow_method:
         methods = parse_valid_comma(allow_method)
         if not methods or not isinstance(methods, (tuple, list)):
             return "Invalid HTTP method"
         for md in methods:
             if md and md.upper() not in ["GET", "POST", "PUT", "DELETE"]:
                 return "Invalid HTTP method"
     if er:
         if not er_pat.match(er.strip()):
             return "Invalid exterior_relation"
     if ir:
         if not ir_pat.match(ir.strip()):
             return "Invalid interior_relation"
         else:
             try:
                 check_ir(ir)
             except (ValueError, TypeError):
                 return "Invalid interior_relation"
コード例 #4
0
ファイル: token.py プロジェクト: 993544899/picbed
def _parse_ir(ir):
    """解析ir规则,其格式是: in:opt1, not in:opt2"""
    if ir:
        rules = {}
        for i in parse_valid_comma(ir):
            opr, opt = i.split(":")
            if opt in ALLOWED_RULES and opr in ("in", "not in"):
                rules[opt] = opr
        return rules
コード例 #5
0
ファイル: app.py プロジェクト: skymysky/picbed
def after_request(res):
    #: Trigger hook, you can modify the response
    hm.call("after_request", res=res)
    if g.cfg.cors:
        if g.cfg.cors == "*":
            res.headers.add("Access-Control-Allow-Origin", "*")
        else:
            cors = parse_valid_comma(g.cfg.cors)
            origin = request.headers.get("Origin")
            if origin in cors:
                res.headers.add("Access-Control-Allow-Origin", origin)
    return res
コード例 #6
0
def after_request(res):
    #: Trigger hook, you can modify the response
    hm.call("after_request", _args=(res, ))
    if g.cfg.cors:
        if g.cfg.cors == "*":
            res.headers.add("Access-Control-Allow-Origin", "*")
        else:
            cors = parse_valid_comma(g.cfg.cors)
            origin = request.headers.get("Origin")
            if origin in cors:
                res.headers.add("Access-Control-Allow-Origin", origin)
    res.headers['X-Content-Type-Options'] = 'nosniff'
    res.headers['X-Frame-Options'] = 'SAMEORIGIN'
    return res
コード例 #7
0
def upload():
    """上传逻辑:
    0. 判断是否登录,如果未登录则判断是否允许匿名上传
    1. 获取上传的文件,判断允许格式
    2. 生成文件名、唯一sha值、上传目录等,选择图片存储的后端钩子(单一)
        - 存储图片的钩子目前版本仅一个,默认是up2local(如果禁用则保存失败)
    3. 解析钩子数据,钩子回调数据格式:{code=?, sender=hook_name, src=?}
        - 后端保存失败或无后端的情况都要立刻返回响应
    4. 此时保存图片成功,持久化存储到全局索引、用户索引
    5. 返回响应:{code:0, data={src=?, sender=success_saved_hook_name}}
    """
    res = dict(code=1, msg=None)
    #: 匿名上传开关检测
    if not is_true(g.cfg.anonymous) and not g.signin:
        res.update(code=403, msg="Anonymous user is not sign in")
        return res
    f = request.files.get('picbed')
    #: 实时获取后台配置中允许上传的后缀,如: jpg|jpeg|png
    allowed_suffix = partial(allowed_file,
                             suffix=parse_valid_verticaline(g.cfg.upload_exts))
    if f and allowed_suffix(f.filename):
        try:
            g.rc.ping()
        except RedisError as e:
            logger.error(e, exc_info=True)
            res.update(code=2, msg="Program data storage service error")
            return res
        stream = f.stream.read()
        suffix = splitext(f.filename)[-1]
        filename = secure_filename(f.filename)
        if "." not in filename:
            filename = "%s%s" % (generate_random(8), suffix)
        #: 根据文件名规则重定义图片名
        upload_file_rule = g.cfg.upload_file_rule
        if upload_file_rule in ("time1", "time2", "time3"):
            filename = "%s%s" % (gen_rnd_filename(upload_file_rule), suffix)
        #: 上传文件位置前缀规则
        upload_path_rule = g.cfg.upload_path_rule
        if upload_path_rule == 'date1':
            upload_path = get_today("%Y/%m/%d")
        elif upload_path_rule == 'date2':
            upload_path = get_today("%Y%m%d")
        else:
            upload_path = ''
        upload_path = join(g.userinfo.username or 'anonymous', upload_path)
        #: 定义文件名唯一索引
        sha = "sha1.%s.%s" % (get_current_timestamp(True), sha1(filename))
        #: 定义保存图片时仅使用某些钩子,如: up2local
        #: TODO 目前版本仅允许设置了一个,后续考虑聚合
        includes = parse_valid_comma(g.cfg.upload_includes or 'up2local')
        if len(includes) > 1:
            includes = [choice(includes)]
        #: TODO 定义保存图片时排除某些钩子,如: up2local, up2other
        # excludes = parse_valid_comma(g.cfg.upload_excludes or '')
        #: 钩子返回结果(目前版本最终结果中应该最多只有1条数据)
        data = []

        #: 保存图片的钩子回调
        def callback(result):
            logger.info(result)
            if result["sender"] == "up2local":
                result["src"] = url_for("static",
                                        filename=join(UPLOAD_FOLDER,
                                                      upload_path, filename),
                                        _external=True)
            data.append(dfr(result))

        #: 调用钩子中upimg_save方法
        current_app.extensions["hookmanager"].call(
            _funcname="upimg_save",
            _callback=callback,
            _include=includes,
            filename=filename,
            stream=stream,
            upload_path=upload_path,
            local_basedir=join(current_app.root_path,
                               current_app.static_folder, UPLOAD_FOLDER))
        #: 判定后端存储全部失败时,上传失败
        if not data:
            res.update(code=1, msg="No valid backend storage service")
            return res
        if len(data) == len([i for i in data if i.get("code") != 0]):
            res.update(
                code=1,
                msg="All backend storage services failed to save pictures")
            return res
        #: 存储数据
        defaultSrc = data[0]["src"]
        pipe = g.rc.pipeline()
        pipe.sadd(rsp("index", "global"), sha)
        if g.signin and g.userinfo.username:
            pipe.sadd(rsp("index", "user", g.userinfo.username), sha)
        pipe.hmset(
            rsp("image", sha),
            dict(
                sha=sha,
                filename=filename,
                upload_path=upload_path,
                user=g.userinfo.username if g.signin else 'anonymous',
                ctime=get_current_timestamp(),
                status='enabled',  # disabled, deleted
                src=defaultSrc,
                sender=data[0]["sender"],
                senders=json.dumps(data)))
        try:
            pipe.execute()
        except RedisError as e:
            logger.error(e, exc_info=True)
            res.update(code=3, msg="Program data storage service error")
        else:
            res.update(
                code=0,
                filename=filename,
                sender=data[0]["sender"],
                api=url_for("api.shamgr", sha=sha, _external=True),
            )
            #: format指定图片地址的显示字段,默认src,可以用点号指定
            #: 比如data.src,那么返回格式{code, filename..., data:{src}, ...}
            fmt = request.form.get("format", request.args.get("format"))
            res.update(format_upload_src(fmt, defaultSrc))
    else:
        res.update(msg="No file or image format allowed")
    return res
コード例 #8
0
ファイル: api.py プロジェクト: howardyan93/picbed
def link():
    res = dict(code=1, msg=None)
    ltk = rsp("linktokens")
    username = g.userinfo.username

    def check_body():
        """校验post、put参数,返回值有效说明校验不通过"""
        allow_origin = request.form.get("allow_origin")
        allow_ip = request.form.get("allow_ip")
        allow_ep = request.form.get("allow_ep")
        allow_method = request.form.get("allow_method")
        er = request.form.get("exterior_relation")
        ir = request.form.get("interior_relation")
        if allow_origin:
            origins = parse_valid_comma(allow_origin)
            if not origins or not isinstance(origins, (tuple, list)):
                return "Invalid url address"
            for url in origins:
                if url and not check_origin(url):
                    return "Invalid url address"
        if allow_ip:
            ips = parse_valid_comma(allow_ip)
            if not ips or not isinstance(ips, (tuple, list)):
                return "Invalid IP address"
            for ip in ips:
                if ip and not check_ip(ip):
                    return "Invalid IP address"
        if allow_ep:
            eps = parse_valid_comma(allow_ep)
            if not eps or not isinstance(eps, (tuple, list)):
                return "Not found the endpoint"
            for ep in eps:
                if ep and ep not in current_app.view_functions.keys():
                    return "Not found the endpoint"
        if allow_method:
            methods = parse_valid_comma(allow_method)
            if not methods or not isinstance(methods, (tuple, list)):
                return "Invalid HTTP method"
            for md in methods:
                if md and md.upper() not in ["GET", "POST", "PUT", "DELETE"]:
                    return "Invalid HTTP method"
        if er:
            if not er_pat.match(er.strip()):
                return "Invalid exterior_relation"
        if ir:
            if not ir_pat.match(ir.strip()):
                return "Invalid interior_relation"
            else:
                try:
                    check_ir(ir)
                except (ValueError, TypeError):
                    return "Invalid interior_relation"

    if request.method == "GET":
        is_mgr = is_true(request.args.get("is_mgr"))
        linktokens = g.rc.hgetall(ltk)
        pipe = g.rc.pipeline()
        for ltid, usr in iteritems(linktokens):
            if is_mgr and g.is_admin:
                pipe.hgetall(rsp("linktoken", ltid))
            else:
                if username == usr:
                    pipe.hgetall(rsp("linktoken", ltid))
        try:
            result = pipe.execute()
        except RedisError:
            res.update(msg="Program data storage service error")
        else:
            res.update(code=0, data=result, count=len(result))

    elif request.method == "POST":
        comment = request.form.get("comment") or ""
        #: 定义此引用上传图片时默认设置的相册名
        album = request.form.get("album") or ""
        #: 定义以下几个权限之间的允许访问条件,opt and/or/not opt
        er = request.form.get("exterior_relation", "").strip()
        #: 定义权限内部允许访问条件 in/not in:opt,
        ir = request.form.get("interior_relation", "").strip()
        #: 定义权限项及默认值,检测参数时不包含默认值
        allow_origin = request.form.get("allow_origin") or ""
        allow_ip = request.form.get("allow_ip") or ""
        allow_ep = request.form.get("allow_ep") or "api.upload"
        allow_method = request.form.get("allow_method") or "post"
        #: 判断用户是否有token
        ak = rsp("account", username)
        if not g.rc.hget(ak, "token"):
            res.update(msg="No tokens yet")
            return res
        cv = check_body()
        if cv:
            res.update(msg=cv)
            return res
        if allow_origin:
            allow_origin = ",".join([
                get_origin(url) for url in parse_valid_comma(allow_origin)
                if url
            ])
        #: 生成一个引用
        LinkId = gen_uuid()
        LinkSecret = generate_password_hash(LinkId)
        lid = "%s:%s:%s" % (get_current_timestamp(), LinkId,
                            hmac_sha256(LinkId, LinkSecret))
        LinkToken = b64encode(lid.encode("utf-8")).decode("utf-8")
        pipe = g.rc.pipeline()
        pipe.hset(ltk, LinkId, username)
        pipe.hmset(
            rsp("linktoken", LinkId),
            dict(
                LinkId=LinkId,
                LinkSecret=LinkSecret,
                LinkToken=LinkToken,
                ctime=get_current_timestamp(),
                user=username,
                comment=comment,
                album=album,
                status=1,  # 状态,1是启用,0是禁用
                allow_origin=allow_origin,
                allow_ip=allow_ip,
                allow_ep=allow_ep,
                allow_method=allow_method,
                exterior_relation=er,
                interior_relation=ir,
            ))
        try:
            pipe.execute()
        except RedisError:
            res.update(msg="Program data storage service error")
        else:
            res.update(code=0, LinkToken=LinkToken)

    elif request.method == "PUT":
        LinkId = request.form.get("LinkId")
        Action = request.args.get("Action")
        key = rsp("linktoken", LinkId)
        if Action == "disable":
            try:
                g.rc.hset(key, "status", 0)
            except RedisError:
                res.update(msg="Program data storage service error")
            else:
                res.update(code=0)
            return res
        elif Action == "enable":
            try:
                g.rc.hset(key, "status", 1)
            except RedisError:
                res.update(msg="Program data storage service error")
            else:
                res.update(code=0)
            return res
        if LinkId and g.rc.exists(key):
            comment = request.form.get("comment") or ""
            album = request.form.get("album") or ""
            er = request.form.get("exterior_relation", "").strip()
            ir = request.form.get("interior_relation", "").strip()
            allow_origin = request.form.get("allow_origin") or ""
            allow_ip = request.form.get("allow_ip") or ""
            allow_ep = request.form.get("allow_ep") or "api.upload"
            allow_method = request.form.get("allow_method") or "post"
            cv = check_body()
            if cv:
                res.update(msg=cv)
                return res
            if allow_origin:
                allow_origin = ",".join([
                    get_origin(url) for url in parse_valid_comma(allow_origin)
                    if url
                ])
            pipe = g.rc.pipeline()
            pipe.hset(ltk, LinkId, username)
            pipe.hmset(
                key,
                dict(
                    mtime=get_current_timestamp(),
                    comment=comment,
                    album=album,
                    allow_origin=allow_origin,
                    allow_ip=allow_ip,
                    allow_ep=allow_ep,
                    allow_method=allow_method,
                    exterior_relation=er,
                    interior_relation=ir,
                ))
            try:
                pipe.execute()
            except RedisError:
                res.update(msg="Program data storage service error")
            else:
                res.update(code=0)
        else:
            res.update(msg="Not found the LinkId")

    elif request.method == "DELETE":
        LinkId = request.form.get("LinkId")
        if LinkId:
            pipe = g.rc.pipeline()
            pipe.hdel(ltk, LinkId)
            pipe.delete(rsp("linktoken", LinkId))
            try:
                pipe.execute()
            except RedisError:
                res.update(msg="Program data storage service error")
            else:
                res.update(code=0)
        else:
            res.update(msg="Parameter error")

    return res
コード例 #9
0
ファイル: api.py プロジェクト: howardyan93/picbed
def upload():
    """上传逻辑:
    0. 判断是否登录,如果未登录则判断是否允许匿名上传
    1. 获取上传的文件,判断允许格式
        - 拦截下判断文件,如果为空,尝试获取body中提交的picbed
        - 如果picbed是合法base64,那么会返回Base64FileStorage类;
          如果picbed是合法url[图片],那么服务端会自动下载,返回ImgUrlFileStorage类;
          否则为空。
          PS: 允许DATA URI形式, eg: data:image/png;base64,the base64 of image
    2. 生成文件名、唯一sha值、上传目录等,选择图片存储的后端钩子(单一)
        - 存储图片的钩子目前版本仅一个,默认是up2local(如果禁用则保存失败)
        - 如果提交album参数会自动创建相册,否则归档到默认相册
    3. 解析钩子数据,钩子回调数据格式:{code=?, sender=hook_name, src=?}
        - 后端保存失败或无后端的情况都要立刻返回响应
    4. 此时保存图片成功,持久化存储到全局索引、用户索引
    5. 返回响应:{code:0, data={src=?, sender=success_saved_hook_name}}
        - 允许使用一些参数调整响应数据、格式
    """
    res = dict(code=1, msg=None)
    #: 文件域或base64上传字段
    FIELD_NAME = g.cfg.upload_field or "picbed"
    #: 匿名上传开关检测
    if not is_true(g.cfg.anonymous) and not g.signin:
        res.update(code=403, msg="Anonymous user is not sign in")
        return res
    #: 相册名称,可以是任意字符串
    album = (request.form.get("album")
             or getattr(g, "up_album", "")) if g.signin else 'anonymous'
    #: 实时获取后台配置中允许上传的后缀,如: jpg|jpeg|png
    allowed_suffix = partial(allowed_file,
                             suffix=parse_valid_verticaline(g.cfg.upload_exts))
    #: 尝试读取上传数据
    fp = request.files.get(FIELD_NAME)
    #: 当fp无效时尝试读取base64或url
    if not fp:
        picstrurl = request.form.get(FIELD_NAME)
        filename = request.form.get("filename")
        if picstrurl:
            if picstrurl.startswith("http://") or \
                    picstrurl.startswith("https://"):
                fp = ImgUrlFileStorage(picstrurl, filename).getObj
            else:
                try:
                    #: base64在部分场景发起http请求时,+可能会换成空格导致异常
                    fp = Base64FileStorage(picstrurl, filename)
                except ValueError as e:
                    logger.debug(e)
    if fp and allowed_suffix(fp.filename):
        try:
            g.rc.ping()
        except RedisError as e:
            logger.error(e, exc_info=True)
            res.update(code=2, msg="Program data storage service error")
            return res
        stream = fp.stream.read()
        suffix = splitext(fp.filename)[-1]
        filename = secure_filename(fp.filename)
        if "." not in filename:
            filename = "%s%s" % (generate_random(8), suffix)
        #: 根据文件名规则重定义图片名
        upload_file_rule = (
            g.userinfo.ucfg_upload_file_rule
            or g.cfg.upload_file_rule) if is_true(
                g.cfg.upload_rule_overridden) else g.cfg.upload_file_rule
        if upload_file_rule in ("time1", "time2", "time3"):
            filename = "%s%s" % (gen_rnd_filename(upload_file_rule), suffix)
        #: 上传文件位置前缀规则
        upload_path_rule = (
            g.userinfo.ucfg_upload_path_rule
            or g.cfg.upload_path_rule) if is_true(
                g.cfg.upload_rule_overridden) else g.cfg.upload_path_rule
        if upload_path_rule == 'date1':
            upload_path = get_today("%Y/%m/%d")
        elif upload_path_rule == 'date2':
            upload_path = get_today("%Y%m%d")
        else:
            upload_path = ''
        upload_path = join(g.userinfo.username or 'anonymous', upload_path)
        #: 定义文件名唯一索引
        sha = "sha1.%s.%s" % (get_current_timestamp(True), sha1(filename))
        #: 定义保存图片时仅使用某些钩子,如: up2local
        #: TODO 目前版本仅允许设置了一个,后续聚合
        includes = parse_valid_comma(g.cfg.upload_includes or 'up2local')
        if len(includes) > 1:
            includes = [choice(includes)]
        #: TODO 定义保存图片时排除某些钩子,如: up2local, up2other
        # excludes = parse_valid_comma(g.cfg.upload_excludes or '')
        #: 钩子返回结果(目前版本最终结果中应该最多只有1条数据)
        data = []

        #: 保存图片的钩子回调

        def callback(result):
            logger.info(result)
            if result["sender"] == "up2local":
                result["src"] = url_for("static",
                                        filename=join(UPLOAD_FOLDER,
                                                      upload_path, filename),
                                        _external=True)
            data.append(dfr(result))

        #: 调用钩子中upimg_save方法
        current_app.extensions["hookmanager"].call(
            _funcname="upimg_save",
            _callback=callback,
            _include=includes,
            filename=filename,
            stream=stream,
            upload_path=upload_path,
            local_basedir=join(current_app.root_path,
                               current_app.static_folder, UPLOAD_FOLDER))
        #: 判定后端存储全部失败时,上传失败
        if not data:
            res.update(code=1, msg="No valid backend storage service")
            return res
        if len(data) == len([i for i in data if i.get("code") != 0]):
            res.update(
                code=1,
                msg="All backend storage services failed to save pictures",
                errors={
                    i["sender"]: i["msg"]
                    for i in data if i.get("code") != 0
                },
            )
            return res
        #: 存储数据
        defaultSrc = data[0]["src"]
        pipe = g.rc.pipeline()
        pipe.sadd(rsp("index", "global"), sha)
        if g.signin and g.userinfo.username:
            pipe.sadd(rsp("index", "user", g.userinfo.username), sha)
        pipe.hmset(
            rsp("image", sha),
            dict(
                sha=sha,
                album=album,
                filename=filename,
                upload_path=upload_path,
                user=g.userinfo.username if g.signin else 'anonymous',
                ctime=get_current_timestamp(),
                status='enabled',  # disabled, deleted
                src=defaultSrc,
                sender=data[0]["sender"],
                senders=json.dumps(data),
                agent=request.form.get("origin",
                                       request.headers.get('User-Agent', '')),
                method=getUploadMethod(fp.__class__.__name__),
            ))
        try:
            pipe.execute()
        except RedisError as e:
            logger.error(e, exc_info=True)
            res.update(code=3, msg="Program data storage service error")
        else:
            res.update(
                code=0,
                filename=filename,
                sender=data[0]["sender"],
                api=url_for("api.shamgr", sha=sha, _external=True),
            )
            #: format指定图片地址的显示字段,默认src,可以用点号指定
            #: 比如data.src,那么返回格式{code, filename..., data:{src}, ...}
            #: 比如imgUrl,那么返回格式{code, filename..., imgUrl(=src), ...}
            fmt = request.form.get("format", request.args.get("format"))
            res.update(format_upload_src(fmt, defaultSrc))
    else:
        res.update(msg="No file or image format error")
    return res
コード例 #10
0
ファイル: api.py プロジェクト: howardyan93/picbed
def waterfall():
    res = dict(code=1, msg=None)
    #: 依次根据ctime、filename排序
    sort = request.args.get("sort") or "desc"
    #: 符合人类习惯的page,第一页是1(程序计算需要减1)
    page = request.args.get("page") or 1
    #: 返回数据条数
    limit = request.args.get("limit") or 10
    #: 管理员账号读取所有图片数据
    is_mgr = is_true(request.args.get("is_mgr"))
    #: 相册,当album不为空时,近返回此相册数据,允许逗号分隔多个
    album = request.args.get("album", request.form.get("album"))
    try:
        page = int(page) - 1
        limit = int(limit)
        if page < 0:
            raise ValueError
    except (ValueError, TypeError):
        res.update(code=2, msg="Parameter error")
    else:
        if g.userinfo.username:
            if is_mgr and g.is_admin:
                uk = rsp("index", "global")
            else:
                uk = rsp("index", "user", g.userinfo.username)
            pipe = g.rc.pipeline()
            for sha in g.rc.smembers(uk):
                pipe.hgetall(rsp("image", sha))
            try:
                result = pipe.execute()
            except RedisError:
                res.update(msg="Program data storage service error")
            else:
                #: 最终返回的经过过滤、排序等处理后的数据
                data = []
                #: 该用户或管理员级别所能查看的所有相册
                albums = []
                ask_albums = parse_valid_comma(album)
                if result and isinstance(result, (tuple, list)):
                    for i in result:
                        albums.append(i.get("album"))
                        i.update(
                            senders=json.loads(i["senders"]),
                            ctime=int(i["ctime"]),
                        )
                        if ask_albums:
                            if i.get("album") in ask_albums:
                                data.append(i)
                        else:
                            data.append(i)
                data = sorted(data,
                              key=lambda k:
                              (k.get('ctime', 0), k.get('filename', '')),
                              reverse=False if sort == "asc" else True)
                count = len(data)
                data = ListEqualSplit(data, limit)
                pageCount = len(data)
                if page < pageCount:
                    res.update(
                        code=0,
                        count=count,
                        data=data[page],
                        pageCount=pageCount,
                        albums=list(set([i for i in albums if i])),
                    )
                else:
                    res.update(code=3, msg="No data")
        else:
            res.update(msg="No valid username found")
    return res
コード例 #11
0
ファイル: test_utils.py プロジェクト: copyit/picbed
 def test_utils(self):
     self.assertEqual("900150983cd24fb0d6963f7d28e17f72", md5("abc"))
     self.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d",
                      sha1("abc"))
     self.assertEqual("picbed:a:b", rsp("a", "b"))
     self.assertEqual(parse_valid_comma("a,b, c,"), ["a", "b", "c"])
     self.assertEqual(parse_valid_verticaline("a|b| c"), ["a", "b", "c"])
     self.assertTrue(is_true(1))
     self.assertTrue(is_true("on"))
     self.assertTrue(is_true("true"))
     self.assertFalse(is_true(0))
     self.assertIsInstance(get_current_timestamp(), int)
     self.assertTrue(allowed_file("test.PNG"))
     self.assertTrue(allowed_file(".jpeg"))
     self.assertFalse(allowed_file("my.psd"))
     self.assertFalse(allowed_file("ha.gif", ["jpg"]))
     self.assertFalse(allowed_file("ha.jpeg", ["jpg"]))
     self.assertFalse(allowed_file("ha.png", ["jpg"]))
     self.assertTrue(allowed_file("ha.jpg", ["jpg"]))
     v = "6afa9046a9579cad143a384c1b564b9a250d27d6f6a63f9f20bf3a7594c9e2c6"
     self.assertEqual(v, hmac_sha256("key", "text"))
     self.assertEqual(v, hmac_sha256(b"key", b"text"))
     self.assertEqual(v, hmac_sha256(u"key", u"text"))
     self.assertEqual(
         "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
         sha256("abc"),
     )
     #: test format_upload_src
     baseimg = "img-url"
     basefmt = {"src": baseimg}
     self.assertEqual(format_upload_src(123, baseimg), basefmt)
     self.assertEqual(format_upload_src(None, baseimg), basefmt)
     self.assertEqual(format_upload_src([0], baseimg), basefmt)
     self.assertEqual(format_upload_src("", baseimg), basefmt)
     self.assertEqual(format_upload_src(".", baseimg), basefmt)
     self.assertEqual(format_upload_src(".1", baseimg), basefmt)
     self.assertEqual(format_upload_src("1.", baseimg), basefmt)
     self.assertEqual(format_upload_src(1.1, baseimg), basefmt)
     self.assertEqual(format_upload_src("1.1", baseimg),
                      {"1": {
                          "1": baseimg
                      }})
     self.assertEqual(format_upload_src("u", baseimg), basefmt)
     self.assertEqual(format_upload_src("im", baseimg), {"im": baseimg})
     self.assertEqual(format_upload_src("url", baseimg), {"url": baseimg})
     self.assertEqual(format_upload_src("i.am.src", baseimg), basefmt)
     self.assertEqual(format_upload_src("src.url", baseimg),
                      {"src": {
                          "url": baseimg
                      }})
     #: test format_apires
     self.assertEqual(format_apires({"code": 0}, "success", "bool"),
                      {"success": True})
     self.assertEqual(format_apires({"code": 0}, oc="200"), {"code": 200})
     self.assertEqual(format_apires({"code": -1}, "status", "bool"),
                      {"status": False})
     self.assertEqual(
         format_apires(dict(code=-1, msg="xxx"), "errno", "200"),
         {
             "errno": -1,
             "msg": "xxx"
         },
     )
     self.assertEqual(
         format_apires(dict(code=-1, msg="xxx"), "errno", "200", "errmsg"),
         {
             "errno": -1,
             "errmsg": "xxx"
         },
     )
     self.assertEqual(
         format_apires(dict(code=0, msg="xxx"), "", "200", "errmsg"),
         {
             "code": 200,
             "errmsg": "xxx"
         },
     )
     self.assertEqual(len(generate_random()), 6)
     self.assertIn("Mozilla/5.0", gen_ua())
     # bleach
     self.assertEqual(bleach_html("<i>abc</i>"), "<i>abc</i>")
     self.assertEqual(
         bleach_html("<script>var abc</script>"),
         "&lt;script&gt;var abc&lt;/script&gt;",
     )
     # re
     self.assertEqual(parse_author_mail("staugur"), ("staugur", None))
     self.assertEqual(parse_author_mail("staugur <mail>"),
                      ("staugur", "mail"))
コード例 #12
0
def upload():
    #: 视频上传接口,上传流程:
    #: 1. 必须登录,通过固定的picbed字段获取上传内容
    #: 2. 生成sha,文件名规则是年月日时分秒原名,上传到用户目录下
    #: 3. 保存到后端,存储数据返回响应
    res = dict(code=1, msg=None)
    if not g.signin:
        res.update(code=403, msg="Anonymous user is not sign in")
        return res
    if g.userinfo.status != 1:
        msg = ("Pending review, cannot upload pictures" if g.userinfo.status
               in (-2, -1) else "The user is disabled, no operation")
        res.update(code=403, msg=msg)
        return res
    allowed_suffix = partial(allowed_file,
                             suffix=("mp4", "ogg", "ogv", "webm", "3gp",
                                     "mov"))
    fp = request.files.get("picbed")
    title = request.form.get("title") or ""
    if not fp or not allowed_suffix(fp.filename):
        res.update(msg="No file or image format error")
        return res
    suffix = splitext(fp.filename)[-1]
    filename = secure_filename(fp.filename)
    if "." not in filename:
        filename = "%s%s" % (generate_random(8), suffix)
    stream = fp.stream.read()
    upload_path = join(g.userinfo.username, get_today("%Y/%m/%d"))
    sha = "sha256.%s.%s" % (get_current_timestamp(True), sha256(filename))
    includes = parse_valid_comma(g.cfg.upload_includes or 'up2local')
    if len(includes) > 1:
        includes = [choice(includes)]
    data = current_app.extensions["hookmanager"].call(
        _funcname="upimg_save",
        _include=includes,
        _kwargs=dict(filename=filename,
                     stream=stream,
                     upload_path=upload_path,
                     local_basedir=join(current_app.root_path,
                                        current_app.static_folder,
                                        UPLOAD_FOLDER)))
    for i, result in enumerate(data):
        if result["sender"] == "up2local":
            data.pop(i)
            result["src"] = url_for("static",
                                    filename=join(UPLOAD_FOLDER, upload_path,
                                                  filename),
                                    _external=True)
            data.insert(i, result)
    #: 判定后端存储全部失败时,上传失败
    if not data:
        res.update(code=1, msg="No valid backend storage service")
        return res
    if is_all_fail(data):
        res.update(
            code=1,
            msg="All backend storage services failed to save pictures",
        )
        return res
    #: 存储数据
    defaultSrc = data[0]["src"]
    pipe = g.rc.pipeline()
    pipe.sadd(rsp("index", "video", g.userinfo.username), sha)
    pipe.hmset(
        rsp("video", sha),
        dict(
            sha=sha,
            user=g.userinfo.username,
            title=title,
            filename=filename,
            upload_path=upload_path,
            ctime=get_current_timestamp(),
            src=defaultSrc,
            sender=data[0]["sender"],
            senders=json.dumps(data),
        ))
    try:
        pipe.execute()
    except RedisError:
        res.update(code=3, msg="Program data storage service error")
    else:
        res.update(
            code=0,
            sender=data[0]["sender"],
            src=defaultSrc,
        )
    return res
コード例 #13
0
ファイル: test_utils.py プロジェクト: qdjx/picbed
 def test_utils(self):
     self.assertEqual("900150983cd24fb0d6963f7d28e17f72", md5("abc"))
     self.assertEqual(
         "a9993e364706816aba3e25717850c26c9cd0d89d", sha1("abc")
     )
     self.assertEqual("picbed:a:b", rsp("a", "b"))
     self.assertEqual(parse_valid_comma("a,b, c,"), ["a", "b", "c"])
     self.assertEqual(parse_valid_verticaline("a|b| c"), ["a", "b", "c"])
     self.assertTrue(is_true(1))
     self.assertTrue(is_true("on"))
     self.assertTrue(is_true("true"))
     self.assertFalse(is_true(0))
     self.assertIsInstance(get_current_timestamp(), int)
     self.assertTrue(allowed_file("test.PNG"))
     self.assertTrue(allowed_file(".jpeg"))
     self.assertFalse(allowed_file("my.psd"))
     self.assertFalse(allowed_file("ha.gif", ["jpg"]))
     self.assertFalse(allowed_file("ha.jpeg", ["jpg"]))
     self.assertFalse(allowed_file("ha.png", ["jpg"]))
     self.assertTrue(allowed_file("ha.jpg", ["jpg"]))
     v = "6afa9046a9579cad143a384c1b564b9a250d27d6f6a63f9f20bf3a7594c9e2c6"
     self.assertEqual(v, hmac_sha256('key', 'text'))
     self.assertEqual(v, hmac_sha256(b'key', b'text'))
     self.assertEqual(v, hmac_sha256(u'key', u'text'))
     self.assertEqual(
         "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
         sha256("abc")
     )
     #: test format_upload_src
     baseimg = 'img-url'
     basefmt = {'src': baseimg}
     self.assertEqual(format_upload_src(123, baseimg), basefmt)
     self.assertEqual(format_upload_src(None, baseimg), basefmt)
     self.assertEqual(format_upload_src([0], baseimg), basefmt)
     self.assertEqual(format_upload_src('', baseimg), basefmt)
     self.assertEqual(format_upload_src('.', baseimg), basefmt)
     self.assertEqual(format_upload_src('.1', baseimg), basefmt)
     self.assertEqual(format_upload_src('1.', baseimg), basefmt)
     self.assertEqual(format_upload_src(1.1, baseimg), basefmt)
     self.assertEqual(
         format_upload_src('1.1', baseimg), {'1': {'1': baseimg}}
     )
     self.assertEqual(format_upload_src('u', baseimg), basefmt)
     self.assertEqual(format_upload_src('im', baseimg), {'im': baseimg})
     self.assertEqual(format_upload_src('url', baseimg), {'url': baseimg})
     self.assertEqual(format_upload_src('i.am.src', baseimg), basefmt)
     self.assertEqual(
         format_upload_src('src.url', baseimg), {'src': {'url': baseimg}}
     )
     #: test format_apires
     self.assertEqual(
         format_apires({'code': 0}, "success", "bool"), {'success': True}
     )
     self.assertEqual(
         format_apires({'code': 0}, oc="200"), {'code': 200}
     )
     self.assertEqual(
         format_apires({'code': -1}, "status", "bool"), {'status': False}
     )
     self.assertEqual(
         format_apires(dict(code=-1, msg='xxx'), 'errno', '200'),
         {'errno': -1, 'msg': 'xxx'}
     )
     self.assertEqual(
         format_apires(dict(code=-1, msg='xxx'), 'errno', '200', 'errmsg'),
         {'errno': -1, 'errmsg': 'xxx'}
     )
     self.assertEqual(
         format_apires(dict(code=0, msg='xxx'), '', '200', 'errmsg'),
         {'code': 200, 'errmsg': 'xxx'}
     )
     self.assertEqual(len(generate_random()), 6)
     self.assertIn("Mozilla/5.0", gen_ua())