Esempio n. 1
0
async def terminal(event):
    full_cmd_str = event.pattern_match.group(1)
    cmd_output = None
    try:
        if isWindows():
            full_cmd_str = f"powershell {full_cmd_str}"
            cmds = shlex.split(full_cmd_str)
            proc = Popen(cmds, stdout=PIPE, stderr=PIPE)
        else:  # POSIX systems
            executor = None
            if isinstance(USE_BIN_BASH, bool) and USE_BIN_BASH:
                executor = "/bin/bash"
            proc = Popen(full_cmd_str, shell=True, executable=executor,
                         stdout=PIPE, stderr=PIPE)
        cmd_output, cmd_error = proc.communicate()
        if proc.returncode or cmd_error:
            cmd_output = cmd_error
        cmd_output = ("".join([chr(char) for char in cmd_output])
                      if cmd_output is not None else msgRep.BASH_ERROR)
    except Exception as e:
        log.error(e, exc_info=True)
        cmd_output = msgRep.BASH_ERROR
    try:
        await event.edit(f"`$ {full_cmd_str}\n\n{cmd_output}`")
    except MessageTooLongError:
        log.info("Shell output is too large. "
                 "Trying to upload output as a file...")
        await outputAsFile(event, cmd_output)
    return
Esempio n. 2
0
def _print_instructions(commit_id: str):
    if isWindows():
        print()
        print("=== UPDATE INSTRUCTIONS ===")
        print(f"Commit ID: {commit_id}")
        print("- Start recovery (python recovery.py)")
        print("- Select 'Apply update'")
        print("- Enter commit id (see above)")
        print("- Wait for recovery to finish")
        print("- Exit recovery")
        print("- Start HyperUBot (python -m userbot)")
        print()
    return
Esempio n. 3
0
def module_info(name_of_module: str, module: str) -> str:
    if module in getLoadModules().keys():
        package_name, moduletype, installation_date = (msgRep.UNKNOWN, ) * 3
        size = 0
        authors = getModuleInfo().get(module, {}).get("authors",
                                                      msgRep.UNKNOWN)
        version = getModuleInfo().get(module, {}).get("version", 0)
        package_name = module
        module += ".py"
        syspath = join(".", "userbot", "modules")
        userpath = join(".", "userbot", "modules_user")
        if exists(join(syspath, module)):
            moduletype = msgRep.SYSTEM
            size = sizeStrMaker(getsize(join(syspath, module)))
            if isWindows():
                installation_date = getctime(join(syspath, module))
            elif isMacOS():
                installation_date = stat(join(syspath, module)).st_birthtime
            else:
                installation_date = stat(join(syspath, module)).st_ctime
        elif exists(join(userpath, module)):
            moduletype = msgRep.USER
            size = sizeStrMaker(getsize(join(userpath, module)))
            if isWindows():
                installation_date = getctime(join(userpath, module))
            elif isMacOS():
                installation_date = stat(join(userpath, module)).st_birthtime
            else:
                installation_date = stat(join(userpath, module)).st_ctime
        result = f"{msgRep.PKG_NAME}: {package_name}\n"
        result += f"{msgRep.MODULE_TYPE}: {moduletype}\n"
        result += f"{msgRep.AUTHORS}: {authors}\n"
        result += f"{msgRep.VERSION}: {version}\n"
        result += f"{msgRep.SIZE}: {size}\n"
        result += f"{msgRep.INSTALL_DATE}: {ctime(installation_date)}"
        return msgRep.NAME_MODULE.format(name_of_module) + "\n\n" + result
    else:
        raise IndexError
Esempio n. 4
0
async def restart(power_off):  # Totally not a shutdown kang *sips whiskey*
    if isWindows():
        await power_off.edit(msgRep.RESTART_UNSUPPORTED)
        return
    cmd_args = power_off.pattern_match.group(1).split(" ", 1)
    if cmd_args[0] == "safemode":
        setConfig("REBOOT_SAFEMODE", True)
    setConfig("REBOOT", True)
    await power_off.edit(msgRep.RESTART)
    if getConfig("LOGGING"):
        await event_log(power_off, "RESTART", custom_text=msgRep.RESTART_LOG)
    _setprop("reboot", True)
    _setprop("rebootchatid", power_off.chat_id)
    _setprop("rebootmsgid", power_off.message.id)
    _setprop("rebootmsg", msgRep.RESTARTED)
    await power_off.client.disconnect()
    return
import userbot.include.git_api as git
from userbot.sysutils.event_handler import EventHandler
from userbot.sysutils.registration import register_cmd_usage, register_module_desc, register_module_info
from logging import getLogger
import sys
import requests
import os
import time

log = getLogger(__name__)

MODULE_LIST = []

from userbot.sysutils.sys_funcs import isWindows

if isWindows():
    USER_MODULES_DIR = ".\\userbot\\modules_user\\"
else:
    USER_MODULES_DIR = "./userbot/modules_user/"

if " " not in sys.executable:
    EXECUTABLE = sys.executable
else:
    EXECUTABLE = '"' + sys.executable + '"'

def list_updater():
    global MODULE_LIST
    MODULE_LIST = []
    assets = git.getAssets(git.getReleaseData(git.getData("userbot8895/HUB-Plus"), 0))
    for asset in assets:
        assetName = git.getReleaseFileName(asset)
Esempio n. 6
0
def setColorText(text: str, color: Colors) -> str:
    if isWindows() and not WIN_COLOR_ENABLED:
        return text  # don't use ANSI codes
    return color + text + Colors.END
Esempio n. 7
0
async def updater(event):
    arg = event.pattern_match.group(1)
    git_repo = await _is_git_repo()
    warn_emoji = u"\u26A0"
    update_now = True if arg.lower() == "upgrade" else False
    global _LATEST_VER

    if not update_now or (update_now and not _LATEST_VER):
        await event.edit(msgRep.CHECKING_UPDATES)

    if update_now and _LATEST_VER:
        await event.edit(msgRep.DOWNLOADING_RELEASE)
        if not _get_latest_release(_LATEST_VER.get("rules"),
                                   _LATEST_VER.get("zip")):
            await event.edit(msgRep.UPDATE_FAILED)
            log.error("Failed to download latest release. Aborting process",
                      exc_info=True)
            _LATEST_VER.clear()
            return
        release_ver = _LATEST_VER.get("version")
        _LATEST_VER.clear()
        commit_id = _get_commit_id()
        if not commit_id:
            await event.edit(msgRep.UPDATE_FAILED)
            return
        if isWindows():
            _print_instructions(commit_id)
            await event.edit(msgRep.DOWNLOAD_SUCCESS_WIN)
        else:
            await event.edit(msgRep.DOWNLOAD_SUCCESS)
            if _set_autoupdate(event.chat_id, event.message.id, release_ver,
                               commit_id):
                await event.client.disconnect()
            else:
                await event.edit(msgRep.START_RECOVERY_FAILED)
        return

    try:
        release_data = getLatestData("prototype74/HyperUBot")
    except Exception:
        await event.edit(msgRep.UPDATE_FAILED)
        log.error("Failed to get latest release", exc_info=True)
        return

    try:
        tag_version = release_data["tag_name"][1:]
        release_version = verAsTuple(tag_version)
    except ValueError:
        await event.edit(msgRep.UPDATE_FAILED)
        log.error("Invalid tag version from release", exc_info=True)
        return
    except Exception:
        await event.edit(msgRep.UPDATE_FAILED)
        log.error("Failed to parse tag version from release", exc_info=True)
        return

    if VERSION_TUPLE > release_version:
        log.warning(f"Current version newer than on release server "
                    f"({VERSION} > {tag_version})")
        await event.edit(f"{msgRep.UPDATE_FAILED}: "
                         f"{msgRep.UPDATE_INTERNAL_FAILED}")
        if _LATEST_VER:
            _LATEST_VER.clear()
        return

    if VERSION_TUPLE == release_version:
        log.info(f"Already up-to-date")
        reply = f"**{msgRep.ALREADY_UP_TO_DATE}**\n\n"
        if git_repo:
            reply += f"{warn_emoji} __{msgRep.GIT_REPO}__\n\n"
        reply += f"{msgRep.LATEST}: {tag_version}\n"
        reply += f"{msgRep.CURRENT}: {VERSION}\n"
        if _LATEST_VER:
            _LATEST_VER.clear()
        await event.edit(reply)
        return

    if VERSION_TUPLE < release_version:
        _LATEST_VER["version"] = tag_version
        try:
            assets = release_data.get("assets", [])
            if assets:
                for asset in assets:
                    if asset.get("name", "") == "rules.py":
                        _LATEST_VER["rules"] = asset.get(
                            "browser_download_url")
                        break
        except Exception:
            await event.edit(msgRep.UPDATE_FAILED)
            log.error("Failed to get assets from release", exc_info=True)
            return
        _LATEST_VER["zip"] = release_data.get("zipball_url")
        release_url = release_data.get("html_url")
        publish_date = _parse_datetime(release_data["published_at"])
        log.info(f"An Update to {tag_version} is available")
        reply = f"**{msgRep.UPDATE_AVAILABLE}**\n\n"
        if git_repo:
            reply += f"{warn_emoji} __{msgRep.GIT_REPO}__\n\n"
        reply += f"**{msgRep.LATEST}: {tag_version}**\n"
        reply += f"{msgRep.CURRENT}: {VERSION}\n"
        reply += (f"{msgRep.RELEASE_DATE}: {publish_date}\n\n"
                  if publish_date else "\n")
        reply += msgRep.CHANGELOG_AT.format(f"[GitHub]({release_url})\n\n")
        if update_now:
            reply += msgRep.DOWNLOADING_RELEASE
            await event.edit(reply)
            if not _get_latest_release(_LATEST_VER.get("rules"),
                                       _LATEST_VER.get("zip")):
                await event.edit(
                    reply.replace(msgRep.DOWNLOADING_RELEASE,
                                  msgRep.UPDATE_FAILED))
                log.error(
                    "Failed to download latest release. "
                    "Aborting process",
                    exc_info=True)
                _LATEST_VER.clear()
                return
            _LATEST_VER.clear()
            commit_id = _get_commit_id()
            if not commit_id:
                await event.edit(
                    reply.replace(msgRep.DOWNLOADING_RELEASE,
                                  msgRep.UPDATE_FAILED))
                return
            if isWindows():
                _print_instructions(commit_id)
                await event.edit(
                    reply.replace(msgRep.DOWNLOADING_RELEASE,
                                  msgRep.DOWNLOAD_SUCCESS_WIN))
            else:
                await event.edit(
                    reply.replace(msgRep.DOWNLOADING_RELEASE,
                                  msgRep.DOWNLOAD_SUCCESS))
                if _set_autoupdate(event.chat_id, event.message.id,
                                   tag_version, commit_id):
                    await event.client.disconnect()
                else:
                    await event.edit(
                        reply.replace(msgRep.DOWNLOAD_SUCCESS,
                                      msgRep.START_RECOVERY_FAILED))
        else:
            reply += msgRep.UPDATE_QUEUED
            await event.edit(reply)
    return