0

For what its worth, I struggled to have the latest version of Brave installed on my Mac as the autoupdate wouldn’t work on my end. So I decided to grab the latest binary from GitHub via a script that would then also automatically install it.

I dont need that script now anymore, but deleting it seems a waste to me as I invested a little time into it. So I am posting it here in the hopes that someone can use it.

This Python script will check your installed version against the latest one available, and if the latest one on GitHub is newer, it will attempt to download and install it automatically:

import os
import re
import subprocess
import requests
from bs4 import BeautifulSoup
from tqdm import tqdm
from packaging import version
from urllib.parse import urljoin


def get_installed_brave_version():
    try:
        # Run the command to get the Brave browser version on macOS
        result = subprocess.run(
            [
                "defaults",
                "read",
                "/Applications/Brave Browser.app/Contents/Info.plist",
                "CFBundleShortVersionString",
            ],
            capture_output=True,
            text=True,
        )
        installed_version_str = result.stdout.strip()

        version_parts = installed_version_str.split('.')
        if len(version_parts) >= 3:
            return version.parse(".".join(version_parts[-3:]))

    except Exception as e:
        print("Error getting installed Brave version:", str(e))
    return None

def get_latest_brave_version():
    try:
        url = "https://api.github.com/repos/brave/brave-browser/releases/latest"
        response = requests.get(url)

        if response.status_code == 200:
            release_data = response.json()
            latest_version_str = release_data.get("tag_name")

            if latest_version_str:
                print("Latest: ", latest_version_str)
                return version.parse(latest_version_str)
            else:
                print("No tag_name found in the GitHub API response.")
        else:
            print(f"Failed to fetch GitHub API. Status code: {response.status_code}")

    except Exception as e:
        print(f"Error while fetching latest version from GitHub API: {str(e)}")

    return None

def get_latest_brave_pkg_url():
    try:
        url = "https://api.github.com/repos/brave/brave-browser/releases/latest"
        response = requests.get(url)

        if response.status_code == 200:
            release_data = response.json()
            assets = release_data.get("assets")

            if assets:
                for asset in assets:
                    name = asset.get("name")
                    if name and name.endswith("Brave-Browser-arm64.pkg"):
                        return asset.get("browser_download_url")

            print("No Brave-Browser-arm64.pkg file found in the GitHub API response.")
        else:
            print(f"Failed to fetch GitHub API. Status code: {response.status_code}")

    except Exception as e:
        print(f"Error while fetching latest version from GitHub API: {str(e)}")

    return None

def download_brave_installer(version_str):
    installer_path = f"Brave-Browser-{version_str}.pkg"
    
    # Check if the file already exists
    if os.path.exists(installer_path):
        print(f"Installer already exists: {installer_path}")
        return installer_path
    
    download_url = get_latest_brave_pkg_url()
    response = requests.get(download_url, stream=True)

    if response.status_code == 200:
        installer_path = f"Brave-Browser-{version_str}.pkg"
        total_size = int(response.headers.get('content-length', 0))

        with open(installer_path, 'wb') as installer_file, tqdm(
                desc="Downloading",
                total=total_size,
                unit='B',
                unit_scale=True,
                unit_divisor=1024,
        ) as progress_bar:
            for data in response.iter_content(chunk_size=1024):
                installer_file.write(data)
                progress_bar.update(len(data))

        print(f"\nInstaller downloaded successfully: {installer_path}")
        return installer_path
    else:
        print("Failed to download the installer.")
        return None

def install_brave(installer_path):
    try:
        # Run the installer command on the downloaded installer file
        subprocess.run(["sudo", "-u", "adm", "installer", "-pkg", installer_path, "-target", "/"])
        # print("Only testing...")
        # print("Brave installed successfully.")
    except Exception as e:
        print("Error installing Brave:", str(e))

def check_brave_version():
    installed_version = get_installed_brave_version()
    
    if installed_version:
        print("Installed Brave version:", installed_version)
        
        latest_version = get_latest_brave_version()
        
        if latest_version:
            if installed_version < latest_version:
                print("Your Brave browser is outdated. Updating to version", latest_version)
                
            installer_path = download_brave_installer(str(latest_version))
                
            if installer_path:
                install_brave(installer_path)
            # else:
            #    print("Failed to download the installer. Update aborted.")
            else:
                print("Your Brave browser is up to date.")
        else:
            print("Unable to retrieve the latest Brave browser version. Please try again later.")
    else:
        print("Unable to determine the installed Brave browser version.")

if __name__ == "__main__":
    check_brave_version()

0

Browse other questions tagged or ask your own question.