Skip to content

Commit

Permalink
feat: Improve codes and update ci config.
Browse files Browse the repository at this point in the history
  • Loading branch information
loonghao committed May 4, 2024
1 parent 6c654f9 commit a5d5d46
Show file tree
Hide file tree
Showing 11 changed files with 79 additions and 65 deletions.
10 changes: 4 additions & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,16 @@ repos:
rev: 22.12.0
hooks:
- id: black
language_version: python3.10
- hooks:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-docstring-first
- id: check-json
- id: check-yaml
- id: debug-statements
- id: double-quote-string-fixer
- id: name-tests-test
- id: requirements-txt-fixer
repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.4.0
- hooks:
- additional_dependencies:
- flake8-typing-imports==1.5.0
Expand Down
2 changes: 1 addition & 1 deletion maya_umbrella/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
from maya_umbrella.core import Defender


__all__ = ['Defender']
__all__ = ["Defender"]
13 changes: 3 additions & 10 deletions maya_umbrella/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,8 @@


class Defender(object):
callback_ids = [

]
remove_callbacks = [

]
callback_ids = []
remove_callbacks = []
_bad_files = []
_vaccines = []
callback_maps = {
Expand Down Expand Up @@ -57,10 +53,7 @@ def setup(self):
method_name = matched.group("name")
self.logger.info("setup %s.", name)
self.callback_ids.append(
{
name: om.MSceneMessage.addCallback(callback,
getattr(self, "{0}_callback".format(method_name)))
}
{name: om.MSceneMessage.addCallback(callback, getattr(self, "{0}_callback".format(method_name)))}
)

def before_callback(self, *args, **kwargs):
Expand Down
15 changes: 6 additions & 9 deletions maya_umbrella/filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ def this_root():
return os.path.abspath(os.path.dirname(__file__))



def safe_remove_file(file_path):
"""Remove the file at the given path without raising an error if the file does not exist."""
try:
Expand Down Expand Up @@ -66,7 +65,7 @@ def patch_file(source, target, key_values, report_error=True):

def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
"""Generate a random string of the given size using the given characters."""
return ''.join(random.choice(chars) for _ in range(size))
return "".join(random.choice(chars) for _ in range(size))


def rename(src):
Expand All @@ -82,10 +81,11 @@ def rename(src):
def load_hook(hook_file):
"""Load the Python module from the given hook file."""
hook_name = os.path.basename(hook_file).split(".py")[0]
if hasattr(importlib, 'machinery'):
if hasattr(importlib, "machinery"):
# Python 3
# Import built-in modules
from importlib.util import spec_from_loader

loader = importlib.machinery.SourceFileLoader(hook_name, hook_file)
spec = importlib.util.spec_from_loader(loader.name, loader=loader)
module = importlib.util.module_from_spec(spec)
Expand All @@ -94,20 +94,17 @@ def load_hook(hook_file):
# Python 2
# Import built-in modules
import imp

module = imp.load_source(hook_name, hook_file)
return module


def get_hooks():
"""Return a list of paths to all hook files in the 'hooks' directory."""
pattern = os.path.join(this_root(), "hooks", "*.py")
return [
hook for hook in glob.glob(pattern) if "__init__" not in hook
]
return [hook for hook in glob.glob(pattern) if "__init__" not in hook]


def get_vaccines():
pattern = os.path.join(this_root(), "vaccines", "*.py")
return [
vaccine for vaccine in glob.glob(pattern) if "__init__" not in vaccine
]
return [vaccine for vaccine in glob.glob(pattern) if "__init__" not in vaccine]
8 changes: 4 additions & 4 deletions maya_umbrella/hooks/fix_on_model_change_3dc.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@
def hook(logger):
needs_fixing = False
try:
expression_str = cmds.getAttr('uiConfigurationScriptNode.before')
expression_str = cmds.getAttr("uiConfigurationScriptNode.before")
fixed_expression_lines = []
for line in expression_str.split('\n'):
for line in expression_str.split("\n"):
if '-editorChanged "onModelChange3dc"' in line:
needs_fixing = True
continue
fixed_expression_lines.append(line)
fixed_expression = '\n'.join(fixed_expression_lines)
fixed_expression = "\n".join(fixed_expression_lines)
if needs_fixing:
cmds.setAttr('uiConfigurationScriptNode.before', fixed_expression, typ='string')
cmds.setAttr("uiConfigurationScriptNode.before", fixed_expression, typ="string")
except:
pass
mel.eval('outlinerEditor -edit -selectCommand "" "outlinerPanel1";')
8 changes: 2 additions & 6 deletions maya_umbrella/vaccine.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,7 @@ def local_script_path(self):

@property
def bad_files(self):
return [

]
return []

@property
def bad_nodes(self):
Expand All @@ -50,9 +48,7 @@ def bad_script_nodes(self):
return []

def collect(self):
self._bad_files.extend(
[temp_file for temp_file in glob.glob(os.path.join(self.local_script_path, "._*"))]
)
self._bad_files.extend([temp_file for temp_file in glob.glob(os.path.join(self.local_script_path, "._*"))])

def remove_bad_files(self):
self.collect()
Expand Down
2 changes: 1 addition & 1 deletion maya_umbrella/vaccines/vaccine1.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@ def __init__(self, logger=None):
def bad_files(self):
return [
os.path.join(self.local_script_path, "fuckVirus.py"),
os.path.join(self.local_script_path, "fuckVirus.pyc")
os.path.join(self.local_script_path, "fuckVirus.pyc"),
]
25 changes: 12 additions & 13 deletions maya_umbrella/vaccines/vaccine2.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,20 @@ def __init__(self, logger=None):

@property
def bad_files(self):
return [
os.path.join(self.local_script_path, "vaccine.py"),
os.path.join(self.local_script_path, "vaccine.pyc")
]
return [os.path.join(self.local_script_path, "vaccine.py"), os.path.join(self.local_script_path, "vaccine.pyc")]

def _get_nodes(self):
bad_script_nodes = []
for script_node in cmds.ls(type="script"):
if cmds.referenceQuery(script_node, isNodeReferenced=True):
continue
script_before_string = cmds.getAttr('{}.before'.format(script_node))
script_after_string = cmds.getAttr('{}.after'.format(script_node))
script_before_string = cmds.getAttr("{}.before".format(script_node))
script_after_string = cmds.getAttr("{}.after".format(script_node))
for script_string in [script_before_string, script_after_string]:
if not script_string:
continue
if 'internalVar' in script_string or 'userSetup' in script_string or 'fuckVirus' in script_string:
self._logger.warning('script node {} has internalVar or userSetup or fuckVirus'.format(script_node))
if "internalVar" in script_string or "userSetup" in script_string or "fuckVirus" in script_string:
self._logger.warning("script node {} has internalVar or userSetup or fuckVirus".format(script_node))
bad_script_nodes.append(script_node)
return bad_script_nodes

Expand All @@ -48,17 +45,19 @@ def check_usersetup_py(self):
os.path.join(self.local_script_path, "vaccine.py"),
os.path.join(self.user_script_path, "vaccine.py"),
os.path.join(self.local_script_path, "userSetup.py"),
os.path.join(self.user_script_path, "userSetup.py")
os.path.join(self.user_script_path, "userSetup.py"),
]:
if os.path.exists(usersetup_py):
data = read_file(usersetup_py)
if "petri_dish_path = cmds.internalVar(userAppDir=True) + 'scripts/userSetup.py" in data:
self._logger.warning('vaccine.py found : Infected by Malware!')
self._logger.warning("vaccine.py found : Infected by Malware!")
self._bad_files.append(rename(usersetup_py))

if "cmds.evalDeferred(\'leukocyte = vaccine.phage()\')" in data \
and "cmds.evalDeferred(\'leukocyte.occupation()\')" in data:
self._logger.warning('userSetup.py : Infected by Malware!')
if (
"cmds.evalDeferred('leukocyte = vaccine.phage()')" in data
and "cmds.evalDeferred('leukocyte.occupation()')" in data
):
self._logger.warning("userSetup.py : Infected by Malware!")
self._bad_files.append(rename(usersetup_py))

def before_callback(self, *args, **kwargs):
Expand Down
47 changes: 36 additions & 11 deletions maya_umbrella/vaccines/vaccine3.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

class Vaccine(BaseVaccine):
virus_name = "virus2024429"
hik_regex = r'python\(\"import base64;\s*pyCode\s*=\s*base64\.urlsafe_b64decode\([\'\"].*?[\"\']\);\s*exec\s*\(\s*pyCode\s*\)\"\)\s*;'
hik_regex = r"python\(\"import base64;\s*pyCode\s*=\s*base64\.urlsafe_b64decode\([\'\"].*?[\"\']\);\s*exec\s*\(\s*pyCode\s*\)\"\)\s*;"
_bad_files = []

def __init__(self, logger=None):
Expand All @@ -26,7 +26,7 @@ def bad_files(self):

@property
def get_syssst_dir(self):
return os.path.join(os.getenv('APPDATA'), 'syssst')
return os.path.join(os.getenv("APPDATA"), "syssst")

def _get_nodes(self):
bad_expression = []
Expand All @@ -46,8 +46,10 @@ def check_usersetup_mel(self):
# check usersetup.mel
# C:/Users/hallong/Documents/maya/scripts/usersetup.mel
# C:/Users/hallong/Documents/maya/xxxx/scripts/usersetup.mel
for usersetup_mel in [os.path.join(self.local_script_path, "usersetup.mel"),
os.path.join(self.user_script_path, "usersetup.mel")]:
for usersetup_mel in [
os.path.join(self.local_script_path, "usersetup.mel"),
os.path.join(self.user_script_path, "usersetup.mel"),
]:
if os.path.exists(usersetup_mel):
data = read_file(usersetup_mel)
if "import base64; pyCode = base64.urlsafe_b64decode" in data:
Expand All @@ -58,25 +60,48 @@ def bad_nodes(self):
return self._get_nodes()

def before_callback(self, *args, **kwargs):
self._bad_files.extend([
self.get_syssst_dir
])
self._bad_files.extend([self.get_syssst_dir])
self.check_usersetup_mel()
self.fix_hik_files()
self.fix_script_job()
super(Vaccine, self).before_callback(args, kwargs)

def fix_hik_files(self):
pattern = os.path.join(self.maya_install_root, 'resources/l10n/*/plug-ins/mayaHIK.pres.mel')
pattern = os.path.join(self.maya_install_root, "resources/l10n/*/plug-ins/mayaHIK.pres.mel")
for hik_mel in glob.glob(pattern):
with open(hik_mel, 'rb') as f:
with open(hik_mel, "rb") as f:
data = f.read()

if len(re.findall(self.hik_regex, data)) > 0:
with open(hik_mel, 'wb') as f:
f.write(re.sub(self.hik_regex, '', data))
with open(hik_mel, "wb") as f:
f.write(re.sub(self.hik_regex, "", data))
self._logger.warning("Remove virus code from {}".format(hik_mel))

def fix_script_job(self):
virus_gene = [
"leukocyte",
"execute",
]

def get_virus_script_jobs():
"""Traverse the list of virus script job name.
Returns:
list: Malicious virus script job name.
"""
return [
scriptjob
for scriptjob in cmds.scriptJob(listJobs=True)
for virus in virus_gene
if virus in scriptjob
]

for script_job in get_virus_script_jobs():
script_num = int(script_job.split(":", 1)[0])
self._logger.info("Kill script job {}".format(script_job))
cmds.scriptJob(kill=script_num, force=True)

def after_callback(self, *args, **kwargs):
"""After callback."""
self.check_usersetup_mel()
self.fix_hik_files()
super(Vaccine, self).after_callback(args, kwargs)
12 changes: 9 additions & 3 deletions noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,18 @@ def lint(session: nox.Session) -> None:

@nox.session
def preflight(session: nox.Session) -> None:
session.install("pre-commit")
session.install("black")
session.install("isort")
session.install("pre-commit")
# session.run("black", PACKAGE_NAME)
session.run("isort", PACKAGE_NAME)

session.run(
"pre-commit",
"run",
"--all-files",
"--show-diff-on-failure",
"--hook-stage=manual",
*session.posargs,
)

def add_dynamic_maya_session(session_name, command):
@nox.session(name=session_name, python=False)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ build-backend = "poetry.core.masonry.api"

[tool.black]
line-length = 120
target_version = ['py37']
target_version = ['py36']
include = '\.pyi?$'
exclude = '''
Expand Down

0 comments on commit a5d5d46

Please sign in to comment.