Skip to content

Commit

Permalink
vsthemes parse fix, clean up, cat command, pypi readme
Browse files Browse the repository at this point in the history
  • Loading branch information
theammir committed Dec 4, 2022
1 parent 3dd92e5 commit 869c49f
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 66 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pip install bdtheme
## Usage
You have access to `bdtheme` command now in your `bash`/`cmd`.
* `bdtheme init [path/to/folder]` - initialize BeautifulDiscord and set the `directory` as themes folder. No worries, you probably won't need the files, so you can omit all the arguments. **Requires Discord to be launched**
* `bdtheme download` - themes browser. Navigate with WASD/arrows, "q" to exit, choose whatever you like and hit enter.
* `bdtheme download` - themes browser. Navigate with WaSd/arrows, Shift+A/Shift+D to switch tabs, "q" to exit, choose whatever you like and hit enter.
* `bdtheme set [filename]` - if no `filename` specified, opens browser you're familliar with so you can apply chosen theme. Changes should be visible after no time, otherwise it could happen something's wrong.
* `bdtheme revert` - cleans Discord files up a little, so there's no more BeautifulDiscord and .css hot-reload.
* `bdtheme cat` - print out content of current theme's .css file.
52 changes: 20 additions & 32 deletions bdtheme/src/curses_app.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import contextlib
import curses
import shutil
import re
Expand Down Expand Up @@ -37,6 +38,7 @@ def init_app(stdscr, paginator_data, on_choice):
while mainloop:
paginator = paginators[pag_index]
theme_list = theme_cache[pag_index]
cursor[0] = min([max(5, cursor[0]), wy - 5, len(theme_list) + 4])

stdscr.clear()
# Slashes
Expand All @@ -47,25 +49,23 @@ def init_app(stdscr, paginator_data, on_choice):

# Notes text
stdscr.addstr(3, 3, 'Press "q" to exit.')
stdscr.addstr(wy - 3, 3, '"WasD" or arrows to navigate.')
stdscr.addstr(wy - 2, 3, 'Capital "AS" to switch tabs.')
stdscr.addstr(wy - 3, 3, '"WaSd" or arrows to navigate.')
stdscr.addstr(wy - 2, 3, 'Capital "AD" to switch tabs.')
# No-init warning text
if not os.path.exists(get_themedir()):
stdscr.addstr(
wy - 1, 10, 'Execute "bdtheme init" first!', curses.color_pair(2))
# Themes text
for y in range(min(wy - 5 - 5, len(theme_list))):
try:
stdscr.addstr(y+5, 5, str((y + 1) + (paginator.pagesize * (paginator.page - 1))) + ". "
+ str(theme_list[y]))
stdscr.addstr(y + 5, 5, f"{str(y + 1 + paginator.pagesize * (paginator.page - 1))}. {str(theme_list[y])}")

except IndexError:
break

# Current paginators
tabs_text = []
for p in paginators:
tabs_text.append(f"[ {p.name} ]")
overall_len = sum([len(i) for i in tabs_text])
tabs_text = [f"[ {p.name} ]" for p in paginators]
overall_len = sum(len(i) for i in tabs_text)
start_x = (wx // 2) - (overall_len // 2)
offset = 0
for tab in tabs_text:
Expand All @@ -84,22 +84,20 @@ def init_app(stdscr, paginator_data, on_choice):
if key in [ord("q"), ord("Q"), ord("й"), ord("Й")]:
mainloop = False
elif key in [curses.KEY_DOWN, ord("s"), ord("S"), ord("ы"), ord("Ы")]:
if cursor[0] + 1 in range(5, min(wy, len(theme_list)) + 5):
cursor[0] += 1
# if cursor[0] + 1 in range(5, min(wy, len(theme_list)) + 5):
cursor[0] += 1
elif key in [curses.KEY_UP, ord("w"), ord("W"), ord("ц"), ord("Ц")]:
if cursor[0] - 1 in range(5, min(wy, len(theme_list)) + 5):
cursor[0] -= 1
# if cursor[0] - 1 in range(5, min(wy, len(theme_list)) + 5):
cursor[0] -= 1
elif key in [curses.KEY_ENTER, 10]:
chosen_theme = theme_list[cursor[0] - 5]
on_choice(chosen_theme)
mainloop = False
elif key in [curses.KEY_RIGHT, ord("d"), ord("в")]:
next_page = paginator.next_page()
if next_page:
if next_page := paginator.next_page():
theme_cache[pag_index] = next_page
elif key in [curses.KEY_LEFT, ord("a"), ord("ф")]:
prev_page = paginator.previous_page()
if prev_page:
if prev_page := paginator.previous_page():
theme_cache[pag_index] = prev_page
elif key in [ord("A"), ord("Ф")]:
pag_index -= 1
Expand All @@ -113,7 +111,7 @@ def init_app(stdscr, paginator_data, on_choice):

def download_app():
def on_choice(theme):
print("Downloading " + theme.name)
print(f"Downloading {theme.name}...")
save_theme(theme)

wrapper(init_app, {"betterdis": parse_better_list,
Expand All @@ -124,10 +122,8 @@ def browse_app():
name_re = r'/\* <(.+)> @ (.+) \*/'

files = []
try:
with contextlib.suppress(FileNotFoundError):
files = os.listdir(get_themes_dir())
except FileNotFoundError:
pass

all_themes_list = []
vs_themes_list = []
Expand All @@ -149,26 +145,18 @@ def browse_app():
themes_dict[theme_name] = filename

def on_choice(theme_name):
print(f"Setting {theme_name}...")
filename = themes_dict[theme_name]
set_theme(filename)

def retrieve_all(page):
if page == 1:
return all_themes_list
else:
return []
return all_themes_list if page == 1 else []

def retrieve_bd(page):
if page == 1:
return bd_themes_list
else:
return []
return bd_themes_list if page == 1 else []

def retrieve_vs(page):
if page == 1:
return vs_themes_list
else:
return []
return vs_themes_list if page == 1 else []

wrapper(init_app, {"overall": retrieve_all,
"betterdis": retrieve_bd, "vsthemes": retrieve_vs}, on_choice)
22 changes: 15 additions & 7 deletions bdtheme/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,14 @@

def scmd_init(args):
themes_dir = None
if args.dir:
themes_dir = args.dir
else:
themes_dir = os.path.join(
os.path.dirname(__file__), "..", "themes")
themes_dir = args.dir or os.path.join(os.path.dirname(__file__), "..", "themes")

themes_dir = os.path.normpath(themes_dir)
with open(os.path.normpath(os.path.join(os.path.dirname(__file__), "..", '.themedir')), 'w') as f:
f.write(themes_dir)
path = os.path.join(themes_dir, "__current.css")
path = os.path.normcase(path)
print("Initializing BeautifulDiscord at " + path)
print(f"Initializing BeautifulDiscord at {path}")

os.makedirs(themes_dir, exist_ok=True)

Expand All @@ -29,7 +26,7 @@ def scmd_browse(_):

def scmd_set(args):
if args.file:
print("Installing " + args.file + " theme.")
print(f"Installing {args.file} theme.")
set_theme(args.file)
else:
browse_app()
Expand All @@ -45,6 +42,14 @@ def scmd_revert(_):
os.system("beaudis --revert")


def scmd_cat(_):
try:
with open(os.path.join(get_themes_dir(), "__current.css"), 'r') as f:
print(f.read())
except FileNotFoundError:
print('Execute "bdtheme init" first.')


def cmd_bdtheme():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(required=True)
Expand Down Expand Up @@ -73,5 +78,8 @@ def cmd_bdtheme():
"revert", help="Remove BeautifulDiscord .css hot-reload.")
p_revert.set_defaults(func=scmd_revert)

p_cat = subparsers.add_parser("cat", help="Print out current .css theme.")
p_cat.set_defaults(func=scmd_cat)

args = parser.parse_args()
args.func(args)
26 changes: 16 additions & 10 deletions bdtheme/src/themes.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def next_page(self):
result = []
remaining = self.pagesize

while not remaining == 0:
while remaining != 0:
page_part = self._coll[:remaining]
result += page_part
self._coll = self._coll[remaining:]
Expand All @@ -62,10 +62,10 @@ def next_page(self):
if not self._coll:
self.parsepage += 1
self._coll = self.retrieve_new(self.parsepage)
if not self._coll:
if result:
break
return result
if not self._coll:
if result:
break
return result

if result:
self.pages_cache[self.page + 1] = result
Expand Down Expand Up @@ -110,7 +110,10 @@ def parse_vsthemes_list(page: int = 1) -> List[Theme]:

result = []
for el in theme_elements:
name = el.find_all("a")[1].text
try:
name = el.find_all("div")[2].find("a").text
except IndexError:
continue
img_url = "https://vsthemes.org" + el.find("img").get("src")
theme_url = el.find("a").get("href")
views, _, likes = el.find("ul", {"class": "iOptions"}).find_all("span")
Expand Down Expand Up @@ -154,10 +157,10 @@ def parse_better_list(page: int, pages: int = 10):
likes = el.find("div", {"id": "addon-likes"}
).text.strip().replace(",", "")

views = int(float(views[:-1]) * abbrevs[views[-1].lower()
]) if not views.isdigit() else int(views)
likes = int(float(likes[:-1]) * abbrevs[likes[-1].lower()
]) if not likes.isdigit() else int(likes)
views = int(views) if views.isdigit() else int(float(views[:-1]) * abbrevs[views[-1].lower()])

likes = int(likes) if likes.isdigit() else int(float(likes[:-1]) * abbrevs[likes[-1].lower()])


result.append(Theme(name, img_url=img_url,
url=theme_url, likes=likes, views=views, css=parse_better_css, source="bd"))
Expand All @@ -180,7 +183,10 @@ def parse_better_css(url: str) -> None:
def save_theme(theme: Theme) -> None:
themes_dir = get_themes_dir()
theme_css = theme.css(theme.url)
# with open(os.path.join(os.path.dirname(__file__), "fix.css"), "r") as f:
# fix_css = f.read()
with open(os.path.join(themes_dir, f"{uuid.uuid4()}.css"), "a+", encoding="utf-8") as f:
f.write(f"/* <{theme.name}> @ {theme.source} */\n")
# f.write(fix_css)
f.write("\n".join(list(filter(lambda i: not i.lower(
).startswith("//meta"), theme_css.split("\n")))))
35 changes: 19 additions & 16 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,22 @@
if sys.platform == "win32":
requirements.append("windows-curses")

setup(
name="bdtheme",
author="TheAmmiR",
license="MIT",
description="Console BeautifulDiscord theme manager",
version="1.3.1",
packages=find_packages(
exclude=["themes", "venv"]),
install_requires=requirements,
python_requires=">=3.8",
entry_points={
"console_scripts": [
"bdtheme=bdtheme.src.main:cmd_bdtheme"
]
}
)
with open("README.md", "r") as readme:
setup(
name="bdtheme",
author="TheAmmiR",
license="MIT",
description="Console BeautifulDiscord theme manager",
long_description=readme.read(),
long_description_content_type='text/markdown',
version="1.3.22",
packages=find_packages(
exclude=["themes", "venv"]),
install_requires=requirements,
python_requires=">=3.8",
entry_points={
"console_scripts": [
"bdtheme=bdtheme.src.main:cmd_bdtheme"
]
}
)

0 comments on commit 869c49f

Please sign in to comment.