MCPcopy Index your code
hub / github.com/ChinaGodMan/UserScripts / GreasyFork

Class GreasyFork

utils/script-import-sync.py:84–248  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

82
83# GreasyFork API类
84class GreasyFork:
85 def __init__(self):
86 self.session = requests.Session()
87 self.csrf_token = None
88
89 def fetch_csrf_token(self):
90 """
91 提取 CSRF Token。
92 """
93 url = 'https://greasyfork.org'
94 response = self.session.get(url)
95 if response.status_code == 200:
96 soup = BeautifulSoup(response.text, 'html.parser')
97 csrf_token_meta = soup.find('meta', {'name': 'csrf-token'})
98 if csrf_token_meta:
99 self.csrf_token = csrf_token_meta.get('content')
100 return self.csrf_token
101 else:
102 raise ValueError("CSRF Token meta tag not found")
103 else:
104 raise Exception(
105 f"Failed to fetch the page. Status Code: {response.status_code}")
106
107 def login(self, email, password, totp):
108 if self.csrf_token is None:
109 self.fetch_csrf_token()
110
111 login_url = 'https://greasyfork.org/zh-CN/users/sign_in'
112 headers = {
113 'Content-Type': 'application/x-www-form-urlencoded'
114 }
115 data = {
116 'authenticity_token': self.csrf_token,
117 'user[email]': email,
118 'user[password]': password,
119 'user[remember_me]': '1',
120 'user[otp_attempt]': totp,
121 'commit': '登录'
122 }
123
124 response = self.session.post(login_url, headers=headers, data=data)
125 if response.ok:
126 soup = BeautifulSoup(response.text, 'html.parser')
127 # 登录提示
128 tip = soup.select_one("body > div.width-constraint > p")
129 # 用户信息
130 user_info = soup.select_one("#nav-user-info > span.user-profile-link > a")
131 match = re.search(r'/users/(\d+)-', user_info.get('href', ''))
132 user_id = match.group(1) if match else None
133 user_name = user_info.get_text()
134 print(f"\033[32m{user_name}({user_id}):{tip.get_text()}\033[0m")
135 self.fetch_csrf_token() # 登录成功后重新获取csrf_token.所有的请求都需要csrf_token,而且获取一次就行了,一个csrf_token可以多次使用
136 else:
137 raise Exception(f"Login failed. Status Code: {response.status_code}\n{response.text}")
138
139 def get(self, url):
140 response = self.session.get(url)
141 return response

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected