Skip to content

Commit

Permalink
Fixing android build
Browse files Browse the repository at this point in the history
  • Loading branch information
bohdanbobrowski committed Sep 6, 2024
1 parent 1f22bc5 commit 866192b
Show file tree
Hide file tree
Showing 7 changed files with 137 additions and 75 deletions.
130 changes: 92 additions & 38 deletions blog2epub/blog2epub_gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
from threading import Thread
from typing import List
from urllib import parse
from urllib.error import URLError

import pkg_resources
from kivy.uix.anchorlayout import AnchorLayout # type: ignore
from kivy.uix.boxlayout import BoxLayout # type: ignore
from kivymd.uix.datatables import MDDataTable # type: ignore
Expand Down Expand Up @@ -85,15 +87,20 @@ class Tab(MDBoxLayout, MDTabsBase):

class Blog2EpubKivyWindow(MDBoxLayout):
def __init__(self, **kwargs):
global USER_DATA_DIR
super().__init__(**kwargs)
global USER_DATA_DIR
self.orientation = "vertical"

self.articles_data = []
self.blog2epub_settings = Blog2EpubSettings(path=USER_DATA_DIR)
if platform == "android":
self.blog2epub_settings.data.destination_folder = os.path.join(
os.environ["ANDROID_STORAGE"], "emulated", "0", "Download"
)
self.blog2epub = None
self.download_thread = None
self.ebook_data = None
self._generate_lock = False

self.tabs = MDTabs()
self.add_widget(self.tabs)
Expand All @@ -111,7 +118,18 @@ def __init__(self, **kwargs):
self.tabs.add_widget(self.tab_about)

self.interface = KivyInterface(self.console_output, self.console_clear)
# DEBUG:
# self.interface.print(self.blog2epub_settings.data.dict())
# self.interface.print(str(pydantic.version.version_info()))
# for name, value in os.environ.items():
# self.interface.print(f"{name}={value}")
#
# if platform == "android":
# from android.permissions import request_permissions, Permission
#
# request_permissions(
# [Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE]
# )

def _define_tab_download(self):
self.tab_download = Tab(
Expand All @@ -129,7 +147,7 @@ def _define_tab_download(self):
self.tab_download.add_widget(params_row)

self.console = TextInput(
font_size=sp(16),
font_size=sp(12),
font_name=UI_FONT_NAME,
background_color="black",
foreground_color="white",
Expand Down Expand Up @@ -227,8 +245,11 @@ def _define_tab_generate(self):
text="Generate",
font_size=sp(16),
disabled=True,
on_press=self.generate,
)
if platform == "android":
self.generate_button.bind(on_touch_down=self.generate)
else:
self.generate_button.bind(on_press=self.generate)
self._put_element_in_anchor_layout(self.generate_button, tab_layout)

self.tab_generate.add_widget(tab_layout)
Expand All @@ -238,16 +259,17 @@ def select_destination_folder(self, *args, **kwargs):
title="Select ebook destination",
)
logging.info(f"Selected path: {path}")
self.blog2epub_settings.data.destination_folder = path[0]
self.blog2epub_settings.save()
if path:
self.blog2epub_settings.data.destination_folder = path[0]
self.blog2epub_settings.save()

self.destination_button.text = (
f"Destination folder: {self.blog2epub_settings.data.destination_folder}"
)

@staticmethod
def _put_element_in_anchor_layout(element, layout):
anchor_layout = AnchorLayout(anchor_x="center", size_hint=(1, 0.04))
anchor_layout = AnchorLayout(anchor_x="center", size_hint=(1, 0.1))
anchor_layout.add_widget(element)
layout.add_widget(anchor_layout)

Expand All @@ -263,6 +285,19 @@ def _update_tab_generate(self):
else:
self.generate_button.disabled = True

def _print_packages(self):
installed_packages = pkg_resources.working_set
installed_packages_list = sorted(
["%s==%s" % (i.key, i.version) for i in installed_packages]
)
if hasattr(self, "interface"):
self.interface.clear()
for pkg in installed_packages_list:
self.interface.print(pkg)
else:
for pkg in installed_packages_list:
logging.info(pkg)

def _define_tab_about(self):
self.tab_about = Tab(
title="About",
Expand All @@ -271,13 +306,13 @@ def _define_tab_about(self):
spacing=sp(1),
padding=sp(16),
)
self.tab_about.add_widget(
Image(
source=asset_path("blog2epub.png"),
allow_stretch=True,
size_hint=(1, 0.7),
)
logo_image = Image(
source=asset_path("blog2epub.png"),
allow_stretch=True,
size_hint=(1, 0.7),
)
logo_image.bind(on_triple_tap=self._print_packages())
self.tab_about.add_widget(logo_image)
self.tab_about.add_widget(
MDLabel(
text=f"v. {Blog2Epub.version}",
Expand Down Expand Up @@ -321,7 +356,7 @@ def _get_url_row(self) -> MDBoxLayout:
hint_text="Url:",
text=self.blog2epub_settings.data.url,
helper_text="Press up/down to browse in url history",
icon_right="clipboard-flow",
# icon_right="clipboard-flow",
url_history=self.blog2epub_settings.data.history,
)
url_row.add_widget(self.url_entry)
Expand All @@ -336,7 +371,7 @@ def _get_params_row(self) -> MDBoxLayout:
text=self.blog2epub_settings.data.limit,
input_type="number",
hint_text="Limit:",
icon_right="numeric",
# icon_right="numeric",
)
self.limit_entry.bind(text=self._validate_limit)
params_row.add_widget(self.limit_entry)
Expand All @@ -345,7 +380,7 @@ def _get_params_row(self) -> MDBoxLayout:
text=self.blog2epub_settings.data.skip,
input_type="number",
hint_text="Skip:",
icon_right="numeric",
# icon_right="numeric",
)
self.skip_entry.bind(text=self._validate_skip)
params_row.add_widget(self.skip_entry)
Expand Down Expand Up @@ -426,16 +461,32 @@ def _get_articles_to_save(self) -> List[ArticleModel]:
articles_to_save.append(self.ebook_data.articles[x])
return articles_to_save

def _get_platform_name(self) -> str:
platform_name = ""
if platform == "android":
platform_name = "Android"
if platform == "win":
platform_name = "Windows"
if platform == "macos":
platform_name = "MacOS"
if platform == "linux":
platform_name = "Linux"
return platform_name

def generate(self, *args, **kwargs):
if self.ebook_data:
ebook = Book(
book_data=self.ebook_data,
configuration=self.blog2epub_settings.data,
interface=self.interface,
destination_folder=self.blog2epub_settings.data.destination_folder,
)
ebook.save(self._get_articles_to_save())
self.popup_success(ebook)
if not self._generate_lock:
self._generate_lock = self.generate_button.disabled = True
if self.ebook_data:
ebook = Book(
book_data=self.ebook_data,
configuration=self.blog2epub_settings.data,
interface=self.interface,
destination_folder=self.blog2epub_settings.data.destination_folder,
platform_name=self._get_platform_name(),
)
ebook.save(self._get_articles_to_save())
self.popup_success(ebook)
self._generate_lock = self.generate_button.disabled = False

def _update_articles_data(self, articles: List):
no = 1
Expand Down Expand Up @@ -463,22 +514,26 @@ def _get_articles_rows(self):

def download(self, *args, **kwargs):
global USER_DATA_DIR
self.url_entry.error = False
self.interface.clear()
self._disable_download_button()
self.articles_table.update_row_data(self.articles_table, [])
self.tab_select.disabled = True
self.save_settings()
self.blog2epub = Blog2Epub(
url=self._get_url(),
configuration=self.blog2epub_settings.data,
cache_folder=USER_DATA_DIR,
interface=self.interface,
)
self.download_thread = Thread(
target=self._download_ebook,
kwargs={"blog2epub": self.blog2epub},
)
self.download_thread.start()
try:
self.blog2epub = Blog2Epub(
url=self._get_url(),
configuration=self.blog2epub_settings.data,
cache_folder=USER_DATA_DIR,
interface=self.interface,
)
self.download_thread = Thread(
target=self._download_ebook,
kwargs={"blog2epub": self.blog2epub},
)
self.download_thread.start()
except BadUrlException or URLError:
self.url_entry.error = True

def cancel_download(self, *args, **kwargs):
if self.blog2epub:
Expand Down Expand Up @@ -527,7 +582,7 @@ def popup_success(self, ebook: Book):
def success(self, ebook: Book):
success_content = MDBoxLayout(orientation="vertical")
epub_cover_image_widget = MDBoxLayout(
padding=sp(20),
padding=sp(10),
size_hint=(1, 1),
)
epub_cover_image_widget.add_widget(
Expand Down Expand Up @@ -583,8 +638,7 @@ def send_ebook_via_email(inst):
title_size=sp(20),
title_font=UI_FONT_NAME,
content=success_content,
size_hint=(None, None),
size=(sp(700), sp(500)),
size_hint=(0.8, 0.8),
)
success_popup.open()

Expand Down
42 changes: 19 additions & 23 deletions blog2epub/common/book.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ def __init__(
configuration: ConfigurationModel,
interface: EmptyInterface = EmptyInterface(),
destination_folder: str = ".",
platform_name: str = "",
):
self.start: datetime.date | None = None
self.end: datetime.date | None = None
Expand Down Expand Up @@ -163,36 +164,31 @@ def _add_cover(self):
title=self.title,
subtitle=self.subtitle,
images=self.images,
platform_name=self.platform_name,
)
cover_file_name, cover_file_full_path = self.cover.generate()
self.cover_image_path = os.path.join(cover_file_name, cover_file_full_path)
cover_html = self.cover_html.replace("###FILE###", cover_file_name)
cover_html_fn = "EPUB/cover.xhtml"
content_opf_fn = "EPUB/content.opf"
with zipfile.ZipFile(self.file_full_path, "r") as zf:
content_opf = zf.read(content_opf_fn)
tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(self.file_full_path))
os.close(tmpfd)
with zipfile.ZipFile(self.file_full_path, "r") as zin:
with zipfile.ZipFile(tmpname, "w") as zout:
zout.comment = zin.comment # preserve the comment
for item in zin.infolist():
if item.filename not in [cover_html_fn, content_opf_fn]:
zout.writestr(item, zin.read(item.filename))
os.remove(self.file_full_path)
os.rename(tmpname, self.file_full_path)
with zipfile.ZipFile(self.file_full_path, "a") as zf:
zf.writestr(cover_html_fn, cover_html)
zf.write(cover_file_full_path, "EPUB/" + cover_file_name)
zf.writestr(content_opf_fn, self._upgrade_opf(content_opf, cover_file_name))
if os.path.isfile(self.file_full_path):
if hasattr(self.interface, "notify"):
self.interface.notify(
"blog2epub",
"Epub created",
self.file_full_path,
cover_file_full_path,
)
with zipfile.ZipFile(self.file_full_path, "r") as zf:
content_opf = zf.read(content_opf_fn)
tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(self.file_full_path))
os.close(tmpfd)
with zipfile.ZipFile(self.file_full_path, "r") as zin:
with zipfile.ZipFile(tmpname, "w") as zout:
zout.comment = zin.comment # preserve the comment
for item in zin.infolist():
if item.filename not in [cover_html_fn, content_opf_fn]:
zout.writestr(item, zin.read(item.filename))
os.remove(self.file_full_path)
os.rename(tmpname, self.file_full_path)
with zipfile.ZipFile(self.file_full_path, "a") as zf:
zf.writestr(cover_html_fn, cover_html)
zf.write(cover_file_full_path, "EPUB/" + cover_file_name)
zf.writestr(content_opf_fn, self._upgrade_opf(content_opf, cover_file_name))

self.interface.print(f"Epub created: {self.file_full_path}")

def _upgrade_opf(self, content_opt, cover_file_name):
Expand Down
17 changes: 12 additions & 5 deletions blog2epub/common/cover.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import os
import platform
from random import shuffle
from typing import List

from PIL import Image, ImageDraw, ImageFont
from PIL import Image, ImageDraw, ImageFont, ImageEnhance

from blog2epub.common.assets import asset_path
from blog2epub.common.globals import VERSION
Expand Down Expand Up @@ -30,6 +31,7 @@ def __init__(
title: str,
subtitle: str,
images: List[ImageModel],
platform_name: str = "",
):
"""
:param book: intance of Book class
Expand All @@ -41,6 +43,7 @@ def __init__(
self.title = title
self.subtitle = subtitle
self.images = self._check_image_size(set(i.hash for i in images))
self.platform_name = platform_name

def _check_image_size(self, image_hashes: set[str]):
verified_images = []
Expand Down Expand Up @@ -115,7 +118,7 @@ def _draw_text(self, cover_image):
)
cover_draw.text(
(15, 750),
f"Generated with blog2epub v{VERSION}\nfrom {self.blog_url}",
f"Generated with blog2epub v{VERSION} {self.platform_name}\nfrom {self.blog_url}",
(155, 155, 155),
font=generator_font,
)
Expand All @@ -128,7 +131,7 @@ def generate(self):
self.interface.print(
f"Generating cover (800px*600px) from {len(self.images)} images."
)
dark_factor = 1
dark_factor = 1.0
if len(self.images) > 0:
if len(self.images) > 1:
shuffle(self.images)
Expand All @@ -141,8 +144,9 @@ def generate(self):
thumb = self._make_thumb(
Image.open(img_file), (self.tile_size, self.tile_size)
)
thumb = thumb.point(lambda p: p * dark_factor)
dark_factor = dark_factor - 0.03
enhancer = ImageEnhance.Brightness(thumb)
thumb = enhancer.enhance(dark_factor)
dark_factor -= 0.03
cover_image.paste(thumb, (y * self.tile_size, x * self.tile_size))
i = i + 1
if i > len(self.images):
Expand All @@ -152,4 +156,7 @@ def generate(self):
cover_file_name = self.file_name + ".jpg"
cover_file_full_path = os.path.join(self.dirs.path, cover_file_name)
cover_image.save(cover_file_full_path, format="JPEG", quality=100)
self.interface.print(
f"Cover generated: {cover_file_full_path}"
)
return cover_file_name, cover_file_full_path
Loading

0 comments on commit 866192b

Please sign in to comment.