获取上串文件获取上串文件

utils

import random
import re
import string
from urllib.parse import urlparse
import requests
import hashlib  
import os
import oss2 

def get_file_md5(file_path):  
    if not os.path.isfile(file_path):  
        return None  
      
    with open(file_path, 'rb') as f:  
        md5_hash = hashlib.md5()  
        while True:  
            data = f.read(4096)  
            if not data:  
                break  
            md5_hash.update(data)  
      
    return md5_hash.hexdigest(), os.path.getsize(file_path), os.path.splitext(file_path)[1]

# 上传文件
def upload(file_path, md5_name, accessId, accessSecret):
  
    # 初始化OSS客户端  
    auth = oss2.Auth(accessId, accessSecret)
    bucket = oss2.Bucket(auth, 'http://oss-cn-beijing.aliyuncs.com', 'down11/20240326')  
    
    # 文件路径和其他参数  
    object_name = md5_name  
    part_size = 1024 * 1024  # 例如,每个分片大小为1MB  
    
    # 初始化分片上传并获取upload_id  
    upload_id = bucket.init_multipart_upload(object_name).upload_id  
    
    # 准备分片列表  
    parts = []  
    
    # 打开文件并上传每个分片  
    with open(file_path, 'rb') as file:  
        while True:  
            data = file.read(part_size)  
            if not data:  
                break  
            part_number = len(parts) + 1  
            result = bucket.upload_part(object_name, data, part_number, upload_id=upload_id)  
            parts.append({  
                'part_number': part_number,  
                'etag': result.etag  
            })  
    
    # 完成分片上传  
    bucket.complete_multipart_upload(object_name, upload_id, parts)

from hashlib import sha256
import hmac
import base64
import uuid
import hashlib

app_key = "203803574"
app_secret = "9znpamsyl2c7cdrr9sas0le9vbc3r6ba"
 #KdBtvfW8dNsqP177v6HMn0qNMzCeGF9NhfA6apMf90w=" "HG195lJSk7rRZ+93yRQNfTu8Rgwphcei09Oer+1UvmI="
# "https://bizapi.csdn.net/download-console-api/v1/user/author-layer" "spCjl6GflfLzFXDBEe8EitdRjEuGxLuY6Xrq5LJusQo="
# "https://bizapi.csdn.net/download-console-api/v1/user/v2/demandSquare/list" "R2CadKDIoJtDIjwk0XAT2WBnScAvXDnWXH89gu0LWkU="
# "https://bizapi.csdn.net/download-console-api/v1/user/v2/author-layer-task/list?taskStatus=1&authorTaskStatus=&pageNo=1&pageSize=2&titleQuery=&taskId=" "0C2hyR9Ar53Hv+Bv8T8gCdcuULJ1U4+ktBkthPEcgoY="
# "https://bizapi.csdn.net/download-console-api/v1/user/sources/obtainViewRecord?type=0" "eu0NZuDl8yupOTTbzxsM+QZOwXvw0MG9ljZf72cp+zo="
# "https://bizapi.csdn.net/download-console-api/v1/user/sources/getGuideInfo" "3kO6mnX1cd7NlpdBmdtKh0JVbZS2eHtErXBq3Ahx1co="
# "https://bizapi.csdn.net/download-console-api/v1/user/sources/category" "HbbjCtxjWxV6E2R/6/dDb3LkX0glenZxHIJBtjkS7mI="
# "https://bizapi.csdn.net/download-console-api/v1/user/getUserUploadMsg" "fF0jO4UPVIYqUs65pdaY6CMJSeVSGzb3PrUue3DRw7Y="
# "https://bizapi.csdn.net/blog-console-api/v1/getSubdomainExpire" "ikRgMDHPgsnBlnEgr992+/odPdfNeid/IIoFhnVZvVA="


#x-ca-nonce
def createUuid():
    text = ""
    char_list = []
    for c in range(97,97+6):
        char_list.append(chr(c))
    for c in range(49,58):
        char_list.append(chr(c))
    for i in "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx":
        if i == "4":
            text += "4"
        elif i == "-":
            text += "-"
        else:
            text += random.choice(char_list)
    return text
def generate_uuid():  
    hex_chars = '0123456789abcdefABCDEF'  # 直接定义十六进制字符集  
    uuid = [None] * 36  # 创建一个长度为36的空列表来存储UUID的各部分  
    for i in range(36):  
        if i == 8 or i == 13 or i == 18 or i == 23:  
            uuid[i] = '-'  # 在指定的位置插入'-'  
        elif i == 14:  
            uuid[i] = '4'  # 在第15位插入'4'  
        else:  
            if i == 19:  # 对于第20位,确保是8, 9, A, 或 B  
                uuid[i] = random.choice('89AB')  
            else:  # 对于其他'x'的位置,可以是任何十六进制字符  
                uuid[i] = random.choice(hex_chars)  
    return ''.join(uuid)  # 将列表中的元素连接成一个字符串  
# js 生成函数
"""
l = function(e) {
                var t = {};
                for (var n in e) {
                    var a = n.toLowerCase();
                    a.startsWith("x-ca-") && ("x-ca-signature" !== a && "x-ca-signature-headers" !== a && "x-ca-key" !== a && "x-ca-nonce" !== a || (t[a] = e[n]))
                }
                return t
            }
_ = function(e) {
                var t = e.method "GET"
                  , n = e.url
                  , a = e.appSecret
                  , o = e.accept "application/json, text/plain, */*"
                  , r = e.date ""
                  , c = e.contentType ""
                  , i = e.params
                  , u = e.headers
                  , f = "";
                i || -1 === n.indexOf("?") ? i || (i = {}) : (i = h(n),
                n = n.split("?")[0]);
                var m = "";
                f += "".concat(t, "\n"),
                f += "".concat(o, "\n"),
                f += "".concat(m, "\n"),
                f += "".concat(c, "\n"),
                f += "".concat(r, "\n");
                var _, b = l(u), g = Array.from(Object.keys(b)).sort(), P = Object(s["a"])(g);
                try {
                    for (P.s(); !(_ = P.n()).done; ) {
                        var v = _.value;
                        f += v + ":" + b[v] + "\n"
                    }
                } catch (O) {
                    P.e(O)
                } finally {
                    P.f()
                }
                var A = /^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.csdn\.net)/
                  , w = n.replace(A, "");
                f += p(w, i);
                var U = d.a.HmacSHA256(f, a)
                  , k = U.toString(d.a.enc.Base64);
                return k
            }
"""

from urllib.parse import parse_qs  
def p(e, t):  
    # 过滤掉t中值为空字符串或None的键  
    filtered_t = {k: v for k, v in t.items() if v is not None and v != ""}  
      
    # 将过滤后的字典项转换成查询字符串的格式  
    query_string = "&".join([f"{k}={v}" for k, v in filtered_t.items()])  
      
    # 如果存在查询字符串,则将其附加到e后面,前面加上问号  
    if query_string:  
        return f"{e}?{query_string}"  
    else:  
        return e 
    
def h(url):  
    # 解析URL,提取查询参数  
    parsed_url = urlparse(url)  
    query_params = parse_qs(parsed_url.query)  
      
    # 将查询参数转换为字典,其中键是参数名,值是参数值的列表  
    # 如果参数只出现一次,则列表只有一个元素  
    params_dict = {k: v[0] if len(v) == 1 else v for k, v in query_params.items()}  
      
    # 返回参数字典  
    return params_dict  
def function_l(e):  
    t = {}  
    for n in e:  
        a = n.lower()  
        if a.startswith("x-ca-") and a in ["x-ca-signature", "x-ca-signature-headers", "x-ca-key", "x-ca-nonce"]:  
            t[a] = e[n]  
    return t  
  
def function_underscore(e):  
    # 假设 h, s["a"], p, d.a.HmacSHA256, d.a.enc.Base64 已经在其他地方定义或导入  
    # 初始化变量  
    t = e.get("method", "GET")  
    n = e["url"]  
    a = e["appSecret"]  
    o = e.get("accept", "application/json, text/plain, */*")  
    r = e.get("date", "")  
    c = e.get("contentType", "")  
    i = e.get("params", {})  
    u = e["headers"]  
    f = ""  
      
    # 处理 params 和 url  
    if not i and n.find("?") == -1:  
        pass  # 假设没有 params 或 url 中没有 '?' 时不进行操作  
    else:  
        if "?" in n:  
            i = h(n)  # 假设 h 是处理 url 中的查询参数的函数  
            n = n.split("?")[0]  
    # 构建待签名的字符串 f  
    f += "{}\n".format(t)  
    f += "{}\n".format(o)  
    f += "\n"  # 假设 m 为空字符串  
    f += "{}\n".format(c)  
    f += "{}\n".format(r)  
      
    # 过滤和排序 headers  
    b = function_l(u)  
    g = sorted(b.keys())  
    P = iter(g)  # 假设 s["a"] 是一个返回迭代器的函数  
      
    try:  
        while True:  
            try:  
                v = next(P)  
            except StopIteration:  
                break  
            f += "{}:{}\n".format(v, b[v])  
    except Exception as O:  
        # 处理异常,假设 P.e 是处理异常的方法  
        pass  
    finally:  
        # 假设 P.f 是清理资源的方法  
        pass  
      
    # 处理 url  
    A = r"^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.csdn\.net)"  
    w = re.sub(A, "", n)  # 假设已经导入了 re 模块  
      
    # 拼接 query string  
    f += p(w, i)  # 假设 p 是拼接 query string 的函数  
      
    # 生成签名  
    U = hmac.new(a.encode(), f.encode(), hashlib.sha256).digest()  
    k = base64.b64encode(U).decode()  # 假设 d.a.HmacSHA256 和 d.a.enc.Base64 分别对应于 hmac.new 和 base64.b64encode  
      
    return k  
  
# 示例使用  
import http.cookiejar as cookielib
# "https://bizapi.csdn.net/download-console-api/v1/user/sources/getAuthorized?fileMd5=eaa25e77d592edc2123ee19a7356e04b&fileSize=572766609"
def make_headers(cookies, url):
    nonce = createUuid()
    signature = function_underscore({
        "url": url,
        "appSecret": app_secret,
        "headers": {
            "X-Ca-Key": app_key,
            "X-Ca-Nonce": nonce
        }
    })
    
    
    print(f"signature is : {signature}")
    return {
        "Accept": "application/json, text/plain, */*",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Cache-Control": "no-cache",
        "Content-Type": "application/json",
        "Origin": "https://upload.csdn.net",
        "Pragma": "no-cache",
        "Referer": "https://upload.csdn.net/creation/uploadResources",
        "Sec-Ch-Ua-Mobile": "?0",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Ch-Ua-Platform": '"macOS"',
        "Uri-Name": "feige",
        "Cookie": cookies,
        "Sec-Fetch-Site": "same-site",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36",
        "X-Ca-Key": app_key,
        "X-Ca-Nonce": nonce,
        "X-Ca-Signature": signature,
        "X-Ca-Signature-Headers": "x-ca-key,x-ca-nonce",
    }

if __name__ == "__main__":
    nonce = "e6a20b79-1a23-44e1-b49c-5da538633be8" #createUuid() #"42ff7465-ec7c-4f46-bd3d-99d44c21cb83" #generate_uuid()
    authorized_url = "https://bizapi.csdn.net/download-console-api/v1/user/sources/getAuthorized?fileMd5=eaa25e77d592edc2123ee19a7356e04b&fileSize=572766609"
    signature = function_underscore({
        "url": authorized_url,
        "appSecret": app_secret,
        "headers": {
            "X-Ca-Key": "203803574",
            "X-Ca-Nonce": nonce
        }
    })
    print(nonce)
    print(signature)

main

import requests
import hashlib  
import os
import oss2 
from utils.util import get_file_md5, make_headers, upload

class API_Login():
    def __init__(self, user, pwd) -> None:
        self.Session = self.login(user, pwd)
    def login(self, user_name, pwd):
        url = "https://passport.csdn.net/v1/register/pc/login/doLogin"  
        # 创建一个session对象  
        session = requests.Session()  
    
        # 设置请求头  
        self.headers = {  
            "Content-Type": "application/json;charset=UTF-8",  
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"  
        }  
    
        # 准备POST请求的数据  
        login_data = {  
            "loginType": "1",  
            "pwdOrVerifyCode": pwd,  
            "uaToken": "",  
            "userIdentification": user_name,  
            "webUmidToken": ""  
        }  
    
        # 使用session对象发送POST请求进行登录  
        response = session.post(url=url, json=login_data, headers=self.headers)  
    
        # 检查登录是否成功  
        if response.status_code == 200:  
            print("登录成功")  
            # 返回session对象,以便在其他函数中使用  
            return session  
        else:  
            print("登录失败", response.text)  
            return None 
    def upload_source(self, title, desc, tag, file_path):
        md5, size , ext = get_file_md5(file_path)
        # 验证身份 get
        authorized_url = f"https://bizapi.csdn.net/download-console-api/v1/user/sources/getAuthorized?fileMd5={md5}&fileSize={size}" 
        # authorized_url = "https://bizapi.csdn.net/download-console-api/v1/user/sources/getAuthorized?fileMd5=eaa25e77d592edc2123ee19a7356e04b&fileSize=572766609"

        # 上传  put
        file_name = f"{md5}{ext}"
        upload_url = f"https://csdn-dl-data.oss-cn-beijing.aliyuncs.com/down11/20240326/file_name?partNumber=1&uploadId=D40B7FC3E9BD4FF9A7E5CDA9BF3ED0F7"
        # 保存表单
        save_resource = "https://upload.csdn.net/v1/user/sources/saveSource"
        json = {
            "title": "protobuf3.11.2文件",
            "description": "protobuf3.11.2文件",
            "tag": "protobuf",
            "authorLayerTaskIds": "",
            "pubType": 0,
            "categoryId": 12009,
            "fileAddr": f"/20240326/{md5}.zip",
            "fileSize": size,
            "fileMd5": f"{md5}",
            "originName": "protobuf-3.11.2.zip",
            "demandSquareId": None,
            "url": "https://upload.csdn.net/creation/uploadResources?spm=1011.2415.3001.6218",
            "agree_change_score": False,
            "isVipSource": False,
            "sourceScore": 0,
            "autoParamMap": {}
        }
        cookies = {cookie.name: cookie.value for cookie in self.Session.cookies}  
        cookies = '; '.join(f'{name}={value}' for name, value in cookies.items())
        # 将 cookie 格式化为 headers 格式  
        
        headers = make_headers(cookies, authorized_url)
        # self.Session.headers = headers
        res = self.Session.get(url=authorized_url, headers= headers, verify=False)
        if res.status_code == 200:  
            print("请求成功。")  
            print("响应头部信息:")  
            print(res.headers)  # 打印响应的头部信息  
            print("响应正文内容:")  
            print(res.text)  # 打印响应的正文内容  
        else:  
            print(f"请求失败,状态码:{res.status_code}")  
            print("响应头部信息:")  
            print(res.headers)  # 尽管请求失败,但通常仍然可以访问响应头部  
            print(res.headers.get('X-Ca-Error-Message'))  # 尽管请求失败,但通常仍然可以访问响应头部  
            print(res.headers.get('X-Ca-Error-Code'))  # 尽管请求失败,但通常仍然可以访问响应头部  
            # 注意:如果状态码不是 2xx,res.text 可能不包含有用的信息或为空  
            print("响应正文内容:")  
            print(res.text)  # 打印可能的错误信息或响应内容
        
        

if __name__ == "__main__":
    user = "15005935876"
    pwd = "cdmstrong123"
    S = API_Login(user, pwd)
    # S.login(user,pwd)
    S.upload_source("d", "d", "d", "write.py")
    # md5, _, ext = get_file_md5("write.py")
    # print(ext)






  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东哥爱编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值