Skip to content

Commit

Permalink
Reduce code smells
Browse files Browse the repository at this point in the history
  • Loading branch information
laggykiller committed Oct 2, 2023
1 parent 9e5ff7d commit 76c7cdb
Show file tree
Hide file tree
Showing 12 changed files with 81 additions and 84 deletions.
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@ RUN chmod -R 777 /app

VOLUME ["/app/stickers_input", "/app/stickers_output"]

FROM base-gui as min-gui
FROM base-gui AS min-gui
RUN apt purge -y curl wget gpg git && \
apt clean autoclean && \
apt autoremove --yes && \
rm -rf /var/lib/{apt,dpkg,cache,log}/

FROM base-gui as full
FROM base-gui AS full
# Install signal-desktop-beta
RUN wget -O- https://updates.signal.org/desktop/apt/keys.asc | gpg --dearmor > signal-desktop-keyring.gpg && \
cat signal-desktop-keyring.gpg | tee -a /usr/share/keyrings/signal-desktop-keyring.gpg > /dev/null && \
Expand Down
10 changes: 5 additions & 5 deletions compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def osx_install_universal2_dep():
osx_run_in_venv('python -m pip download --require-virtualenv -r requirements.txt --platform macosx_11_0_x86_64 --only-binary=:all: -d wheel_x64')

create_universal_wheels('./wheel_arm', './wheel_x64', 'wheel_universal2')
osx_run_in_venv(f'python -m pip install --require-virtualenv ./wheel_universal2/*')
osx_run_in_venv('python -m pip install --require-virtualenv ./wheel_universal2/*')

def nuitka(python_bin, arch):
cmd_list = [
Expand All @@ -99,7 +99,7 @@ def nuitka(python_bin, arch):
cmd_list.append('--windows-icon-from-ico=src/sticker_convert/resources/appicon.ico')
elif platform.system() == 'Darwin' and arch:
cmd_list.append(f'--macos-target-arch={arch}')
cmd_list.append(f'--disable-console')
cmd_list.append('--disable-console')

cmd_list.append('src/sticker-convert.py')
if platform.system() == 'Darwin':
Expand All @@ -122,7 +122,7 @@ def osx_patch():
f.write('open ./sticker-convert-cli')
os.chmod('sticker-convert.app/Contents/MacOS/sticker-convert', 0o744)

osx_run_in_venv(f'codesign --force --deep -s - sticker-convert.app')
osx_run_in_venv('codesign --force --deep -s - sticker-convert.app')

def compile():
arch = os.environ.get('SC_COMPILE_ARCH')
Expand Down Expand Up @@ -153,8 +153,8 @@ def compile():

if platform.system() == 'Windows':
win_patch()
elif platform.system() == 'Darwin' and arch:
osx_patch()
# elif platform.system() == 'Darwin':
# osx_patch()

if __name__ == '__main__':
compile()
4 changes: 2 additions & 2 deletions scripts/opt-comp-experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def put(self, msg: str):

def generate_random_apng(res: int, fps: float, duration: float, out_f: str):
apngasm = APNGAsm()
for i in range(int(duration/1000*fps)):
for _ in range(int(duration/1000*fps)):
im = numpy.random.rand(res, res, 4) * 255
frame = create_frame_from_rgba(im, res, res)
frame.delay_num = int(1000 / fps)
Expand Down Expand Up @@ -171,7 +171,7 @@ def main():
Thread(target=write_result, args=(csv_path, results_queue, len(combinations))).start()

processes = []
for i in range(processes_max):
for _ in range(processes_max):
process = Process(
target=compress_worker,
args=(jobs_queue, results_queue)
Expand Down
10 changes: 6 additions & 4 deletions src/sticker_convert/auth/get_signal_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ def download_signal_desktop(self, download_url: str, signal_bin_path: str):

self.cb_msg(download_url)

prompt = f'Signal Desktop not detected.\nDownload and install Signal Desktop BETA version\nAfter installation, quit Signal Desktop before continuing'
prompt = 'Signal Desktop not detected.\n'
prompt += 'Download and install Signal Desktop BETA version\n'
prompt += 'After installation, quit Signal Desktop before continuing'
while not (os.path.isfile(signal_bin_path) or shutil.which(signal_bin_path)):
if self.cb_ask_str != input:
self.cb_ask_str(prompt, initialvalue=download_url, cli_show_initialvalue=False)
Expand Down Expand Up @@ -154,7 +156,7 @@ def download_chromedriver(self, major_version: str, chromedriver_download_dir: s
with zipfile.ZipFile(f, 'r') as z, open(chromedriver_path, 'wb+') as g:
g.write(z.read(chromedriver_zip_path))

if not platform.system() == 'Windows':
if platform.system() != 'Windows':
st = os.stat(chromedriver_path)
os.chmod(chromedriver_path, st.st_mode | stat.S_IEXEC)

Expand Down Expand Up @@ -187,7 +189,7 @@ def get_cred(self) -> tuple[Optional[str], Optional[str]]:
else:
uuid = str(self.driver.execute_script('return window.SignalDebug.getReduxState().items.uuid_id'))
password = str(self.driver.execute_script('return window.SignalDebug.getReduxState().items.password'))
except JavascriptException as e:
except JavascriptException:
pass

return uuid, password
Expand Down Expand Up @@ -241,7 +243,7 @@ def launch_signal_desktop(self):
if major_version:
self.cb_msg(f'Signal Desktop is using chrome version {major_version}')
else:
self.cb_msg(f'Unable to determine Signal Desktop chrome version')
self.cb_msg('Unable to determine Signal Desktop chrome version')
return

chromedriver_path, local_chromedriver_version = self.get_local_chromedriver(chromedriver_download_dir=self.chromedriver_download_dir)
Expand Down
8 changes: 4 additions & 4 deletions src/sticker_convert/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def cli(self):
parser = argparse.ArgumentParser(description='CLI for stickers-convert', formatter_class=argparse.RawTextHelpFormatter)

parser.add_argument('--version', action='version', version=__version__)
parser.add_argument(f'--no-confirm', dest='no_confirm', action='store_true', help=self.help['global']['no_confirm'])
parser.add_argument('--no-confirm', dest='no_confirm', action='store_true', help=self.help['global']['no_confirm'])

parser_input = parser.add_argument_group('Input options')
for k, v in self.help['input'].items():
Expand Down Expand Up @@ -176,7 +176,7 @@ def get_opt_comp(self, args):
if output_option == 'local':
preset = 'custom'
args.no_compress = True
self.cb_msg(f'Auto compression option set to no_compress (Reason: Export to local directory only)')
self.cb_msg('Auto compression option set to no_compress (Reason: Export to local directory only)')
elif output_option == 'imessage':
preset = 'imessage_small'
self.cb_msg(f'Auto compression option set to {preset}')
Expand Down Expand Up @@ -288,9 +288,9 @@ def get_opt_cred(self, args):
if line_cookies:
self.opt_cred['line']['cookies'] = line_cookies

self.cb_msg(f'Got Line cookies successfully')
self.cb_msg('Got Line cookies successfully')
else:
self.cb_msg(f'Failed to get Line cookies. Have you logged in the web browser?')
self.cb_msg('Failed to get Line cookies. Have you logged in the web browser?')

if args.save_cred:
creds_path = os.path.join(CurrDir.get_config_dir(), 'creds.json')
Expand Down
2 changes: 1 addition & 1 deletion src/sticker_convert/downloaders/download_kakao.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def download_animated(self, item_code: str) -> bool:

num = 0
with zipfile.ZipFile(io.BytesIO(zip_file)) as zf:
self.cb_msg(f'Unzipping...')
self.cb_msg('Unzipping...')
if self.cb_bar:
self.cb_bar(set_progress_mode='determinate', steps=len(zf.namelist()))

Expand Down
5 changes: 2 additions & 3 deletions src/sticker_convert/downloaders/download_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ def analyze_url(url: str) -> Optional[tuple[str, str, bool]]:
pack_id = url.replace('https://line.me/S/sticker/', '').split('/')[0]
region = parse.parse_qs(url_parsed.query)['lang'][0]
elif url.startswith('https://store.line.me/officialaccount/event/sticker/'):
url_parsed = parse.urlparse(url)
pack_id = url.replace('https://store.line.me/officialaccount/event/sticker/', '').split('/')[0]
region = url.replace('https://store.line.me/officialaccount/event/sticker/', '').split('/')[1]
elif url.startswith('https://store.line.me/emojishop/product/'):
Expand Down Expand Up @@ -178,7 +177,7 @@ def get_pack_url(self) -> str:
def decompress_emoticon(self, zip_file: bytes):
num = 0
with zipfile.ZipFile(io.BytesIO(zip_file)) as zf:
self.cb_msg(f'Unzipping...')
self.cb_msg('Unzipping...')

self.cb_bar(set_progress_mode='determinate', steps=len(self.pack_files))
for sticker in self.pack_files:
Expand All @@ -201,7 +200,7 @@ def decompress_emoticon(self, zip_file: bytes):
def decompress_stickers(self, zip_file: bytes):
num = 0
with zipfile.ZipFile(io.BytesIO(zip_file)) as zf:
self.cb_msg(f'Unzipping...')
self.cb_msg('Unzipping...')

self.cb_bar(set_progress_mode='determinate', steps=len(self.pack_files))
for sticker in self.pack_files:
Expand Down
4 changes: 0 additions & 4 deletions src/sticker_convert/gui_frames/progress_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@ def update_message_box(self, *args, **kwargs):
msg = kwargs.get('msg')
cls = kwargs.get('cls')

# scrollbar_prev_loc = self.message_box.yview()[1]

if not msg and len(args) == 1:
msg = str(args[0])

Expand All @@ -77,8 +75,6 @@ def update_message_box(self, *args, **kwargs):
if msg:
self.message_box.insert('end', msg)

# Follow the end of the box if it was at the end
# if scrollbar_prev_loc == 1.0:
if self.auto_scroll:
self.message_box._text.yview_moveto(1.0)

Expand Down
2 changes: 1 addition & 1 deletion src/sticker_convert/gui_windows/line_get_auth_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def cb_get_cookies_thread(self, *args):
self.gui.creds['line']['cookies'] = line_cookies
self.gui.line_cookies_var.set(line_cookies)

self.cb_msg_block_line(f'Got Line cookies successfully')
self.cb_msg_block_line('Got Line cookies successfully')
self.gui.save_creds()
self.gui.highlight_fields()
return
Expand Down
2 changes: 1 addition & 1 deletion src/sticker_convert/uploaders/upload_signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def upload_stickers_signal(self) -> list[str]:
msg_block = 'emoji.txt is required for uploading signal stickers\n'
msg_block += f'emoji.txt generated for you in {self.in_dir}\n'
msg_block += f'Default emoji is set to {self.opt_comp.get("default_emoji")}.\n'
msg_block += f'Please edit emoji.txt now, then continue'
msg_block += 'Please edit emoji.txt now, then continue'
MetadataHandler.generate_emoji_file(dir=self.in_dir, default_emoji=self.opt_comp.get("default_emoji"))

self.cb_msg_block(msg_block)
Expand Down
12 changes: 6 additions & 6 deletions src/sticker_convert/uploaders/xcode_imessage.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ def create_xcode_proj(self, author: str, title: str):
# packname StickerPackExtension/Stickers.xcstickers/Sticker Pack.stickerpack/0.sticker/0.png
shutil.copy(os.path.join(self.in_dir, i), os.path.join(sticker_path, i))

dict = {
json_content = {
'info': {
'author': 'xcode',
'version': 1,
Expand All @@ -229,18 +229,18 @@ def create_xcode_proj(self, author: str, title: str):

# packname StickerPackExtension/Stickers.xcstickers/Sticker Pack.stickerpack/0.sticker/Contents.json
with open(os.path.join(sticker_path, 'Contents.json'), 'w+') as f:
json.dump(dict, f, indent=2)
json.dump(json_content, f, indent=2)

# packname StickerPackExtension/Stickers.xcstickers/Sticker Pack.stickerpack/Contents.json
with open(os.path.join(stickers_path, 'Contents.json')) as f:
dict = json.load(f)
json_content = json.load(f)

dict['stickers'] = []
json_content['stickers'] = []
for i in stickers_lst:
dict['stickers'].append({'filename': i}) # type: ignore[attr-defined]
json_content['stickers'].append({'filename': i}) # type: ignore[attr-defined]

with open(os.path.join(stickers_path, 'Contents.json'), 'w+') as f:
json.dump(dict, f, indent=2)
json.dump(json_content, f, indent=2)

# packname StickerPackExtension/Stickers.xcstickers/iMessage App Icon.stickersiconset
iconset_path = os.path.join(pack_path, 'stickers StickerPackExtension/Stickers.xcstickers/iMessage App Icon.stickersiconset')
Expand Down
102 changes: 51 additions & 51 deletions src/sticker_convert/utils/apple_png_normalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,85 +8,85 @@

class ApplePngNormalize:
@staticmethod
def normalize(oldPNG: bytes) -> bytes:
pngheader = b"\x89PNG\r\n\x1a\n"
def normalize(old_png: bytes) -> bytes:
png_header = b"\x89PNG\r\n\x1a\n"

if oldPNG[:8] != pngheader:
return oldPNG
if old_png[:8] != png_header:
return old_png

newPNG = oldPNG[:8]
new_png = old_png[:8]

chunkPos = len(newPNG)
chunkD = bytearray()
chunk_pos = len(new_png)
chunk_d = bytearray()

foundCGBi = False
found_cgbi = False

# For each chunk in the PNG file
while chunkPos < len(oldPNG):
while chunk_pos < len(old_png):

# Reading chunk
chunkLength = oldPNG[chunkPos:chunkPos+4]
chunkLength = struct.unpack(">L", chunkLength)[0]
chunkType = oldPNG[chunkPos+4 : chunkPos+8]
chunkData = oldPNG[chunkPos+8:chunkPos+8+chunkLength] # type: ignore[operator]
chunkCRC = oldPNG[chunkPos+chunkLength+8:chunkPos+chunkLength+12] # type: ignore[operator]
chunkCRC = struct.unpack(">L", chunkCRC)[0]
chunkPos += chunkLength + 12 # type: ignore[operator]
chunk_length = old_png[chunk_pos:chunk_pos+4]
chunk_length = struct.unpack(">L", chunk_length)[0]
chunk_type = old_png[chunk_pos+4 : chunk_pos+8]
chunk_data = old_png[chunk_pos+8:chunk_pos+8+chunk_length] # type: ignore[operator]
chunk_crc = old_png[chunk_pos+chunk_length+8:chunk_pos+chunk_length+12] # type: ignore[operator]
chunk_crc = struct.unpack(">L", chunk_crc)[0]
chunk_pos += chunk_length + 12 # type: ignore[operator]

# Parsing the header chunk
if chunkType == b"IHDR":
width = struct.unpack(">L", chunkData[0:4])[0]
height = struct.unpack(">L", chunkData[4:8])[0]
if chunk_type == b"IHDR":
width = struct.unpack(">L", chunk_data[0:4])[0]
height = struct.unpack(">L", chunk_data[4:8])[0]

# Parsing the image chunk
if chunkType == b"IDAT":
if chunk_type == b"IDAT":
# Concatename all image data chunks
chunkD += chunkData
chunk_d += chunk_data
continue

# Stopping the PNG file parsing
if chunkType == b"IEND":
if not foundCGBi:
return oldPNG
if chunk_type == b"IEND":
if not found_cgbi:
return old_png

bufSize = width * height * 4 + height
chunkData = zlib.decompress(chunkD, -8, bufSize)
chunk_data = zlib.decompress(chunk_d, -8, bufSize)

# Swapping red & blue bytes for each pixel
chunkData = bytearray(chunkData)
chunk_data = bytearray(chunk_data)
offset = 1
for y in range(height):
for x in range(width):
chunkData[offset+4*x],chunkData[offset+4*x+2] = chunkData[offset+4*x+2],chunkData[offset+4*x]
chunk_data[offset+4*x],chunk_data[offset+4*x+2] = chunk_data[offset+4*x+2],chunk_data[offset+4*x]
offset += 1+4*width

# Compressing the image chunk
#chunkData = newdata
chunkData = zlib.compress( chunkData )
chunkLength = len( chunkData ) # type: ignore[assignment]
chunkCRC = zlib.crc32(b'IDAT') # type: ignore[assignment]
chunkCRC = zlib.crc32(chunkData, chunkCRC) # type: ignore[assignment, arg-type]
chunkCRC = (chunkCRC + 0x100000000) % 0x100000000 # type: ignore[operator]

newPNG += struct.pack(">L", chunkLength)
newPNG += b'IDAT'
newPNG += chunkData
newPNG += struct.pack(">L", chunkCRC)

chunkCRC = zlib.crc32(chunkType) # type: ignore[assignment]
newPNG += struct.pack(">L", 0)
newPNG += b'IEND'
newPNG += struct.pack(">L", chunkCRC)
#chunk_data = newdata
chunk_data = zlib.compress(chunk_data)
chunk_length = len(chunk_data) # type: ignore[assignment]
chunk_crc = zlib.crc32(b'IDAT') # type: ignore[assignment]
chunk_crc = zlib.crc32(chunk_data, chunk_crc) # type: ignore[assignment, arg-type]
chunk_crc = (chunk_crc + 0x100000000) % 0x100000000 # type: ignore[operator]

new_png += struct.pack(">L", chunk_length)
new_png += b'IDAT'
new_png += chunk_data
new_png += struct.pack(">L", chunk_crc)

chunk_crc = zlib.crc32(chunk_type) # type: ignore[assignment]
new_png += struct.pack(">L", 0)
new_png += b'IEND'
new_png += struct.pack(">L", chunk_crc)
break

# Removing CgBI chunk
if chunkType == b"CgBI":
foundCGBi = True
if chunk_type == b"CgBI":
found_cgbi = True
else:
newPNG += struct.pack(">L", chunkLength)
newPNG += chunkType
if chunkLength > 0: # type: ignore[operator]
newPNG += chunkData
newPNG += struct.pack(">L", chunkCRC)
new_png += struct.pack(">L", chunk_length)
new_png += chunk_type
if chunk_length > 0: # type: ignore[operator]
new_png += chunk_data
new_png += struct.pack(">L", chunk_crc)

return newPNG
return new_png

0 comments on commit 76c7cdb

Please sign in to comment.