Skip to content

Commit

Permalink
Added support for local Python environment and improved user SID hand…
Browse files Browse the repository at this point in the history
…ling.

- Added support for running the script in a local Python environment without virtual environments.
- Enhanced user SID retrieval by adding a fallback for manual input if automatic retrieval fails.
- Updated instructions on how to set up Task Scheduler for automatic execution.
- Changed file path handling from `os.getcwd()` to `.parent.resolve()` for better script directory reference.
  • Loading branch information
JunYanOOO committed Aug 9, 2024
1 parent 45f4495 commit aa92ea9
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 58 deletions.
74 changes: 38 additions & 36 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,61 +5,63 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.0.0] - 2024-08-08
## [0.2.0] - 2024-08-09

### Added

- Initial release of the Python script to generate a Task Scheduler XML file.
- Script allows users to choose between Miniconda and Anaconda.
- Script prompts users to input the name of the environment they are using.
- Output path is set to the current working directory.
- A new batch file (`MS_reward.bat`) that automatically sets the current directory and executes the Python script (`main.py -v`).
- Initial release of the Python script:
- Generates a Task Scheduler XML file
- Allows users to choose between Miniconda, Anaconda, and Local Python
- Prompts users to input the name of their environment (if using Miniconda or Anaconda)
- Uses the script directory as the output path
- Default trigger time is set to 6:00 AM on a specified day, with instructions to modify settings after importing to Task Scheduler
- Includes a batch file (`MS_reward.bat`) for automatic execution of the Python script

## [0.1.0] - 2024-07-27

### Added

- New [config.yaml](config.yaml) options
- `retries`
- `base_delay_in_seconds`: how many seconds to delay
- `max`: the max amount of retries to attempt
- `strategy`: method to use when retrying, can be either:
- `CONSTANT`: the default; a constant `base_delay_in_seconds` between attempts
- `EXPONENTIAL`: an exponentially increasing `base_delay_in_seconds` between attempts
- `apprise.summary`: configures how results are summarized via Apprise, can be either:
- `ALWAYS`: the default, as it was before, how many points were gained and goal percentage if set
- `ON_ERROR`: only sends email if for some reason there's remaining searches
- `NEVER`: never send summary
- Apprise notification if activity isn't completed/completable
- Support for more activities
- New arguments (see [readme](README.md#launch-arguments) for details)
- Some useful JetBrains config
- More logging
- Config to make `requests` more reliable
- More checks for bug report
- Me, cal4, as a sponsoree
- New [config.yaml](config.yaml) options
- `retries`
- `base_delay_in_seconds`: how many seconds to delay
- `max`: the max amount of retries to attempt
- `strategy`: method to use when retrying, can be either:
- `CONSTANT`: the default; a constant `base_delay_in_seconds` between attempts
- `EXPONENTIAL`: an exponentially increasing `base_delay_in_seconds` between attempts
- `apprise.summary`: configures how results are summarized via Apprise, can be either:
- `ALWAYS`: the default, as it was before, how many points were gained and goal percentage if set
- `ON_ERROR`: only sends email if for some reason there's remaining searches
- `NEVER`: never send summary
- Apprise notification if activity isn't completed/completable
- Support for more activities
- New arguments (see [readme](README.md#launch-arguments) for details)
- Some useful JetBrains config
- More logging
- Config to make `requests` more reliable
- More checks for bug report
- Me, cal4, as a sponsoree

### Changed

- More reliable searches and closer to human behavior
- When logger is set to debug, doesn't include library code now
- Line endings to LF
- More reliable searches and closer to human behavior
- When logger is set to debug, doesn't include library code now
- Line endings to LF

### Removed

- Calls to close all Chrome processes
- Calls to close all Chrome processes

### Fixed

- [Error when executing script from .bat file](https://github.com/klept0/MS-Rewards-Farmer/issues/113)
- [\[BUG\] AttributeError: 'Browser' object has no attribute 'giveMeProxy'](https://github.com/klept0/MS-Rewards-Farmer/issues/115)
- [\[BUG\] driver.quit causing previous issue of hanging process with heavy load on cpu](https://github.com/klept0/MS-Rewards-Farmer/issues/136)
- Login
- Errors when [config.yaml](config.yaml) doesn't exist
- General reliability and maintainability fixes
- [Error when executing script from .bat file](https://github.com/klept0/MS-Rewards-Farmer/issues/113)
- [\[BUG\] AttributeError: 'Browser' object has no attribute 'giveMeProxy'](https://github.com/klept0/MS-Rewards-Farmer/issues/115)
- [\[BUG\] driver.quit causing previous issue of hanging process with heavy load on cpu](https://github.com/klept0/MS-Rewards-Farmer/issues/136)
- Login
- Errors when [config.yaml](config.yaml) doesn't exist
- General reliability and maintainability fixes

## [0.0.0] - 2023-03-05

### Added

- Farmer and lots of other things, but gotta start a changelog somewhere!
- Farmer and lots of other things, but gotta start a changelog somewhere!
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,13 @@

`python main.py`

6. (Windows Only) You can set up automatic execution by generating a Task Scheduler XML file.

If you are a Windows user, run the `generate_task_xml.py` script to create a `.xml` file. After generating the file, import it into Task Scheduler to schedule automatic execution of the script. This will allow the script to run at the specified time without manual intervention.

To import the XML file into Task Scheduler, see [this guide](https://superuser.com/a/485565/709704).


## Launch arguments

- `-v/--visible` to disable headless
Expand Down Expand Up @@ -113,4 +120,4 @@ Fork this repo and:
- [x] Complete "Read To Earn" (30 pts)
- [x] Setup flags for mobile/desktop search only
- [ ] Setup flags to load config / save data in working directory
- [ ] Provide Windows Task Scheduler config
- [x] Provide Windows Task Scheduler config
65 changes: 44 additions & 21 deletions generate_task_xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,48 +2,66 @@
import os
import subprocess
from datetime import datetime
from pathlib import Path

# 取得當前使用者的名稱
# Get the directory of the script being run
script_dir = Path(__file__).parent.resolve()

# Get the current user's name
current_user = getpass.getuser()


# 取得當前使用者的SID
# Get the current user's SID
def get_user_sid(username):
try:
output = subprocess.check_output(
f'wmic useraccount where name="{username}" get sid', shell=True
)
sid = output.decode().split("\n")[1].strip()
command = [
"powershell",
"-Command",
f"(Get-WmiObject -Class Win32_UserAccount -Filter \"Name='{username}'\").SID",
]
output = subprocess.check_output(command, universal_newlines=True)
sid = output.strip()
return sid
except Exception as e:
print(f"Error getting SID for user {username}: {e}")
return None


current_user_sid = get_user_sid(current_user)
sid = get_user_sid(current_user)

if sid is None:
print("Unable to retrieve SID automatically.")
print(
"Please manually check your SID by running the following command in Command Prompt:"
)
print("whoami /user")
sid = input("Enter your SID manually: ")

computer_name = os.environ["COMPUTERNAME"]

# Let the user choose between Miniconda and Anaconda
print("Please choose your Python distribution:")
print("1. Miniconda")
print("1. Local (Windows system Python without virtual environment)")
print("2. Anaconda")
choice = input("Enter your choice (1 or 2): ")
print("3. Miniconda")
choice = input("Enter your choice (1, 2, or 3): ")

if choice == "1":
base_path = f"C:\\Users\\{current_user}\\miniconda3"
command = f"{script_dir}\\MS_reward.bat"
elif choice == "2":
base_path = f"C:\\Users\\{current_user}\\anaconda3"
command = f"{base_path}\\Scripts\\activate.bat {base_path} && conda activate {{env_name}} && {script_dir}\\MS_reward.bat"
elif choice == "3":
base_path = f"C:\\Users\\{current_user}\\miniconda3"
command = f"{base_path}\\Scripts\\activate.bat {base_path} && conda activate {{env_name}} && {script_dir}\\MS_reward.bat"
else:
print("Invalid choice, please rerun the script and choose 1 or 2.")
print("Invalid choice, please rerun the script and choose 1, 2, or 3.")
exit(1)

# Let the user enter the name of the environment they are using
env_name = input("Please enter the name of the environment you are using: ")

# Use the current working directory as the output path
output_path = os.path.join(os.getcwd(), "MS_reward.xml")
print(f"The XML file will be saved to: {output_path}")

if choice in ["2", "3"]:
env_name = input("Please enter the name of the environment you are using: ")
command = command.format(env_name=env_name)

xml_content = f"""<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
Expand All @@ -54,7 +72,7 @@ def get_user_sid(username):
</RegistrationInfo>
<Triggers>
<CalendarTrigger>
<StartBoundary>2024-07-03T06:00:00</StartBoundary>
<StartBoundary>2024-08-09T06:00:00</StartBoundary>
<Enabled>true</Enabled>
<ScheduleByDay>
<DaysInterval>1</DaysInterval>
Expand All @@ -63,7 +81,7 @@ def get_user_sid(username):
</Triggers>
<Principals>
<Principal id="Author">
<UserId>{current_user_sid}</UserId>
<UserId>{sid}</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>LeastPrivilege</RunLevel>
</Principal>
Expand All @@ -90,14 +108,19 @@ def get_user_sid(username):
<Actions Context="Author">
<Exec>
<Command>%windir%\\System32\\cmd.exe</Command>
<Arguments>/K "{base_path}\\Scripts\\activate.bat {base_path} &amp;&amp; conda activate {env_name} &amp;&amp; {os.getcwd()}\\MS_reward.bat"</Arguments>
<WorkingDirectory>{os.getcwd()}</WorkingDirectory>
<Arguments>/K "{command}"</Arguments>
<WorkingDirectory>{script_dir}</WorkingDirectory>
</Exec>
</Actions>
</Task>"""

# Use the script directory as the output path
output_path = script_dir / "MS_reward.xml"

with open(output_path, "w", encoding="utf-16") as file:
file.write(xml_content)

print(f"XML file has been generated and saved to: {output_path}")
print("To import, see https://superuser.com/a/485565/709704")
print("The trigger time is set to 6:00 AM on the specified day.")
print("You can modify the settings after importing the task into the Task Scheduler.")

0 comments on commit aa92ea9

Please sign in to comment.