Skip to content

Feature/cookie login 修正程序输出,简化手动导入Cookies流程为直接粘贴#8

Merged
YewFence merged 8 commits intomainfrom
feature/cookie-login
Dec 27, 2025
Merged

Feature/cookie login 修正程序输出,简化手动导入Cookies流程为直接粘贴#8
YewFence merged 8 commits intomainfrom
feature/cookie-login

Conversation

@YewFence
Copy link
Copy Markdown
Owner

@YewFence YewFence commented Dec 27, 2025

Summary by CodeRabbit

  • Documentation

    • Updated authentication guide and cookie instructions to use clipboard-based workflow; removed file-based cookie steps.
  • New Features

    • Welcome message shown at startup.
    • Built-in troubleshooting/suggestions output.
  • Improvements

    • Streamlined interactive login prompts and status messages; SSO label updated.
    • Added test-login mode and SSO homepage configuration.
    • Simplified cookie import flow to paste/export clipboard content.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Dec 27, 2025

Caution

Review failed

The pull request is closed.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

Authentication shifts from file-based cookie handling to clipboard-driven and interactive SSO login; config adds TEST_LOGIN_MODE and SSO_INDEX_URL; main app flow and UX were restructured; cookie helper now reads pasted JSON from stdin; docs updated to remove file-based cookie instructions.

Changes

Cohort / File(s) Summary
Documentation
README.md, docs/how_to_get_cookie.md
Removed file-based cookie instructions, renamed auth headings, and replaced file-export steps with clipboard export / paste workflow (Cookie-Editor guidance).
Authentication logic
automation/auth.py
Modified interactive_login_and_save_cookies signature to (login_url, base_url, sso_index_url, cookie_file); navigate to SSO index and click site link labeled "砺儒云课堂"; reload saved cookies after refresh; simplified messages and retry handling.
Configuration
config.py
Added TEST_LOGIN_MODE: bool and SSO_INDEX_URL: str constants (new config entries).
Cookie input handler
cookie_fix.py
Changed from file input to interactive CLI paste: signature removed default filename (cookie_fix()), reads cookie JSON from stdin until empty line, updated validation/messages.
Main application
main.py
Added print_welcome() and suggestions() functions; restructured startup and login flow (use TEST_LOGIN_MODE, auto cookie login if file exists, interactive options, and cookie_fix integration); adjusted shutdown/browser close logic and concise error messages.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant User as User (CLI)
  participant Main as main.py
  participant Auth as automation/auth.py
  participant Browser as Browser/Playwright
  participant SSO as SSO Site

  Note over User,Main: Startup
  User->>Main: run program
  Main->>Main: print_welcome()
  Main->>Auth: check cookie file exists?
  alt cookie file exists and valid
    Auth->>Browser: load cookies
    Browser-->>Auth: cookies loaded
    Auth-->>Main: authenticated
  else no valid cookies
    Main->>User: prompt for login method (interactive / paste cookies)
    alt interactive selected
      Main->>Browser: launch browser (headful)
      Browser-->>User: show SSO login UI
      User->>SSO: completes SSO login manually
      SSO-->>Browser: authenticated session
      Browser->>Auth: page shows "砺儒云课堂" link
      Auth->>Browser: click link, navigate to SSO index
      Browser->>Auth: extract cookies
      Auth->>Auth: save cookies to file
      Auth-->>Main: authenticated
    else paste cookies selected
      User->>Main: paste clipboard JSON
      Main->>Auth: parse & import cookies
      Auth->>Browser: set cookies
      Auth-->>Main: authenticated
    end
  end
  Main->>Browser: proceed with scraping actions
  Main->>Browser: close if connected
  Note right of User: End
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Poem

🐰 I hopped from files to clipboard bright,
SSO stars guiding me through the night,
Cookies now pasted, not tucked away,
Welcome screens lead the login play,
A tiny hop for smoother bytes! 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 77.78% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main changes: fixing program output and simplifying the manual cookie import process to direct pasting.

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d195854 and 87dc6ee.

📒 Files selected for processing (4)
  • automation/auth.py
  • config.py
  • cookie_fix.py
  • main.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @YewFence, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

此拉取请求旨在显著提升SCNU砺儒云视频自动观看工具的用户登录体验。核心改进在于简化了Cookie的导入过程,允许用户直接粘贴浏览器导出的JSON格式Cookie,从而省去了文件操作的步骤。此外,登录流程变得更加智能和用户友好,程序会优先尝试现有凭证,并在必要时提供清晰的引导。此次更新还包括了新的测试配置选项、更简洁的控制台输出以及更健壮的错误处理机制,以提高整体的可用性和可维护性。

Highlights

  • 简化Cookie导入流程: 用户现在可以直接将从浏览器导出的Cookie JSON内容粘贴到程序中,无需再手动创建和保存browser_cookies.json文件。
  • 优化登录体验: 程序启动时会首先尝试使用现有的Cookie文件进行登录。如果Cookie失效或不存在,将引导用户选择交互式登录或手动粘贴Cookie,并提供更清晰的提示和错误信息。
  • 新增测试模式: 在config.py中引入了TEST_MODETEST_LOGIN_MODE配置项,方便开发者进行视频处理和登录功能的测试。
  • 文档更新: 更新了README.mddocs/how_to_get_cookie.md,以反映新的Cookie导入方式,并删除了过时或冗余的说明。
  • 代码健壮性提升: 改进了automation/auth.py中的Cookie刷新逻辑,确保刷新后立即加载新Cookie;同时,main.py中的错误处理和浏览器关闭逻辑也得到了增强。
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

本次 PR 极大地改善了用户体验,特别是将手动导入 Cookies 的流程简化为直接粘贴,这是一个非常棒的改进。代码结构也得到了优化,例如增加了欢迎界面、将重复的建议提取到 suggestions 函数中,以及增强了程序退出的健壮性。整体而言,代码质量很高。

我发现了一些可以进一步改进的小地方,主要集中在代码整洁性和可维护性方面,具体请看我的评论。

Comment on lines +132 to +136
async def interactive_login_and_save_cookies(self,
login_url: str,
base_url: str,
cookie_file: str = "cookies.json",
sso_index_url = "https://sso.scnu.edu.cn/AccountService/user/index.html") -> bool:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

硬编码的 sso_index_url 默认值降低了代码的可维护性。建议将此 URL 移至 config.py 文件中,与其他 URL 配置放在一起。这样可以更方便地进行管理和修改,也符合将配置与逻辑分离的最佳实践。

建议修改如下:

config.py

# ...
LOGIN_URL = "https://sso.scnu.edu.cn/AccountService/user/login.html"
SSO_INDEX_URL = "https://sso.scnu.edu.cn/AccountService/user/index.html" # 新增
# ...

automation/auth.py

async def interactive_login_and_save_cookies(self, 
                                             login_url: str,
                                             base_url: str,
                                             cookie_file: str = "cookies.json",
                                             sso_index_url: str) -> bool: # 移除默认值
# ...

main.py

# ...
login_success = await auth_manager.interactive_login_and_save_cookies(
    config.LOGIN_URL,
    config.BASE_URL,
    config.COOKIE_FILE,
    config.SSO_INDEX_URL # 新增
)
# ...

loop = asyncio.get_running_loop()
retry = await loop.run_in_executor(None, input, "是否重试?(y/n): ")
if retry.lower() not in ('y', 'yes'):
if retry.lower() not in ('y', 'yes', 'Y', 'Yes', 'YES'):
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

这里的条件判断存在冗余。由于已经使用了 .lower() 方法将输入字符串转换为小写,因此没有必要再检查大写形式('Y', 'Yes', 'YES')。这会使代码显得有些混乱。建议简化该条件判断。
另外,为了增强健壮性,最好在使用 .lower() 之前先用 .strip() 去除用户可能输入的额外空格。

Suggested change
if retry.lower() not in ('y', 'yes', 'Y', 'Yes', 'YES'):
if retry.strip().lower() not in ('y', 'yes'):

cookie_fix.py Outdated
@@ -1,15 +1,18 @@
# convert_cookies.py
import json
import sys
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

这里导入了 sys 模块,但在文件的其余部分并未使用。建议移除这行未使用的导入,以保持代码的整洁性。

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (5)
cookie_fix.py (2)

3-3: Remove unused sys import.

The sys module is imported but not used. The input() function is a Python builtin, not from sys.

🔎 Proposed fix
 # convert_cookies.py
 import json
-import sys

12-15: Consider more specific error handling for JSON parsing.

The generic Exception handler at line 52 catches JSON parsing errors, but providing a more specific error message for malformed JSON would improve user experience.

🔎 Proposed fix
         if content == '':
             print("✗ 输入为空,请检查输入内容")
             return False
-        browser_cookies = json.loads(content)
+        try:
+            browser_cookies = json.loads(content)
+        except json.JSONDecodeError as e:
+            print(f"✗ JSON 格式错误: {e}")
+            return False
automation/auth.py (2)

132-136: Add type annotation for sso_index_url parameter.

For consistency with other parameters, add the str type annotation.

🔎 Proposed fix
     async def interactive_login_and_save_cookies(self, 
                                                  login_url: str,
                                                  base_url: str,
                                                  cookie_file: str = "cookies.json",
-                                                 sso_index_url = "https://sso.scnu.edu.cn/AccountService/user/index.html") -> bool:
+                                                 sso_index_url: str = "https://sso.scnu.edu.cn/AccountService/user/index.html") -> bool:

180-181: Simplify retry condition check.

After calling .lower(), checking uppercase variants is redundant.

🔎 Proposed fix
-                if retry.lower() not in ('y', 'yes', 'Y', 'Yes', 'YES'):
+                if retry.lower() not in ('y', 'yes'):
                     return False
main.py (1)

76-76: Redundant assignment.

login_success is already False at this point (set on line 58 and not modified if we reach line 69).

🔎 Proposed fix
         print("登录凭证已失效或不存在")
             # 选择登录方式
             print("\n🔐 请选择获取登录凭证(Cookies)的方式:")
             print("   1. 交互式登录(推荐)- 自动打开登录页面,您手动登录后程序自动获取Cookies")
             print("   2. 使用您手动获取的 Cookies 登录 - 在命令行中直接粘贴浏览器导出的 Cookies JSON")
             
-            login_success = False
             while True:
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3746a97 and d195854.

📒 Files selected for processing (6)
  • README.md
  • automation/auth.py
  • config.py
  • cookie_fix.py
  • docs/how_to_get_cookie.md
  • main.py
🧰 Additional context used
🪛 Ruff (0.14.10)
main.py

59-59: Comment contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF003)


62-62: Comment contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF003)


64-64: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


72-72: String contains ambiguous (FULLWIDTH LEFT PARENTHESIS). Did you mean ( (LEFT PARENTHESIS)?

(RUF001)


72-72: String contains ambiguous (FULLWIDTH RIGHT PARENTHESIS). Did you mean ) (RIGHT PARENTHESIS)?

(RUF001)


73-73: String contains ambiguous (FULLWIDTH LEFT PARENTHESIS). Did you mean ( (LEFT PARENTHESIS)?

(RUF001)


73-73: String contains ambiguous (FULLWIDTH RIGHT PARENTHESIS). Did you mean ) (RIGHT PARENTHESIS)?

(RUF001)


73-73: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


80-80: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


100-100: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


100-100: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


103-103: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


133-133: Do not catch blind exception: Exception

(BLE001)


146-148: try-except-pass detected, consider logging the exception

(S110)


146-146: Do not catch blind exception: Exception

(BLE001)


147-147: Comment contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF003)


156-156: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)


156-156: String contains ambiguous (FULLWIDTH COLON). Did you mean : (COLON)?

(RUF001)

automation/auth.py

169-169: Do not catch blind exception: Exception

(BLE001)


174-174: String contains ambiguous (FULLWIDTH EXCLAMATION MARK). Did you mean ! (EXCLAMATION MARK)?

(RUF001)


177-177: String contains ambiguous (FULLWIDTH EXCLAMATION MARK). Did you mean ! (EXCLAMATION MARK)?

(RUF001)


179-179: String contains ambiguous (FULLWIDTH QUESTION MARK). Did you mean ? (QUESTION MARK)?

(RUF001)

config.py

21-21: Comment contains ambiguous (FULLWIDTH LEFT PARENTHESIS). Did you mean ( (LEFT PARENTHESIS)?

(RUF003)


21-21: Comment contains ambiguous (FULLWIDTH RIGHT PARENTHESIS). Did you mean ) (RIGHT PARENTHESIS)?

(RUF003)


22-22: Comment contains ambiguous (FULLWIDTH LEFT PARENTHESIS). Did you mean ( (LEFT PARENTHESIS)?

(RUF003)


22-22: Comment contains ambiguous (FULLWIDTH RIGHT PARENTHESIS). Did you mean ) (RIGHT PARENTHESIS)?

(RUF003)

cookie_fix.py

13-13: String contains ambiguous (FULLWIDTH COMMA). Did you mean , (COMMA)?

(RUF001)

🔇 Additional comments (7)
README.md (1)

113-124: Documentation updates look good.

The instructions clearly reflect the new clipboard-based cookie workflow and are consistent with the code changes in main.py and cookie_fix.py.

automation/auth.py (1)

150-170: SSO navigation flow looks reasonable.

The flow navigates to SSO, finds the target link, handles popup, and waits for load. The broad exception catch at line 169 is acceptable here to prevent login flow from failing on transient UI issues.

main.py (4)

14-32: Welcome banner looks good.

The ASCII art banner provides a clean user experience with helpful tips about usage and interruption.


59-68: Auto-login flow is well-structured.

Good use of TEST_LOGIN_MODE flag to conditionally skip cookie-based login for testing purposes. The path existence check prevents unnecessary login attempts.


139-148: Browser shutdown handling is appropriate.

The guarded shutdown correctly checks is_connected() before attempting close, and the silent exception handling is reasonable for cleanup code where the browser may already be closed.


150-156: suggestions() function provides helpful troubleshooting guidance.

Consider adding a return type annotation for consistency.

🔎 Optional: Add return type annotation
-def suggestions():
+def suggestions() -> None:
     print("\n💡 故障排查建议:")
docs/how_to_get_cookie.md (1)

16-16: Documentation correctly updated for clipboard workflow.

The simplified instructions now accurately reflect that cookies are copied to clipboard after export, aligning with the new paste-based input in the program.

@YewFence YewFence merged commit c62bbc3 into main Dec 27, 2025
2 of 3 checks passed
@YewFence YewFence deleted the feature/cookie-login branch March 15, 2026 12:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant