ResourcePackUpdater/app/pack.py

92 lines
2.9 KiB
Python
Executable File

import os
import re
import shutil
from shutil import make_archive
import hashlib
from b2sdk.v1 import InMemoryAccountInfo
from b2sdk.v1 import B2Api
from dotenv import load_dotenv
class Pack:
def __init__(self):
os.environ["GIT_SSH_COMMAND"] = f"/usr/bin/ssh -o StrictHostKeyChecking=no -i {os.getcwd()}/{os.environ.get('SSH_KEY')}"
self.branch = os.environ.get('BRANCH')
self.packurl = os.environ.get('RESOURCE_PACK_URL')
if os.path.exists("files"):
shutil.rmtree("files")
os.mkdir("files")
info = InMemoryAccountInfo() # store credentials, tokens and cache in memory
self.b2_api = B2Api(info)
self.b2_api.authorize_account("production", os.environ.get("B2_ID"), os.environ.get("B2_KEY"))
self.bucket = self.b2_api.get_bucket_by_name(os.environ.get("BUCKET"))
def clone(self):
command = f"git clone -b {self.branch} --single-branch {self.packurl} files/resourcepack"
return os.system(command)
def __del__(self):
if os.path.exists("files"):
shutil.rmtree("files")
def pull(self) -> None:
print("Pulling")
command = f"git -C files/resourcepack pull origin {self.branch}"
return os.system(command)
def collate(self) -> None:
print("Collating")
if os.path.exists("files/pack"):
shutil.rmtree("files/pack")
os.mkdir("files/pack")
shutil.copytree("files/resourcepack/assets", "files/pack/assets")
shutil.copy("files/resourcepack/pack.mcmeta", "files/pack/pack.mcmeta")
shutil.copy("files/resourcepack/pack.png", "files/pack/pack.png")
def compress(self) -> None:
print("Compressing")
shutil.make_archive("files/pack", 'zip', "files/pack")
shutil.rmtree("files/pack")
print("Compressed")
def hashPack(self):
try:
print("Hashing")
sha1sum = hashlib.sha1()
with open("files/pack.zip", "rb") as pack:
block = pack.read(2**16)
while len(block) != 0:
sha1sum.update(block)
block = pack.read(2**16)
self.hash = sha1sum.hexdigest()
print("Write hash")
with open("files/hash", 'w') as hashfile:
hashfile.write(self.hash)
except Exception:
print("Failed to hash")
def upload(self):
print("Uploading")
self.b2_api.authorize_account("production", os.environ.get("B2_ID"), os.environ.get("B2_KEY"))
self.bucket.upload_local_file(local_file="files/pack.zip", file_name="pack.zip")
self.bucket.upload_local_file(local_file="files/hash", file_name="hash")
def gethash(self):
return self.hash
if __name__ == "__main__":
load_dotenv()
print("Pack")
pack = Pack()
pack.clone()
pack.pull()
pack.collate()
pack.compress()
pack.hash()
#pack.upload()
pack = None