Exemple #1
0
 def __init__(self, **kwargs):
     super(ServerListsScreen, self).__init__(**kwargs)
     self.lists_loaded = BooleanProperty()
     self.lists_loaded = False
     self.app = App.get_running_app()
     self.fetch_data = None
     self.Data = ""
     self.fetch_data = ComicServerConn()
     self.base_url = self.app.base_url
     self.api_url = self.app.api_url
Exemple #2
0
    def __init__(self, reading_list=None, **kwords):
        self.reading_list = reading_list

        self.app = App.get_running_app()
        self.api_url = self.app.api_url
        self.fetch_data = ComicServerConn()
        self.num_file_done = 0
        self.comic_thumb_height = 240
        self.comic_thumb_width = 156
        id_folder = os.path.join(self.app.sync_folder, self.reading_list.slug)
        my_data_dir = Path(os.path.join(id_folder, 'data'))
        self.my_comic_dir = Path(os.path.join(id_folder, 'comics'))
        self.my_thumb_dir = Path(os.path.join(self.my_comic_dir, 'thumb'))
        if not self.my_comic_dir.is_dir():
            os.makedirs(self.my_comic_dir)
        if not self.my_thumb_dir.is_dir():
            os.makedirs(self.my_thumb_dir)
        # for item in SYNC_SETTINGS_ITEMS:
        #    val = ""
        #    tmp_defaults[key] = getattr(self, key)
        # NOTE: can be removed once DB functions added
        if not my_data_dir.is_dir():
            os.makedirs(my_data_dir)
        settings_json = os.path.join(my_data_dir, 'settings.json')
        comics_json = os.path.join(my_data_dir, 'sync_comics.json')
        self.this_test = "Test"
        self.sync_data = JsonStore(settings_json)
        self.sync_comics = JsonStore(comics_json)
        self.last_read_comic = self.get_last_comic_read()
        if self.sync_data.exists('options'):
            self.cb_only_read_state = self.sync_data.get(
                "options")["cb_only_read_state"]
            self.cb_keep_last_read_state = self.sync_data.get(
                "options")["cb_keep_last_read_state"]
            self.cb_optimize_size_state = self.sync_data.get(
                "options")["cb_optimize_size_state"]
            self.cb_limit_state = self.sync_data.get("options")[
                "cb_limit_state"]
            self.limit_num = self.sync_data.get("options")["limit_num"]
            self.sw_syn_this_active = self.sync_data.get("options")[
                'sw_syn_this_active']
        else:
            self.cb_only_read_state = 'normal'
            self.cb_keep_last_read_state = 'normal'
            self.cb_optimize_size_state = 'normal'
            self.cb_limit_state = 'normal'
            self.limit_num = 25
            self.sw_syn_this_active = False
        # end note

        self.last = 0
        self.limit = 25
        self.sync_range = int(self.last) + int(self.limit_num)
        self.api_key = self.app.config.get('General', 'api_key')
Exemple #3
0
 async def collect_readinglist_data():
     self.readinglist_name = readinglist_name
     self.app.set_screen(self.readinglist_name + " Page 1")
     self.reading_list_title = self.readinglist_name + " Page 1"
     self.readinglist_Id = readinglist_Id
     self.page_number = current_page_num
     self.mode = mode
     if self.mode == "From Server":
         self.fetch_data = ComicServerConn()
         lsit_count_url = "{}/Lists/{}/Comics/".format(
             self.api_url, readinglist_Id)
         # self.fetch_data.get_list_count(lsit_count_url,self)
         self.fetch_data.get_server_data(lsit_count_url, self)
     elif self.mode == "From DataBase":
         self.got_db_data()
Exemple #4
0
    def collect_readinglist_data(self,
                                 readinglist_name,
                                 readinglist_Id,
                                 mode="From DataBase"):
        self.readinglist_name = readinglist_name

        self.reading_list_title = self.readinglist_name + " Page 1"
        self.readinglist_Id = readinglist_Id
        self.mode = mode
        if self.mode == "From Server":
            self.fetch_data = ComicServerConn()
            lsit_count_url = f"{self.api_url}/Lists/{readinglist_Id}/Comics/"
            # self.fetch_data.get_list_count(lsit_count_url,self)
            self.fetch_data.get_server_data(lsit_count_url, self)
        elif self.mode == "From DataBase":
            self.got_db_data()
Exemple #5
0
async def save_thumb(comic_id, c_image_source):
    def got_thumb(results):
        pass

    fetch_data = ComicServerConn()
    app = App.get_running_app()
    id_folder = app.store_dir
    my_thumb_dir = Path(os.path.join(id_folder, "comic_thumbs"))

    if not my_thumb_dir.is_dir():
        os.makedirs(my_thumb_dir)
    file_name = f"{comic_id}.jpg"
    t_file = os.path.join(my_thumb_dir, file_name)
    fetch_data.get_server_file_download(
        c_image_source,
        callback=lambda req, results: got_thumb(results),
        file_path=os.path.join(my_thumb_dir, t_file),
    )
Exemple #6
0
    def __init__(self, **kwargs):
        super(BaseScreen, self).__init__(**kwargs)
        self.app = App.get_running_app()
        self.fetch_data = None
        self.Data = ""

        self.fetch_data = ComicServerConn()
        self.myLoginPop = LoginPopupContent()
        self.popup = LoginPopup(
            content=self.myLoginPop, size_hint=(None, None), size=(500, 400)
        )
        # self.update_settings()
        # self.bind(username=self.update_settings)
        # self.bind_settings()
        self.password = self.app.password
        self.api_key = self.app.api_key
        self.username = self.app.username
        self.base_url = self.app.base_url
        self.open_last_comic_startup = self.app.open_last_comic_startup
Exemple #7
0
 def __init__(self, **kwargs):
     super(ServerComicBookScreen, self).__init__(**kwargs)
     self.fetch_data = None
     self.app = App.get_running_app()
     #        self.base_url = self.app.base_url
     #        self.api_url = self.app.api_url
     self.current_page = None
     self.fetch_data = ComicServerConn()
     self.api_key = self.app.config.get("General", "api_key")
     self.popup_bkcolor = (0.5, 0.5, 0.5, 0.87)
     self.full_screen = False
     self.option_isopen = False
     self.next_dialog_open = False
     self.prev_dialog_open = False
     config_app = App.get_running_app()
     settings_data = json.loads(settings_json_screen_tap_control)
     # Window.bind(on_keyboard=self.events_program)
     for setting in settings_data:
         if setting["type"] == "options":
             tap_config = config_app.config.get(setting["section"],
                                                setting["key"])
             if tap_config == "Disabled":
                 self.ids[setting["key"]].disabled = True
Exemple #8
0
class LocalReadingListsScreen(Screen):
    reading_list_title = StringProperty()
    page_number = NumericProperty()
    max_books_page = NumericProperty()
    dynamic_ids = DictProperty({})  # declare class attribute, dynamic_ids
    sync_bool = BooleanProperty(False)
    so = BooleanProperty()
    new_readinglist = ObjectProperty()

    def __init__(self, **kwargs):
        super(LocalReadingListsScreen, self).__init__(**kwargs)
        self.app = App.get_running_app()
        self.fetch_data = None
        self.readinglist_Id = StringProperty()
        self.readinglist_name = ""
        # self.bind_to_resize()
        self.bind(width=self.my_width_callback)
        self.m_grid = ""
        self.main_stack = ""
        self.prev_button = ""
        self.next_button = ""
        self.base_url = self.app.base_url
        self.api_url = self.app.api_url
        self.api_key = self.app.config.get("General", "api_key")
        self.list_count = ""
        self.paginator_obj = ObjectProperty()
        self.current_page = ObjectProperty()
        self.list_loaded = BooleanProperty()
        self.page_number = 1
        self.list_loaded = False
        self.comic_thumb_height = 240
        self.comic_thumb_width = 156
        self.file_download = True
        self.num_file_done = 0
        self.max_books_page = self.app.max_books_page

    def callback_for_menu_items(self, *args):
        pass

    def setup_screen(self):
        self.api_key = self.app.config.get("General", "api_key")
        self.api_url = self.app.api_url
        self.main_stack = self.ids["main_stack"]
        self.m_grid = self.ids["main_grid"]
        self.prev_button = self.ids["prev_button"]
        self.next_button = self.ids["next_button"]

    def on_pre_enter(self, *args):
        self.app.show_action_bar()

        return super().on_pre_enter(*args)

    def on_leave(self, *args):
        self.app.list_previous_screens.append(self.name)
        return super().on_leave(*args)

    def on_enter(self, *args):
        self.app.set_screen(f"{self.readinglist_name}-(Local) Page 1")

    def my_width_callback(self, obj, value):
        for key, val in self.ids.items():
            if key == "main_grid":
                c = val
                c.cols = (Window.width - 10) // self.comic_thumb_width

    def page_turn(self, c_id, new_UserLastPageRead):
        grid = self.m_grid
        for child in grid.children:
            if child.comic_obj.Id == c_id:
                if new_UserLastPageRead == 0:
                    child.percent_read = 0
                else:
                    child.percent_read = round(
                        new_UserLastPageRead /
                        (child.comic_obj.PageCount - 1) * 100)
                child.page_count_text = f"{child.percent_read}%"

    def collect_readinglist_data(self,
                                 readinglist_name,
                                 readinglist_Id,
                                 mode="From DataBase"):
        self.readinglist_name = readinglist_name

        self.reading_list_title = self.readinglist_name + " Page 1"
        self.readinglist_Id = readinglist_Id
        self.mode = mode
        if self.mode == "From Server":
            self.fetch_data = ComicServerConn()
            lsit_count_url = f"{self.api_url}/Lists/{readinglist_Id}/Comics/"
            # self.fetch_data.get_list_count(lsit_count_url,self)
            self.fetch_data.get_server_data(lsit_count_url, self)
        elif self.mode == "From DataBase":
            self.got_db_data()

    def get_page(self, instance):
        page_num = instance.page_num
        self.app.set_screen(self.readinglist_name + f" Page {page_num}")
        self.reading_list_title = self.readinglist_name + f" Page {page_num}"
        page = self.paginator_obj.page(page_num)
        self.current_page = page
        if page.has_next():
            self.next_button.opacity = 1
            self.next_button.disabled = False
            self.next_button.page_num = page.next_page_number()
        else:
            self.next_button.opacity = 0
            self.next_button.disabled = True
            self.next_button.page_num = ""
        if page.has_previous():
            self.prev_button.opacity = 1
            self.prev_button.disabled = False
            self.prev_button.page_num = page.previous_page_number()
        else:
            self.prev_button.opacity = 0
            self.prev_button.disabled = True
            self.prev_button.page_num = ""
        self.build_page(page.object_list)

        self.ids.main_scroll.scroll_to(self.ids.main_grid.children[0],
                                       padding=10,
                                       animate=True)

    def build_page(self, object_lsit):
        grid = self.m_grid
        grid.clear_widgets()
        for comic in object_lsit:
            if comic.is_sync:
                c = ReadingListComicImage(comic_obj=comic)
                c.lines = 2
                c.readinglist_obj = self.new_readinglist
                c.paginator_obj = self.paginator_obj
                y = self.comic_thumb_height
                if self.mode == "From Server":
                    part_url = f"/Comics/{comic.Id}/Pages/0?"
                    part_api = f"&apiKey={self.api_key}&height={round(dp(y))}"
                    c_image_source = f"{self.api_url}{part_url}{part_api}"
                else:
                    import os

                    id_folder = os.path.join(self.app.sync_folder,
                                             self.new_readinglist.slug)
                    my_thumb_dir = os.path.join(id_folder, "thumb")
                    thumb_name = f"{comic.Id}.jpg"
                    t_file = os.path.join(my_thumb_dir, thumb_name)
                    c_image_source = t_file
                c.source = c_image_source
                c.PageCount = comic.PageCount
                c.pag_pagenum = self.current_page.number
                c.view_mode = "Sync"
                grid.add_widget(c)
                grid.cols = (Window.width - 10) // self.comic_thumb_width
                self.dynamic_ids[id] = c
            else:
                pass
        self.ids.page_count.text = f"Page #\n{self.current_page.number} of \
            {self.paginator_obj.num_pages()}"

    def got_db_data(self):
        """
        used if rl data is already stored in db.
        """
        def _do_readinglist():
            self.new_readinglist = ComicReadingList(
                name=self.readinglist_name,
                data="db_data",
                slug=self.readinglist_Id,
                mode="local_file",
            )
            self.so = self.new_readinglist.sw_syn_this_active
            self.setup_options()
            new_readinglist_reversed = self.new_readinglist.comics
            self.paginator_obj = Paginator(new_readinglist_reversed,
                                           self.max_books_page)
            page = self.paginator_obj.page(self.page_number)
            self.current_page = page
            if page.has_next():
                self.next_button.opacity = 1
                self.next_button.disabled = False
                self.next_button.page_num = page.next_page_number()
            else:
                self.next_button.opacity = 0
                self.next_button.disabled = True
                self.next_button.page_num = ""
            if page.has_previous():
                self.prev_button.opacity = 1
                self.prev_button.disabled = False
                self.prev_button.page_num = page.previous_page_number()
            else:
                self.prev_button.opacity = 0
                self.prev_button.disabled = True
                self.prev_button.page_num = ""
            self.build_page(page.object_list)
            self.list_loaded = True

        Clock.schedule_once(lambda dt: _do_readinglist(), 0)

        # self.bind(new_readinglist=self.setter('sync_bool'))
        # self.max_books_page = int(self.app.config.get(
        #    'General', 'max_books_page'))

    def got_json(self, req, results):
        self.new_readinglist = ComicReadingList(name=self.readinglist_name,
                                                data=results,
                                                slug=self.readinglist_Id)
        for item in self.new_readinglist.comic_json:
            comic_index = self.new_readinglist.comic_json.index(item)
            new_comic = ComicBook(
                item,
                readlist_obj=self.new_readinglist,
                comic_index=comic_index,
            )
            self.new_readinglist.add_comic(new_comic)
        self.setup_options()
        new_readinglist_reversed = self.new_readinglist.comics[::-1]
        self.paginator_obj = Paginator(new_readinglist_reversed,
                                       self.max_books_page)
        page = self.paginator_obj.page(self.page_number)
        self.current_page = page
        if page.has_next():
            self.next_button.opacity = 1
            self.next_button.disabled = False
            self.next_button.page_num = page.next_page_number()
        else:
            self.next_button.opacity = 0
            self.next_button.disabled = True
            self.next_button.page_num = ""
        if page.has_previous():
            self.prev_button.opacity = 1
            self.prev_button.disabled = False
            self.prev_button.page_num = page.previous_page_number()
        else:
            self.prev_button.opacity = 0
            self.prev_button.disabled = True
            self.prev_button.page_num = ""
        self.build_page(page.object_list)
        self.list_loaded = True

    def setup_options(self):
        s_r_l = self.new_readinglist
        self.sync_options = SyncOptionsPopup(
            size_hint=(0.76, 0.76),
            cb_limit_active=s_r_l.cb_limit_active,
            limit_num_text=str(s_r_l.limit_num),
            cb_only_read_active=s_r_l.cb_only_read_active,
            cb_purge_active=s_r_l.cb_purge_active,
            cb_optimize_size_active=s_r_l.cb_optimize_size_active,
            sw_syn_this_active=bool(s_r_l.sw_syn_this_active),
        )
        self.sync_options.ids.limit_num.bind(
            on_text_validate=self.sync_options.check_input,
            focus=self.sync_options.check_input,
        )

        self.sync_options.title = self.new_readinglist.name

    def open_sync_options(self):
        if self.sync_options.ids.sw_syn_this.active is True:
            self.sync_options.ids.syn_on_off_label.text = f""
            self.sync_options.ids.syn_on_off_label.theme_text_color = "Primary"
        self.sync_options.open()

    def sync_readinglist(self):
        if self.sync_options.ids.sw_syn_this.active is False:
            self.sync_options.ids.syn_on_off_label.text = f"Sync Not Turned On"
            self.open_sync_options()
        elif self.sync_options.ids.sw_syn_this.active is True:
            toast(f"Starting sync of {self.new_readinglist.name}")
            self.new_readinglist.do_sync()
Exemple #9
0
    def build_last_comic_section(  # noqa
        self, readinglist_name, readinglist_Id
    ):
        def __got_readlist_data(results):
            async def __load_readinglist_scree(paginator_obj=None):
                if tmp_last_comic_type == "local_file":
                    x_readinglists_screen = self.app.manager.get_screen(
                        "local_readinglists_screen"
                    )
                else:
                    x_readinglists_screen = self.app.manager.get_screen(
                        "server_readinglists_screen"
                    )
                x_readinglists_screen.list_loaded = False
                x_readinglists_screen.setup_screen()
                x_readinglists_screen.page_number = tmp_last_pag_pagnum
                x_readinglists_screen.loading_done = False
                self.call_collect(
                    set_mode,
                    x_readinglists_screen,
                    readinglist_name,
                    readinglist_Id,
                )

            tmp_last_comic_id = self.app.config.get("Saved", "last_comic_id")
            tmp_last_comic_type = self.app.config.get(
                "Saved", "last_comic_type"
            )
            tmp_last_pag_pagnum = int(
                self.app.config.get("Saved", "last_pag_pagnum")
            )
            if tmp_last_comic_id == "":
                return
            else:
                query = ReadingList.select().where(
                    ReadingList.slug == readinglist_Id
                )
                if query.exists():
                    Logger.info(f"{readinglist_name} already in Database")
                    set_mode = "From DataBase"
                    mode = ""
                    if tmp_last_comic_type == "local_file":
                        mode = "local_file"
                    self.new_readinglist = ComicReadingList(
                        name=self.readinglist_name,
                        data="db_data",
                        slug=self.readinglist_Id,
                        mode=mode,
                    )

                    # self.new_readinglist.comics_write()
                    max_books_page = int(
                        self.app.config.get("General", "max_books_page")
                    )
                    new_readinglist_reversed = self.new_readinglist.comics
                    paginator_obj = Paginator(
                        new_readinglist_reversed, max_books_page
                    )
                    for x in range(1, paginator_obj.num_pages()):
                        this_page = paginator_obj.page(x)
                        for comic in this_page.object_list:
                            if tmp_last_comic_id == comic.Id:
                                tmp_last_pag_pagnum = this_page.number
                    asynckivy.start(
                        __load_readinglist_scree(paginator_obj=paginator_obj)
                    )
                    if (
                        self.open_last_comic_startup == 1
                        and not self.app.app_started
                    ):
                        for comic in self.new_readinglist.comics:
                            if comic.slug == tmp_last_comic_id:

                                self.open_comic(
                                    tmp_last_comic_id=tmp_last_comic_id,
                                    tmp_last_comic_type=tmp_last_comic_type,
                                    paginator_obj=paginator_obj,
                                    comic=comic,
                                    tmp_last_pag_pagnum=tmp_last_pag_pagnum,
                                )
                    else:
                        grid = self.ids["main_grid"]
                        grid.cols = 1
                        grid.clear_widgets()
                        for comic in self.new_readinglist.comics:
                            if comic.slug == tmp_last_comic_id:
                                c = ReadingListComicImage(comic_obj=comic)
                                c.readinglist_obj = self.new_readinglist
                                c.paginator_obj = paginator_obj
                                x = self.app.comic_thumb_width
                                y = self.app.comic_thumb_height
                                if tmp_last_comic_type == "local_file":
                                    if comic.local_file == "":
                                        return
                                    import os

                                    id_folder = os.path.join(
                                        self.app.sync_folder,
                                        self.new_readinglist.slug,
                                    )
                                    my_thumb_dir = os.path.join(
                                        id_folder, "thumb"
                                    )
                                    thumb_name = f"{comic.Id}.jpg"
                                    t_file = os.path.join(
                                        my_thumb_dir, thumb_name
                                    )
                                    c_image_source = t_file
                                else:
                                    round_y = round(dp(y))
                                    part_url = f"/Comics/{comic.Id}/Pages/0?"
                                    part_api = "&apiKey={}&height={}".format(
                                        self.api_key, round_y
                                    )
                                    c_image_source = "{}{}{}".format(
                                        self.app.api_url, part_url, part_api
                                    )
                                c.source = c_image_source
                                c.PageCount = comic.PageCount
                                c.pag_pagenum = tmp_last_pag_pagnum
                                if tmp_last_comic_type == "local_file":
                                    c.view_mode = "Sync"
                                strtxt = f"{comic.Series} #{comic.Number}"
                                tmp_color = get_hex_from_color((1, 1, 1, 1))
                                c.text = f"[color={tmp_color}]{strtxt}[/color]"
                                grid.add_widget(c)
                                tmp_txt = f"Last Comic Load from \
                                        {self.new_readinglist.name}"
                                self.ids.last_comic_label.text = tmp_txt
                else:
                    Logger.info(
                        f"{readinglist_name} \
                            not in Database This could be a problems"
                    )

                    set_mode = "From Server"
                # set_mode = 'From Server'

        self.readinglist_name = readinglist_name
        # self.app.set_screen(self.readinglist_name + ' Page 1')
        self.reading_list_title = self.readinglist_name + " Page 1"
        self.readinglist_Id = readinglist_Id

        # self.fetch_data.get_list_count(lsit_count_url,self)
        tmp_last_comic_type = self.app.config.get("Saved", "last_comic_type")
        if tmp_last_comic_type == "local_file":
            Clock.schedule_once(lambda dt: __got_readlist_data("none"), 0.15)
        else:
            self.fetch_data = ComicServerConn()
            lsit_count_url = (
                f"{self.app.api_url}/Lists/{readinglist_Id}/Comics/"
            )  # noqa
            self.fetch_data.get_server_data_callback(
                lsit_count_url,
                callback=lambda req, results: __got_readlist_data(results),
            )
Exemple #10
0
    def do_sync(self):
        def _syncrun_callback(*args):
            pass

        app = App.get_running_app()
        if app.sync_is_running is True:
            self.please_wait_dialog = MDDialog(
                title="Sync Already in Progress",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                text=f"Please wait till current Sync is done",
                events_callback=_syncrun_callback,
            )
            self.please_wait_dialog.open()
            return
        self.num_file_done = 0
        sync_range = 0
        self.fetch_data = ComicServerConn()
        rl_db = ReadingList.get(ReadingList.slug == self.slug)

        end_last_sync_num = rl_db.end_last_sync_num
        if end_last_sync_num != 0:
            end_last_sync_num = end_last_sync_num - 1
        comicindex_db = ComicIndex.get(ComicIndex.readinglist == self.slug)
        last_read_comic_db = self.db.comics.where(
            (Comic.UserLastPageRead == Comic.PageCount - 1)
            & (Comic.PageCount > 1)
        ).order_by(comicindex_db.index)
        if len(last_read_comic_db) > 1:
            last_read_index = ComicIndex.get(
                ComicIndex.comic == last_read_comic_db[-1].Id,
                ComicIndex.readinglist == self.slug,
            ).index
        elif len(last_read_comic_db) != 0:
            last_read_index = ComicIndex.get(
                ComicIndex.comic == last_read_comic_db[0].Id,
                ComicIndex.readinglist == self.slug,
            ).index
        else:
            last_read_index = 0
        if self.cb_limit_active:
            if self.cb_only_read_active:
                list_comics = self.db.comics.where(
                    ~(Comic.UserLastPageRead == Comic.PageCount - 1)
                    & (Comic.PageCount > 1)
                    & (Comic.been_sync)
                    != True
                ).order_by(
                    comicindex_db.index
                )  # noqa: E712
                if last_read_index < end_last_sync_num:
                    sync_range = int(self.limit_num)
                    tmp_comic_list = list_comics[0:int(sync_range)]
                else:
                    sync_range = int(end_last_sync_num) + int(self.limit_num)
                    tmp_comic_list = list_comics[end_last_sync_num:int(sync_range)]
                purge_list = self.db.comics.where(
                    (Comic.UserLastPageRead == Comic.PageCount - 1)
                    & (Comic.PageCount > 1)
                    & (Comic.is_sync == True)
                ).order_by(
                    comicindex_db.index
                )  # noqa: E712
            else:
                list_comics = (
                    Comic.select()
                    .where(
                        (Comic.is_sync == False) & (Comic.been_sync == False)
                    )
                    .order_by(comicindex_db.index)
                )  # noqa: E712,E501
                sync_range = int(self.limit_num)
                tmp_comic_list = list_comics[0:int(sync_range)]
                purge_list = self.db.comics.where(
                    Comic.is_sync == True
                ).order_by(
                    comicindex_db.index
                )  # noqa: E712
        else:
            sync_range = int(len(self.comics))
            # rl_db.end_last_sync_num = new_end_last_sync_num
            # rl_db.save()
            if self.cb_only_read_active:
                list_comics = self.db.comics.where(
                    ~(Comic.UserLastPageRead == Comic.PageCount - 1)
                    & (Comic.PageCount > 1)
                ).order_by(
                    comicindex_db.index
                )  # noqa: E712
                tmp_comic_list = list_comics[0:int(sync_range)]
            else:
                list_comics = self.db.comics.where(
                    (Comic.is_sync == False) & (Comic.been_sync == False)
                ).order_by(
                    comicindex_db.index
                )  # noqa: E712,E501
                tmp_comic_list = list_comics
        db_item = ReadingList.get(ReadingList.slug == self.slug)
        for key in READINGLIST_SETTINGS_KEYS:
            v = getattr(db_item, key)
            globals()["%s" % key] = v
        app = App.get_running_app()
        id_folder = os.path.join(app.sync_folder, self.slug)
        my_comic_dir = Path(os.path.join(id_folder, "comics"))
        if os.path.isdir(my_comic_dir):
            print(f"{get_size(my_comic_dir)/1000000} MB")
        sync_comic_list = []
        for comic in tmp_comic_list:
            if comic.is_sync is False:
                sync_comic_list.append(comic)
        if self.cb_purge_active:
            for item in purge_list:
                os.remove(item.local_file)
                db_comic = Comic.get(Comic.Id == item.Id)
                db_comic.is_sync = False
                db_comic.local_file = ""
                db_comic.save()
                server_readinglists_screen = app.manager.get_screen(
                    "server_readinglists_screen"
                )
                server_readinglists_screen.file_sync_update(item.Id, False)
        self.sync_readinglist(comic_list=sync_comic_list)
Exemple #11
0
    def callback_for_menu_items(self, *args):
        def __updated_progress(results, state):
            Logger.info(results)
            if state == "Unread":
                # self.img_color = (1, 1, 1, 1)
                self.is_read = False
                self.page_count_text = "0%"
                self.comic_obj.UserLastPage = 0
                self.comic_obj.UserCurrentPage = 0
                self.comic_obj.update()
            elif state == "Read":
                # self.img_color = (.89, .15, .21, 5)
                self.is_read = True
                self.page_count_text = "100%"
                the_page = self.comic_obj.PageCount
                self.comic_obj.UserLastPage = the_page
                self.comic_obj.UserCurrentPage = the_page

        action = args[0].replace("[color=#000000]", "").replace("[/color]", "")
        if action == "Open This Comic":
            self.open_comic()
        elif action == "Mark as Read":
            try:
                db_comic = Comic.get(Comic.Id == self.comic_obj.Id)
                if db_comic:
                    db_comic.UserLastPageRead = self.comic_obj.PageCount - 1
                    db_comic.UserCurrentPage = self.comic_obj.PageCount - 1
                    db_comic.save()
                    self.comic_obj.UserLastPageRead = (
                        self.comic_obj.PageCount - 1)  # noqa
                    self.comic_obj.UserCurrentPage = (
                        self.comic_obj.PageCount - 1)
                    server_readinglists_screen = self.app.manager.get_screen(
                        "server_readinglists_screen")
                    for item in server_readinglists_screen.new_readinglist.comics:
                        if item.Id == self.comic_obj.Id:
                            item.UserCurrentPage = self.comic_obj.PageCount - 1
                            item.UserLastPageRead = self.comic_obj.PageCount - 1
            except (ProgrammingError, OperationalError, DataError) as e:
                Logger.error(f"Mar as unRead DB: {e}")
            server_con = ComicServerConn()
            update_url = "{}/Comics/{}/Progress".format(
                self.app.api_url, self.comic_obj.Id)
            server_con.update_progress(
                update_url,
                self.comic_obj.PageCount - 1,
                callback=lambda req, results: __updated_progress(
                    results, "Read"),
            )
        elif action == "Mark as UnRead":
            try:
                db_comic = Comic.get(Comic.Id == self.comic_obj.Id)
                if db_comic:
                    db_comic.UserLastPageRead = 0
                    db_comic.UserCurrentPage = 0
                    db_comic.save()
                    self.comic_obj.UserLastPageRead = 0
                    self.comic_obj.UserCurrentPage = 0
                    server_readinglists_screen = self.app.manager.get_screen(
                        "server_readinglists_screen")
                    for item in server_readinglists_screen.new_readinglist.comics:
                        if item.Id == self.comic_obj.Id:
                            item.UserCurrentPage = 0
                            item.UserLastPageRead = 0
            except (ProgrammingError, OperationalError, DataError) as e:
                Logger.error(f"Mark as unRead DB: {e}")
            server_con = ComicServerConn()
            update_url = "{}/Comics/{}/Mark_Unread".format(
                self.app.api_url, self.comic_obj.Id)
            server_con.update_progress(
                update_url,
                0,
                callback=lambda req, results: __updated_progress(
                    results, "Unread"),
            )
Exemple #12
0
class ComicReadingList(EventDispatcher):

    # ids = DictProperty({})
    name = StringProperty()
    comics = ListProperty()
    data = DictProperty()
    slug = StringProperty()
    comic_db = ObjectProperty()
    comic_json = ListProperty()
    cb_only_read_active = BooleanProperty(False)
    cb_only_read_active = BooleanProperty(False)
    cb_purge_active = BooleanProperty(False)
    cb_optimize_size_active = BooleanProperty(False)
    cb_limit_active = BooleanProperty(False)
    limit_num = NumericProperty(25)
    sw_syn_this_active = BooleanProperty(False)
    comic_db_in = BooleanProperty(False)
    db = ObjectProperty()
    comics_loaded = ObjectProperty(False)
    last_comic_read = NumericProperty()
    start_last_sync_num = NumericProperty(0)
    end_last_sync_num = NumericProperty(0)
    totalCount = NumericProperty()
    pickled_data = ObjectProperty()
    sync_list = ListProperty()

    def __init__(self, name="", data=None, slug="", mode="Server"):
        self.slug = slug
        self.name = name
        self.event = None
        if data != "db_data":

            self.pickled_data = pickle.dumps(data, -1)
            self.data = pickle.loads(self.pickled_data)
            self.comic_json = self.data["items"]
            if mode != "FileOpen":
                if name == "Single_FileLoad":
                    self.totalCount = 0
                else:
                    self.totalCount = self.data["totalCount"]
        if mode != "FileOpen":
            self.get_or_create_db_item(mode=mode)

    def add_comic(self, comic, index=0):
        """
            Add Single comic book to this colection
        """
        self.comics.insert(0, comic)

    def get_or_create_db_item(self, mode):
        tmp_defaults = {}
        try:
            for key in READINGLIST_DB_KEYS:
                if key == "data":
                    new_dict = {k: self.data[k] for k in self.data.keys()}
                    tmp_defaults["data"] = new_dict
                else:
                    tmp_defaults[key] = getattr(self, key)
            db_item, created = ReadingList.get_or_create(
                slug=self.slug, defaults=tmp_defaults
            )
            self.db = db_item
            if db_item:
                for key in READINGLIST_DB_KEYS:
                    setattr(self, key, getattr(db_item, key))
                if created is True:
                    len_dbcomics = len(db_item.comics)
                    if (
                        len_dbcomics == len(self.comic_json)
                        and len(self.comic_json) != 0
                    ):
                        self.comic_db_in = True
                        self.comics = self.db.comics.order_by(
                            -Comic.comic_index.index
                        )
                else:
                    self.comic_db_in = True
                    comicindex_db = ComicIndex.get(
                        ComicIndex.readinglist == self.slug
                    )
                    if mode == "local_file":
                        list_comics = self.db.comics.where(
                            Comic.is_sync == True, Comic.local_file != ""
                        ).order_by(  # noqa
                            comicindex_db.index
                        )
                        print(f"len:{len(list_comics)}")
                    else:
                        list_comics = self.db.comics.order_by(
                            comicindex_db.index
                        )
                    for comic in list_comics:
                        new_comic = ComicBook(
                            comic_Id=comic.Id,
                            readlist_obj=self,
                            mode="db_data",
                        )
                        self.comics.append(new_comic)
                    self.comics_loaded = True
        except peewee.OperationalError:
            Logger.critical(
                "Somthing happened in get_or_create of readinglist"
            )

    def save_settings(self, *args, **kwargs):
        try:
            rl = ReadingList.get(ReadingList.slug == self.slug)
            for key in READINGLIST_SETTINGS_KEYS:
                setattr(rl, key, kwargs[key])
                setattr(self, key, kwargs[key])
            rl.save()
        except peewee.OperationalError:
            pass

    def do_db_refresh(self, screen=None):
        def __finish_toast(dt):
            app = App.get_running_app()
            screen = app.manager.get_screen("server_readinglists_screen")
            screen.refresh_callback()
            toast("DataBase Refresh Complete")

        def __got_readlist_data(results):
            def __updated_progress(results):
                pass

            the_keys = [
                "Id",
                "Series",
                "Number",
                "Volume",
                "Year",
                "Month",
                "UserCurrentPage",
                "UserLastPageRead",
                "PageCount",
                "Summary",
                "FilePath",
            ]
            for server_comic in results["items"]:
                for db_comic in self.comics:
                    if db_comic.Id == server_comic["Id"]:
                        for key in the_keys:
                            if getattr(db_comic, key) != server_comic[key]:
                                if key in (
                                    "UserCurrentPage",
                                    "UserLastPageRead",
                                ) and (db_comic.is_sync):
                                    if (
                                        db_comic.UserLastPageRead
                                        > server_comic["UserLastPageRead"]
                                    ) or (
                                        db_comic.UserCurrentPage
                                        > server_comic["UserCurrentPage"]
                                    ):
                                        if (
                                            db_comic.UserCurrentPage
                                            > db_comic.UserLastPageRead
                                        ):
                                            current_page = (
                                                db_comic.UserCurrentPage
                                            )  # noqa
                                        else:
                                            current_page = (
                                                db_comic.UserLastPageRead
                                            )  # noqa
                                        update_url = "{}/Comics/{}/Progress".format(
                                            api_url, db_comic.Id
                                        )
                                        self.fetch_data.update_progress(
                                            update_url,
                                            current_page,
                                            callback=lambda req, results: __updated_progress(
                                                results
                                            ),
                                        )
                                    else:
                                        x_str = db_comic.__str__
                                        Logger.info(
                                            "Updating DB Record for {} of {}".format(
                                                key, x_str
                                            )
                                        )
                                        toast(
                                            "Updating DB Record for {} of {}".format(
                                                key, x_str
                                            )
                                        )
                                        db_item = Comic.get(
                                            Comic.Id == db_comic.Id
                                        )
                                        if db_item:
                                            setattr(
                                                db_item, key, server_comic[key]
                                            )
                                            db_item.save()
                                            setattr(self, key, db_item)

            Clock.schedule_once(__finish_toast, 3)

        self.fetch_data = ComicServerConn()
        app = App.get_running_app()
        api_url = app.api_url
        server_url = f"{api_url}/Lists/{self.slug}/Comics/"

        self.fetch_data.get_server_data_callback(
            server_url,
            callback=lambda req, results: __got_readlist_data(results),
        )

    def get_last_comic_read(self):
        last_read_comic = 0
        for comic in self.comics:
            if (
                comic.UserLastPageRead == comic.PageCount - 1
                and comic.PageCount > 1
            ):
                last_read_comic = self.comics.index(comic)
        return last_read_comic

    def do_sync(self):
        def _syncrun_callback(*args):
            pass

        app = App.get_running_app()
        if app.sync_is_running is True:
            self.please_wait_dialog = MDDialog(
                title="Sync Already in Progress",
                size_hint=(0.8, 0.4),
                text_button_ok="Ok",
                text=f"Please wait till current Sync is done",
                events_callback=_syncrun_callback,
            )
            self.please_wait_dialog.open()
            return
        self.num_file_done = 0
        sync_range = 0
        self.fetch_data = ComicServerConn()
        rl_db = ReadingList.get(ReadingList.slug == self.slug)

        end_last_sync_num = rl_db.end_last_sync_num
        if end_last_sync_num != 0:
            end_last_sync_num = end_last_sync_num - 1
        comicindex_db = ComicIndex.get(ComicIndex.readinglist == self.slug)
        last_read_comic_db = self.db.comics.where(
            (Comic.UserLastPageRead == Comic.PageCount - 1)
            & (Comic.PageCount > 1)
        ).order_by(comicindex_db.index)
        if len(last_read_comic_db) > 1:
            last_read_index = ComicIndex.get(
                ComicIndex.comic == last_read_comic_db[-1].Id,
                ComicIndex.readinglist == self.slug,
            ).index
        elif len(last_read_comic_db) != 0:
            last_read_index = ComicIndex.get(
                ComicIndex.comic == last_read_comic_db[0].Id,
                ComicIndex.readinglist == self.slug,
            ).index
        else:
            last_read_index = 0
        if self.cb_limit_active:
            if self.cb_only_read_active:
                list_comics = self.db.comics.where(
                    ~(Comic.UserLastPageRead == Comic.PageCount - 1)
                    & (Comic.PageCount > 1)
                    & (Comic.been_sync)
                    != True
                ).order_by(
                    comicindex_db.index
                )  # noqa: E712
                if last_read_index < end_last_sync_num:
                    sync_range = int(self.limit_num)
                    tmp_comic_list = list_comics[0:int(sync_range)]
                else:
                    sync_range = int(end_last_sync_num) + int(self.limit_num)
                    tmp_comic_list = list_comics[end_last_sync_num:int(sync_range)]
                purge_list = self.db.comics.where(
                    (Comic.UserLastPageRead == Comic.PageCount - 1)
                    & (Comic.PageCount > 1)
                    & (Comic.is_sync == True)
                ).order_by(
                    comicindex_db.index
                )  # noqa: E712
            else:
                list_comics = (
                    Comic.select()
                    .where(
                        (Comic.is_sync == False) & (Comic.been_sync == False)
                    )
                    .order_by(comicindex_db.index)
                )  # noqa: E712,E501
                sync_range = int(self.limit_num)
                tmp_comic_list = list_comics[0:int(sync_range)]
                purge_list = self.db.comics.where(
                    Comic.is_sync == True
                ).order_by(
                    comicindex_db.index
                )  # noqa: E712
        else:
            sync_range = int(len(self.comics))
            # rl_db.end_last_sync_num = new_end_last_sync_num
            # rl_db.save()
            if self.cb_only_read_active:
                list_comics = self.db.comics.where(
                    ~(Comic.UserLastPageRead == Comic.PageCount - 1)
                    & (Comic.PageCount > 1)
                ).order_by(
                    comicindex_db.index
                )  # noqa: E712
                tmp_comic_list = list_comics[0:int(sync_range)]
            else:
                list_comics = self.db.comics.where(
                    (Comic.is_sync == False) & (Comic.been_sync == False)
                ).order_by(
                    comicindex_db.index
                )  # noqa: E712,E501
                tmp_comic_list = list_comics
        db_item = ReadingList.get(ReadingList.slug == self.slug)
        for key in READINGLIST_SETTINGS_KEYS:
            v = getattr(db_item, key)
            globals()["%s" % key] = v
        app = App.get_running_app()
        id_folder = os.path.join(app.sync_folder, self.slug)
        my_comic_dir = Path(os.path.join(id_folder, "comics"))
        if os.path.isdir(my_comic_dir):
            print(f"{get_size(my_comic_dir)/1000000} MB")
        sync_comic_list = []
        for comic in tmp_comic_list:
            if comic.is_sync is False:
                sync_comic_list.append(comic)
        if self.cb_purge_active:
            for item in purge_list:
                os.remove(item.local_file)
                db_comic = Comic.get(Comic.Id == item.Id)
                db_comic.is_sync = False
                db_comic.local_file = ""
                db_comic.save()
                server_readinglists_screen = app.manager.get_screen(
                    "server_readinglists_screen"
                )
                server_readinglists_screen.file_sync_update(item.Id, False)
        self.sync_readinglist(comic_list=sync_comic_list)

    def get_server_file_download(self, req_url, callback, file_path):
        def is_finished(dt):
            if req.is_finished is True:
                app = App.get_running_app()
                screen = app.manager.get_screen("server_readinglists_screen")
                screen.ids.sync_button.enabled = True
                Clock.schedule_once(self.download_file)
            else:
                Clock.schedule_once(is_finished, 0.25)

        app = App.get_running_app()
        username = app.config.get("General", "username")
        api_key = app.config.get("General", "api_key")
        str_cookie = f"API_apiKey={api_key}; BCR_username={username}"
        head = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Cookie": str_cookie,
        }

        req = UrlRequest(
            req_url, req_headers=head, on_success=callback, file_path=file_path
        )
        app = App.get_running_app()
        screen = app.manager.get_screen("server_readinglists_screen")
        if len(self.sync_list) != 0:
            screen.ids.sync_status_lbl.text = (
                f"Sync is Running Left in Que: {len(self.sync_list)}"
            )
            Clock.schedule_once(is_finished, 0.25)
        else:
            toast("Reading List has been Synced, Refreshing Screen")
            screen.ids.sync_status_lbl.text = ""
            screen.ids.sync_button.enabled = True
            app.sync_is_running = False
            # screen.refresh_callback()

    def got_file(self, comic_obj, comic_file="", *args, **kwargs):
        def file_finished_toast(dt):
            toast(f"{os.path.basename(comic_file)} Synced")
        self.num_file_done += 1
        Clock.schedule_once(file_finished_toast)
        self.file_download = True
        db_comic = Comic.get(Comic.Id == comic_obj.Id)
        db_comic.is_sync = True
        db_comic.save()
        db_comic = Comic.get(Comic.Id == comic_obj.Id)
        db_comic.local_file = comic_file
        db_comic.been_sync = True
        db_comic.save()
        rl_db = ReadingList.get(ReadingList.slug == self.slug)
        rl_db.end_last_sync_num += 1
        rl_db.save()
        app = App.get_running_app()
        server_readinglists_screen = app.manager.get_screen(
            "server_readinglists_screen"
        )
        server_readinglists_screen.file_sync_update(comic_obj.Id, True)

    def download_file(self, dt):
        def got_thumb(results):
            pass

        app = App.get_running_app()
        screen = app.manager.get_screen("server_readinglists_screen")
        screen.ids.sync_button.enabled = False
        if len(self.sync_list) == 0:
            toast("Reading List has been Synced, Refreshing Screen")
            app = App.get_running_app()
            screen = app.manager.get_screen("server_readinglists_screen")
            screen.ids.sync_status_lbl.text = ""
            screen.ids.sync_button.enabled = True
            app.sync_is_running = False
            # screen.refresh_callback()
            return
        comic = self.sync_list.pop(0)
        self.file_download = False
        file_name = ntpath.basename(comic.FilePath)
        y = 240
        part_url = f"/Comics/{comic.Id}/Pages/0?"
        app = App.get_running_app()
        part_api = f"&apiKey={app.api_key}&height={round(dp(y))}"
        thumb_url = f"{app.api_url}{part_url}{part_api}"

        if self.cb_optimize_size_active is False:
            sync_url = f"{app.api_url}/Comics/{comic.Id}/Sync/File/"
        elif self.cb_optimize_size_active is True:
            sync_url = f"{app.api_url}/Comics/{comic.Id}/Sync/Webp"
        app = App.get_running_app()
        id_folder = os.path.join(app.sync_folder, self.slug)
        self.my_comic_dir = Path(os.path.join(id_folder, "comics"))
        self.my_thumb_dir = Path(os.path.join(id_folder, "thumb"))
        if not self.my_comic_dir.is_dir():
            os.makedirs(self.my_comic_dir)
        if not self.my_thumb_dir.is_dir():
            os.makedirs(self.my_thumb_dir)
        t_file = os.path.join(self.my_comic_dir, file_name)
        self.get_server_file_download(
            sync_url,
            callback=self.got_file(comic, comic_file=t_file),
            file_path=t_file,
        )
        thumb_name = f"{comic.Id}.jpg"
        self.fetch_data.get_server_file_download(
            thumb_url,
            callback=lambda req, results: got_thumb(results),
            file_path=os.path.join(self.my_thumb_dir, thumb_name),
        )

    def _finish_sync(self, comic_list, *largs):
        def __finish_toast(dt):
            toast("Reading List has been Synced, Refreshing Screen")
            # app = App.get_running_app()
            # screen = app.manager.get_screen("server_readinglists_screen")
            # screen.refresh_callback()

        list_comics = comic_list
        num_comic = len(list_comics)
        if self.num_file_done == num_comic:
            Clock.schedule_once(__finish_toast, 3)
            self.event.cancel()
            self.event = None

    def sync_readinglist(self, comic_list=[]):
        app = App.get_running_app()
        self.sync_list = comic_list
        app = App.get_running_app()
        screen = app.manager.get_screen("server_readinglists_screen")
        screen.ids.sync_status_lbl.text = (
            f"Sync is Running Comics to Sync: {len(self.sync_list)}"
        )
        app.sync_is_running = True
        screen.ids.sync_button.enabled = False
        Clock.schedule_once(self.download_file)
Exemple #13
0
    def do_db_refresh(self, screen=None):
        def __finish_toast(dt):
            app = App.get_running_app()
            screen = app.manager.get_screen("server_readinglists_screen")
            screen.refresh_callback()
            toast("DataBase Refresh Complete")

        def __got_readlist_data(results):
            def __updated_progress(results):
                pass

            the_keys = [
                "Id",
                "Series",
                "Number",
                "Volume",
                "Year",
                "Month",
                "UserCurrentPage",
                "UserLastPageRead",
                "PageCount",
                "Summary",
                "FilePath",
            ]
            for server_comic in results["items"]:
                for db_comic in self.comics:
                    if db_comic.Id == server_comic["Id"]:
                        for key in the_keys:
                            if getattr(db_comic, key) != server_comic[key]:
                                if key in (
                                    "UserCurrentPage",
                                    "UserLastPageRead",
                                ) and (db_comic.is_sync):
                                    if (
                                        db_comic.UserLastPageRead
                                        > server_comic["UserLastPageRead"]
                                    ) or (
                                        db_comic.UserCurrentPage
                                        > server_comic["UserCurrentPage"]
                                    ):
                                        if (
                                            db_comic.UserCurrentPage
                                            > db_comic.UserLastPageRead
                                        ):
                                            current_page = (
                                                db_comic.UserCurrentPage
                                            )  # noqa
                                        else:
                                            current_page = (
                                                db_comic.UserLastPageRead
                                            )  # noqa
                                        update_url = "{}/Comics/{}/Progress".format(
                                            api_url, db_comic.Id
                                        )
                                        self.fetch_data.update_progress(
                                            update_url,
                                            current_page,
                                            callback=lambda req, results: __updated_progress(
                                                results
                                            ),
                                        )
                                    else:
                                        x_str = db_comic.__str__
                                        Logger.info(
                                            "Updating DB Record for {} of {}".format(
                                                key, x_str
                                            )
                                        )
                                        toast(
                                            "Updating DB Record for {} of {}".format(
                                                key, x_str
                                            )
                                        )
                                        db_item = Comic.get(
                                            Comic.Id == db_comic.Id
                                        )
                                        if db_item:
                                            setattr(
                                                db_item, key, server_comic[key]
                                            )
                                            db_item.save()
                                            setattr(self, key, db_item)

            Clock.schedule_once(__finish_toast, 3)

        self.fetch_data = ComicServerConn()
        app = App.get_running_app()
        api_url = app.api_url
        server_url = f"{api_url}/Lists/{self.slug}/Comics/"

        self.fetch_data.get_server_data_callback(
            server_url,
            callback=lambda req, results: __got_readlist_data(results),
        )
Exemple #14
0
class ServerReadingListsScreen(Screen):
    reading_list_title = StringProperty()
    page_number = NumericProperty()
    max_books_page = NumericProperty()
    dynamic_ids = DictProperty({})  # declare class attribute, dynamic_ids
    sync_bool = BooleanProperty(False)
    so = BooleanProperty()
    new_readinglist = ObjectProperty()

    def __init__(self, **kwargs):
        super(ServerReadingListsScreen, self).__init__(**kwargs)
        self.app = App.get_running_app()
        self.fetch_data = None
        self.readinglist_Id = StringProperty()
        self.readinglist_name = ""
        # self.bind_to_resize()
        self.bind(width=self.my_width_callback)
        self.m_grid = ""
        self.main_stack = ""
        self.prev_button = ""
        self.next_button = ""
        self.base_url = self.app.base_url
        self.api_url = self.app.api_url
        self.api_key = self.app.config.get("General", "api_key")
        self.list_count = ""
        self.paginator_obj = ObjectProperty()
        self.current_page = ObjectProperty()
        self.list_loaded = BooleanProperty()
        self.page_number = 1
        self.list_loaded = False
        self.comic_thumb_height = 240
        self.comic_thumb_width = 156
        self.file_download = True
        self.num_file_done = 0
        self.max_books_page = self.app.max_books_page
        self.please_wait_dialog = None
        self.dialog_load_comic_data = None

    def callback_for_menu_items(self, *args):
        pass

    def setup_screen(self):
        self.api_key = self.app.config.get("General", "api_key")
        self.api_url = self.app.api_url
        self.main_stack = self.ids["main_stack"]
        self.m_grid = self.ids["main_grid"]
        self.prev_button = self.ids["prev_button"]
        self.next_button = self.ids["next_button"]

    def on_pre_enter(self, *args):
        self.app.show_action_bar()
        return super().on_pre_enter(*args)

    def on_leave(self, *args):
        self.app.list_previous_screens.append(self.name)
        return super().on_leave(*args)

    def my_width_callback(self, obj, value):

        for key, val in self.ids.items():
            if key == "main_grid":
                c = val
                c.cols = (Window.width - 10) // self.comic_thumb_width

    def page_turn(self, c_id, new_UserLastPageRead):
        grid = self.m_grid
        for child in grid.children:
            if child.comic_obj.Id == c_id:
                if new_UserLastPageRead == 0:
                    child.percent_read = 0
                else:
                    child.percent_read = round(
                        new_UserLastPageRead /
                        (child.comic_obj.PageCount - 1) * 100)
                child.page_count_text = f"{child.percent_read}%"

    def file_sync_update(self, c_id, state):
        grid = self.m_grid
        for child in grid.children:
            if child.comic_obj.Id == c_id:
                child.has_localfile = state

    def collect_readinglist_data(
        self,
        readinglist_name="",
        readinglist_Id="",
        mode="From Server",
        current_page_num=1,
        *largs,
    ):
        async def collect_readinglist_data():
            self.readinglist_name = readinglist_name
            self.app.set_screen(self.readinglist_name + " Page 1")
            self.reading_list_title = self.readinglist_name + " Page 1"
            self.readinglist_Id = readinglist_Id
            self.page_number = current_page_num
            self.mode = mode
            if self.mode == "From Server":
                self.fetch_data = ComicServerConn()
                lsit_count_url = "{}/Lists/{}/Comics/".format(
                    self.api_url, readinglist_Id)
                # self.fetch_data.get_list_count(lsit_count_url,self)
                self.fetch_data.get_server_data(lsit_count_url, self)
            elif self.mode == "From DataBase":
                self.got_db_data()

        asynckivy.start(collect_readinglist_data())

    def get_page(self, instance):
        page_num = instance.page_num
        self.app.set_screen(self.readinglist_name + f" Page {page_num}")
        self.reading_list_title = self.readinglist_name + f" Page {page_num}"
        page = self.paginator_obj.page(page_num)
        self.current_page = page
        if page.has_next():
            self.next_button.opacity = 1
            self.next_button.disabled = False
            self.next_button.page_num = page.next_page_number()
        else:
            self.next_button.opacity = 0
            self.next_button.disabled = True
            self.next_button.page_num = ""
        if page.has_previous():
            self.prev_button.opacity = 1
            self.prev_button.disabled = False
            self.prev_button.page_num = page.previous_page_number()
        else:
            self.prev_button.opacity = 0
            self.prev_button.disabled = True
            self.prev_button.page_num = ""
        self.build_page(page.object_list)

    def build_page(self, object_lsit):
        async def _build_page():
            grid = self.m_grid
            grid.clear_widgets()
            for comic in object_lsit:
                await asynckivy.sleep(0)
                c = ReadingListComicImage(comic_obj=comic)
                c.lines = 2
                c.readinglist_obj = self.new_readinglist
                c.paginator_obj = self.paginator_obj
                y = self.comic_thumb_height
                thumb_filename = f"{comic.Id}.jpg"
                id_folder = self.app.store_dir
                my_thumb_dir = os.path.join(id_folder, "comic_thumbs")
                t_file = os.path.join(my_thumb_dir, thumb_filename)
                if os.path.isfile(t_file):
                    c_image_source = t_file
                else:
                    part_url = f"/Comics/{comic.Id}/Pages/0?"
                    part_api = "&apiKey={}&height={}".format(
                        self.api_key, round(dp(y)))
                    c_image_source = f"{self.api_url}{part_url}{part_api}"
                    asynckivy.start(save_thumb(comic.Id, c_image_source))
                c.source = c_image_source
                c.PageCount = comic.PageCount
                c.pag_pagenum = self.current_page.number
                grid.add_widget(c)
                grid.cols = (Window.width - 10) // self.comic_thumb_width
                self.dynamic_ids[id] = c
            self.ids.page_count.text = "Page #\n{} of {}".format(
                self.current_page.number, self.paginator_obj.num_pages())
            self.loading_done = True

        asynckivy.start(_build_page())

    def refresh_callback(self, *args):
        """A method that updates the state of reading list"""
        def __refresh_callback(interval):
            self.ids.main_grid.clear_widgets()
            self.collect_readinglist_data(
                self.readinglist_name,
                self.readinglist_Id,
                current_page_num=self.page_number,
                mode="From DataBase",
            )
            #            self.build_page(page.object_list)
            # self.ids.main_scroll.refresh_done()
            self.tick = 0

        Clock.schedule_once(__refresh_callback, 1)

    def got_db_data(self):
        """
        used if rl data is already stored in db.
        """
        async def _do_readinglist():
            self.new_readinglist = ComicReadingList(
                name=self.readinglist_name,
                data="db_data",
                slug=self.readinglist_Id,
            )
            await asynckivy.sleep(0)
            self.so = self.new_readinglist.sw_syn_this_active
            self.setup_options()
            new_readinglist_reversed = self.new_readinglist.comics
            self.paginator_obj = Paginator(new_readinglist_reversed,
                                           self.max_books_page)
            page = self.paginator_obj.page(self.page_number)
            self.current_page = page
            if page.has_next():
                self.next_button.opacity = 1
                self.next_button.disabled = False
                self.next_button.page_num = page.next_page_number()
            else:
                self.next_button.opacity = 0
                self.next_button.disabled = True
                self.next_button.page_num = ""
            if page.has_previous():
                self.prev_button.opacity = 1
                self.prev_button.disabled = False
                self.prev_button.page_num = page.previous_page_number()
            else:
                self.prev_button.opacity = 0
                self.prev_button.disabled = True
                self.prev_button.page_num = ""
            self.build_page(page.object_list)
            self.list_loaded = True

        asynckivy.start(_do_readinglist())

    def got_json(self, req, results):
        print("Start got_json")

        async def _got_json():
            print("Start _got_json")
            self.new_readinglist = ComicReadingList(
                name=self.readinglist_name,
                data=results,
                slug=self.readinglist_Id,
            )
            totalCount = self.new_readinglist.totalCount
            i = 1
            for item in self.new_readinglist.comic_json:
                await asynckivy.sleep(0)
                str_name = "{} #{}".format(item["Series"], item["Number"])
                self.dialog_load_comic_data.name_kv_file = str_name
                self.dialog_load_comic_data.percent = str(i * 100 //
                                                          int(totalCount))
                comic_index = self.new_readinglist.comic_json.index(item)
                new_comic = ComicBook(
                    item,
                    readlist_obj=self.new_readinglist,
                    comic_index=comic_index,
                )
                self.new_readinglist.add_comic(new_comic)
                i += 1
            print("End for item in self.new_readinglist.comic_json:")
            self.setup_options()
            new_readinglist_reversed = self.new_readinglist.comics[::-1]
            self.paginator_obj = Paginator(new_readinglist_reversed,
                                           self.max_books_page)
            page = self.paginator_obj.page(self.page_number)
            self.current_page = page
            if page.has_next():
                self.next_button.opacity = 1
                self.next_button.disabled = False
                self.next_button.page_num = page.next_page_number()
            else:
                self.next_button.opacity = 0
                self.next_button.disabled = True
                self.next_button.page_num = ""
            if page.has_previous():
                self.prev_button.opacity = 1
                self.prev_button.disabled = False
                self.prev_button.page_num = page.previous_page_number()
            else:
                self.prev_button.opacity = 0
                self.prev_button.disabled = True
                self.prev_button.page_num = ""
            self.build_page(page.object_list)
            self.list_loaded = True
            self.dialog_load_comic_data.dismiss()

        self.dialog_load_comic_data = DialogLoadKvFiles()
        self.dialog_load_comic_data.open()
        asynckivy.start(_got_json())

    def show_please_wait_dialog(self):
        def __callback_for_please_wait_dialog(*args):
            pass

        self.please_wait_dialog = MDDialog(
            title="No ReadingList loaded.",
            size_hint=(0.8, 0.4),
            text_button_ok="Ok",
            text=f"No ReadingList loaded.",
            events_callback=__callback_for_please_wait_dialog,
        )
        self.please_wait_dialog.open()

    def setup_options(self):
        self.sync_options = SyncOptionsPopup(
            size_hint=(0.76, 0.76),
            cb_limit_active=self.new_readinglist.cb_limit_active,
            limit_num_text=str(self.new_readinglist.limit_num),
            cb_only_read_active=self.new_readinglist.cb_only_read_active,
            cb_purge_active=self.new_readinglist.cb_purge_active,  # noqa
            cb_optimize_size_active=self.new_readinglist.
            cb_optimize_size_active,  # noqa
            sw_syn_this_active=bool(self.new_readinglist.sw_syn_this_active),
        )
        self.sync_options.ids.limit_num.bind(
            on_text_validate=self.sync_options.check_input,
            focus=self.sync_options.check_input,
        )

        self.sync_options.title = self.new_readinglist.name

    def open_sync_options(self):
        if self.sync_options.ids.sw_syn_this.active is True:
            self.sync_options.ids.syn_on_off_label.text = f""
            self.sync_options.ids.syn_on_off_label.theme_text_color = "Primary"
        self.sync_options.open()

    def sync_readinglist(self):
        if self.sync_options.ids.sw_syn_this.active is False:
            self.sync_options.ids.syn_on_off_label.text = f"Sync Not Turned On"
            self.open_sync_options()
        elif self.sync_options.ids.sw_syn_this.active is True:
            toast(f"Starting sync of {self.new_readinglist.name}")
            self.new_readinglist.do_sync()
Exemple #15
0
class SyncReadingListObject(object):
    cb_only_read_state = 'normal'
    cb_keep_last_read_state = 'normal'
    cb_optimize_size_state = 'normal'
    cb_limit_state = 'normal'
    limit_num = 25
    sw_syn_this_active = False

    def __init__(self, reading_list=None, **kwords):
        self.reading_list = reading_list

        self.app = App.get_running_app()
        self.api_url = self.app.api_url
        self.fetch_data = ComicServerConn()
        self.num_file_done = 0
        self.comic_thumb_height = 240
        self.comic_thumb_width = 156
        id_folder = os.path.join(self.app.sync_folder, self.reading_list.slug)
        my_data_dir = Path(os.path.join(id_folder, 'data'))
        self.my_comic_dir = Path(os.path.join(id_folder, 'comics'))
        self.my_thumb_dir = Path(os.path.join(self.my_comic_dir, 'thumb'))
        if not self.my_comic_dir.is_dir():
            os.makedirs(self.my_comic_dir)
        if not self.my_thumb_dir.is_dir():
            os.makedirs(self.my_thumb_dir)
        # for item in SYNC_SETTINGS_ITEMS:
        #    val = ""
        #    tmp_defaults[key] = getattr(self, key)
        # NOTE: can be removed once DB functions added
        if not my_data_dir.is_dir():
            os.makedirs(my_data_dir)
        settings_json = os.path.join(my_data_dir, 'settings.json')
        comics_json = os.path.join(my_data_dir, 'sync_comics.json')
        self.this_test = "Test"
        self.sync_data = JsonStore(settings_json)
        self.sync_comics = JsonStore(comics_json)
        self.last_read_comic = self.get_last_comic_read()
        if self.sync_data.exists('options'):
            self.cb_only_read_state = self.sync_data.get(
                "options")["cb_only_read_state"]
            self.cb_keep_last_read_state = self.sync_data.get(
                "options")["cb_keep_last_read_state"]
            self.cb_optimize_size_state = self.sync_data.get(
                "options")["cb_optimize_size_state"]
            self.cb_limit_state = self.sync_data.get("options")[
                "cb_limit_state"]
            self.limit_num = self.sync_data.get("options")["limit_num"]
            self.sw_syn_this_active = self.sync_data.get("options")[
                'sw_syn_this_active']
        else:
            self.cb_only_read_state = 'normal'
            self.cb_keep_last_read_state = 'normal'
            self.cb_optimize_size_state = 'normal'
            self.cb_limit_state = 'normal'
            self.limit_num = 25
            self.sw_syn_this_active = False
        # end note

        self.last = 0
        self.limit = 25
        self.sync_range = int(self.last) + int(self.limit_num)
        self.api_key = self.app.config.get('General', 'api_key')

    def get_comics(self):
        self.sync_comics.get()

    def get_last_comic_read(self):
        last_read_comic = "None Read"
        for comic in self.reading_list.comics:
            if comic.UserLastPageRead == comic.PageCount-1:
                last_read_comic = self.reading_list.comics.index(comic)

        return last_read_comic

    def save_values(self,
                    cb_limit_state=cb_limit_state,
                    limit_num=limit_num,
                    cb_only_read_state=cb_only_read_state,
                    cb_keep_last_read_state=cb_keep_last_read_state,
                    cb_optimize_size_state=cb_optimize_size_state,
                    sw_syn_this_active=sw_syn_this_active,
                    *args, **kwargs):
        # self.sync_data.put()

        self.sync_data.put('options',
                           cb_limit_state=cb_limit_state,
                           limit_num=limit_num,
                           cb_only_read_state=cb_only_read_state,
                           cb_keep_last_read_state=cb_keep_last_read_state,
                           cb_optimize_size_state=cb_optimize_size_state,
                           sw_syn_this_active=sw_syn_this_active
                           )
        self.cb_only_read_state = cb_only_read_state
        self.cb_keep_last_read_state = cb_keep_last_read_state
        self.cb_optimize_size_state = cb_optimize_size_state
        self.cb_limit_state = cb_limit_state
        self.limit_num = limit_num
        self.sync_range = int(self.last) + int(self.limit_num)
        self.sw_syn_this_active = sw_syn_this_active

    def download_file(self, comic):
        comic_index = 0
        self.file_download = False
        file_name = ntpath.basename(comic.FilePath)
        for i, j in enumerate(self.reading_list.comics):
            if j.Id == comic.Id:
                comic_index = i

        def got_file(results):
            self.num_file_done += 1
            toast(f'{file_name} Synced')
            self.file_download = True
            self.sync_comics.put(comic.Id,
                                 file=file_name,
                                 slug=comic.slug,
                                 data_type='ComicBook',
                                 Series=comic.Series,
                                 Number=comic.Number,
                                 Month=comic.Month,
                                 Year=comic.Year,
                                 UserCurrentPage=comic.UserCurrentPage,
                                 UserLastPageRead=comic.UserLastPageRead,
                                 PageCount=comic.PageCount,
                                 Summary=comic.Summary,
                                 Index=comic_index,
                                 FilePath=comic.FilePath,
                                 ReadlistID=self.reading_list.slug
                                 )

        def got_thumb(results):
            pass

        x = self.comic_thumb_width
        y = self.comic_thumb_height
        thumb_size = f'height={y}&width={x}'
        part_url = f'/Comics/{comic.Id}/Pages/0?'
        part_api = f'&apiKey={self.api_key}&height={round(dp(y))}'
        thumb_url = f"{self.api_url}{part_url}{part_api}"

        if self.cb_optimize_size_state == 'normal':
            sync_url = f'{self.api_url}/Comics/{comic.Id}/File/'
        elif self.cb_optimize_size_state == 'down':
            sync_url = f'{self.api_url}/Comics/{comic.Id}/Sync/'

        self.fetch_data.get_server_file_download(
            sync_url, callback=lambda req,
            results: got_file(results),
            file_path=os.path.join(self.my_comic_dir, file_name)

        )
        thumb_name = f'{comic.Id}.jpg'
        self.fetch_data.get_server_file_download(thumb_url,
                                                 callback=lambda req, results: got_thumb(
                                                     results),
                                                 file_path=os.path.join(
                                                     self.my_thumb_dir, thumb_name)

                                                 )

    def _finish_sync(self, dt):
        def _finish_toast(dt):
            toast('Reading List has been Synceddd')

        list_comics = self.reading_list.comics
        sync_num_comics = list_comics[self.last: self.sync_range]
        num_comic = len(sync_num_comics)
        if self.num_file_done == num_comic:
            Clock.schedule_once(_finish_toast, 3)
            self.event.cancel()

    def sync_readinglist(self):
        list_comics = self.reading_list.comics
        sync_num_comics = list_comics[self.last: self.sync_range]

        self.app.delayed_work(
            self.download_file, sync_num_comics, delay=.5)
        self.event = Clock.schedule_interval(self._finish_sync, 0.5)
Exemple #16
0
class BaseScreen(Screen):
    app = App.get_running_app()
    username = ConfigParserProperty("", "General", "username", app.config)
    password = ConfigParserProperty("", "General", "password", app.config)
    api_key = ConfigParserProperty("", "General", "api_key", app.config)
    base_url = ConfigParserProperty("", "General", "base_url", app.config)

    def __init__(self, **kwargs):
        super(BaseScreen, self).__init__(**kwargs)
        self.app = App.get_running_app()
        self.fetch_data = None
        self.Data = ""

        self.fetch_data = ComicServerConn()
        self.myLoginPop = LoginPopupContent()
        self.popup = LoginPopup(
            content=self.myLoginPop, size_hint=(None, None), size=(500, 400)
        )
        # self.update_settings()
        # self.bind(username=self.update_settings)
        # self.bind_settings()
        self.password = self.app.password
        self.api_key = self.app.api_key
        self.username = self.app.username
        self.base_url = self.app.base_url
        self.open_last_comic_startup = self.app.open_last_comic_startup

    def update_settings(self, *args):
        print(f"This is running : {self.username}")
        # self.username = self.app.username

    def on_pre_enter(self, *args):
        self.check_login()

    def check_login(self):
        # see if user has a api key stored from server
        if self.api_key == "":

            self.myLoginPop.ids.info.text = "[color=#FF0000]\
                No API key stored login to get one\
                    [/color]"
            # self.open_popup()
            # self.fetch_data.get_api_key(req_url,self.username,self.password,self)
        else:

            tmp_readinglist_name = self.app.config.get(
                "Saved", "last_reading_list_name"
            )
            tmp_readinglist_Id = self.app.config.get(
                "Saved", "last_reading_list_id"
            )
            if tmp_readinglist_Id == "":
                return
            else:
                pass
                Clock.schedule_once(
                    lambda dt: self.build_last_comic_section(
                        tmp_readinglist_name, tmp_readinglist_Id
                    )
                )

    def open_comic(
        self,
        tmp_last_comic_id="",
        tmp_last_comic_type="",
        paginator_obj=None,
        comic=None,
        tmp_last_pag_pagnum=None,
    ):
        if tmp_last_comic_type == "local_file":
            view_mode = "Sync"
        else:
            view_mode = "Server"
        screen = self.app.manager.get_screen("comic_book_screen")
        screen.setup_screen(
            readinglist_obj=self.new_readinglist,
            comic_obj=comic,
            paginator_obj=paginator_obj,
            pag_pagenum=tmp_last_pag_pagnum,
            last_load=0,
            view_mode=view_mode,
        )
        self.app.manager.current = "comic_book_screen"
        self.app.app_started = True

    def validate_user(self):
        def got_api(result):
            api_key = result["ApiKey"]
            self.app.config.set("General", "api_key", api_key)
            self.app.config.write()
            self.api_key = api_key
            self.myLoginPop.ids.info.text = "[color=#008000]\
                                            Login Sucessful API key saved\
                                                [/color]"
            self.popup.dismiss()
            tmp_readinglist_name = self.app.config.get(
                "Saved", "last_reading_list_name"
            )
            tmp_readinglist_Id = self.app.config.get(
                "Saved", "last_reading_list_id"
            )
            if tmp_readinglist_Id == "":
                return
            else:
                Clock.schedule_once(
                    lambda dt: self.build_last_comic_section(
                        tmp_readinglist_name, tmp_readinglist_Id
                    )
                )

        user = self.myLoginPop.ids.username_field.text
        pwd = self.myLoginPop.ids.pwd_field.text
        url = self.myLoginPop.ids.url_field.text
        self.base_url = url.strip()
        self.username = user
        self.password = pwd
        req_url = f"{self.app.base_url}/auth"
        self.fetch_data.get_api_key(
            req_url, user, pwd, callback=lambda req, results: got_api(results)
        )

    def call_collect(
        self, set_mode, readinglists_screen, readinglist_name, readinglist_Id
    ):
        Clock.schedule_once(
            lambda dt: readinglists_screen.collect_readinglist_data(
                readinglist_name=readinglist_name,
                readinglist_Id=readinglist_Id,
                mode=set_mode,
            )
        )

    def build_last_comic_section(  # noqa
        self, readinglist_name, readinglist_Id
    ):
        def __got_readlist_data(results):
            async def __load_readinglist_scree(paginator_obj=None):
                if tmp_last_comic_type == "local_file":
                    x_readinglists_screen = self.app.manager.get_screen(
                        "local_readinglists_screen"
                    )
                else:
                    x_readinglists_screen = self.app.manager.get_screen(
                        "server_readinglists_screen"
                    )
                x_readinglists_screen.list_loaded = False
                x_readinglists_screen.setup_screen()
                x_readinglists_screen.page_number = tmp_last_pag_pagnum
                x_readinglists_screen.loading_done = False
                self.call_collect(
                    set_mode,
                    x_readinglists_screen,
                    readinglist_name,
                    readinglist_Id,
                )

            tmp_last_comic_id = self.app.config.get("Saved", "last_comic_id")
            tmp_last_comic_type = self.app.config.get(
                "Saved", "last_comic_type"
            )
            tmp_last_pag_pagnum = int(
                self.app.config.get("Saved", "last_pag_pagnum")
            )
            if tmp_last_comic_id == "":
                return
            else:
                query = ReadingList.select().where(
                    ReadingList.slug == readinglist_Id
                )
                if query.exists():
                    Logger.info(f"{readinglist_name} already in Database")
                    set_mode = "From DataBase"
                    mode = ""
                    if tmp_last_comic_type == "local_file":
                        mode = "local_file"
                    self.new_readinglist = ComicReadingList(
                        name=self.readinglist_name,
                        data="db_data",
                        slug=self.readinglist_Id,
                        mode=mode,
                    )

                    # self.new_readinglist.comics_write()
                    max_books_page = int(
                        self.app.config.get("General", "max_books_page")
                    )
                    new_readinglist_reversed = self.new_readinglist.comics
                    paginator_obj = Paginator(
                        new_readinglist_reversed, max_books_page
                    )
                    for x in range(1, paginator_obj.num_pages()):
                        this_page = paginator_obj.page(x)
                        for comic in this_page.object_list:
                            if tmp_last_comic_id == comic.Id:
                                tmp_last_pag_pagnum = this_page.number
                    asynckivy.start(
                        __load_readinglist_scree(paginator_obj=paginator_obj)
                    )
                    if (
                        self.open_last_comic_startup == 1
                        and not self.app.app_started
                    ):
                        for comic in self.new_readinglist.comics:
                            if comic.slug == tmp_last_comic_id:

                                self.open_comic(
                                    tmp_last_comic_id=tmp_last_comic_id,
                                    tmp_last_comic_type=tmp_last_comic_type,
                                    paginator_obj=paginator_obj,
                                    comic=comic,
                                    tmp_last_pag_pagnum=tmp_last_pag_pagnum,
                                )
                    else:
                        grid = self.ids["main_grid"]
                        grid.cols = 1
                        grid.clear_widgets()
                        for comic in self.new_readinglist.comics:
                            if comic.slug == tmp_last_comic_id:
                                c = ReadingListComicImage(comic_obj=comic)
                                c.readinglist_obj = self.new_readinglist
                                c.paginator_obj = paginator_obj
                                x = self.app.comic_thumb_width
                                y = self.app.comic_thumb_height
                                if tmp_last_comic_type == "local_file":
                                    if comic.local_file == "":
                                        return
                                    import os

                                    id_folder = os.path.join(
                                        self.app.sync_folder,
                                        self.new_readinglist.slug,
                                    )
                                    my_thumb_dir = os.path.join(
                                        id_folder, "thumb"
                                    )
                                    thumb_name = f"{comic.Id}.jpg"
                                    t_file = os.path.join(
                                        my_thumb_dir, thumb_name
                                    )
                                    c_image_source = t_file
                                else:
                                    round_y = round(dp(y))
                                    part_url = f"/Comics/{comic.Id}/Pages/0?"
                                    part_api = "&apiKey={}&height={}".format(
                                        self.api_key, round_y
                                    )
                                    c_image_source = "{}{}{}".format(
                                        self.app.api_url, part_url, part_api
                                    )
                                c.source = c_image_source
                                c.PageCount = comic.PageCount
                                c.pag_pagenum = tmp_last_pag_pagnum
                                if tmp_last_comic_type == "local_file":
                                    c.view_mode = "Sync"
                                strtxt = f"{comic.Series} #{comic.Number}"
                                tmp_color = get_hex_from_color((1, 1, 1, 1))
                                c.text = f"[color={tmp_color}]{strtxt}[/color]"
                                grid.add_widget(c)
                                tmp_txt = f"Last Comic Load from \
                                        {self.new_readinglist.name}"
                                self.ids.last_comic_label.text = tmp_txt
                else:
                    Logger.info(
                        f"{readinglist_name} \
                            not in Database This could be a problems"
                    )

                    set_mode = "From Server"
                # set_mode = 'From Server'

        self.readinglist_name = readinglist_name
        # self.app.set_screen(self.readinglist_name + ' Page 1')
        self.reading_list_title = self.readinglist_name + " Page 1"
        self.readinglist_Id = readinglist_Id

        # self.fetch_data.get_list_count(lsit_count_url,self)
        tmp_last_comic_type = self.app.config.get("Saved", "last_comic_type")
        if tmp_last_comic_type == "local_file":
            Clock.schedule_once(lambda dt: __got_readlist_data("none"), 0.15)
        else:
            self.fetch_data = ComicServerConn()
            lsit_count_url = (
                f"{self.app.api_url}/Lists/{readinglist_Id}/Comics/"
            )  # noqa
            self.fetch_data.get_server_data_callback(
                lsit_count_url,
                callback=lambda req, results: __got_readlist_data(results),
            )

    def update_leaf(self):
        Window.fullscreen = "auto"

    def open_popup(self):

        self.popup.open()

    def close_popup(self):
        self.popup.dismiss()

    def got_error(self, req, results):
        Logger.critical("ERROR in %s %s" % (inspect.stack()[0][3], results))

    def got_time_out(self, req, results):
        Logger.critical("ERROR in %s %s" % (inspect.stack()[0][3], results))

    def got_failure(self, req, results):
        Logger.critical("ERROR in %s %s" % (inspect.stack()[0][3], results))

    def got_redirect(self, req, results):
        Logger.critical("ERROR in %s %s" % (inspect.stack()[0][3], results))

    def callback_for_menu_items(self, *args):
        pass
Exemple #17
0
class ServerComicBookScreen(Screen):
    scroller = ObjectProperty()
    top_pop = ObjectProperty()
    section = StringProperty()
    sort_by = StringProperty()
    last_load = NumericProperty()
    str_page_count = StringProperty()
    full_screen = BooleanProperty()
    next_nav_comic_thumb = ObjectProperty()
    prev_nav_comic_thumb = ObjectProperty()
    pag_pagenum = NumericProperty()
    view_mode = StringProperty()
    dynamic_ids = DictProperty({})  # declare class attribute, dynamic_ids
    paginator_obj = ObjectProperty()
    comic_obj = ObjectProperty()
    id = StringProperty()

    def __init__(self, **kwargs):
        super(ServerComicBookScreen, self).__init__(**kwargs)
        self.fetch_data = None
        self.app = App.get_running_app()
        #        self.base_url = self.app.base_url
        #        self.api_url = self.app.api_url
        self.current_page = None
        self.fetch_data = ComicServerConn()
        self.api_key = self.app.config.get("General", "api_key")
        self.popup_bkcolor = (0.5, 0.5, 0.5, 0.87)
        self.full_screen = False
        self.option_isopen = False
        self.next_dialog_open = False
        self.prev_dialog_open = False
        config_app = App.get_running_app()
        settings_data = json.loads(settings_json_screen_tap_control)
        # Window.bind(on_keyboard=self.events_program)
        for setting in settings_data:
            if setting["type"] == "options":
                tap_config = config_app.config.get(setting["section"],
                                                   setting["key"])
                if tap_config == "Disabled":
                    self.ids[setting["key"]].disabled = True

    def setup_screen(
        self,
        readinglist_obj=None,
        comic_obj=None,  # noqa
        view_mode="Server",
        paginator_obj=None,
        pag_pagenum=1,
        last_load=0,
        **kwargs,
    ):

        self.current_page = None
        self.readinglist_obj = None
        self.pag_pagenum = 0
        self.last_load = 0
        self.readinglist_obj = readinglist_obj
        self.comic_obj = comic_obj
        self.paginator_obj = paginator_obj
        self.view_mode = view_mode
        self.app.config.write()
        self.pag_pagenum = pag_pagenum
        self.last_load = last_load
        self.app.open_comic_screen = "None"
        if self.view_mode == "FileOpen":
            pass
        else:
            if self.view_mode == "Sync":
                last_comic_type = "local_file"
            else:
                last_comic_type = "Server"
            self.app.config.set("Saved", "last_comic_id", self.comic_obj.Id)
            self.app.config.set("Saved", "last_comic_type", last_comic_type)
            self.app.config.set("Saved", "last_reading_list_id",
                                self.readinglist_obj.slug)
            self.app.config.set("Saved", "last_reading_list_name",
                                self.readinglist_obj.name)
            if int(self.pag_pagenum):
                self.app.config.set("Saved", "last_pag_pagnum",
                                    self.pag_pagenum)
        self.app.config.write()
        comic_book_carousel = self.ids.comic_book_carousel
        comic_book_carousel.clear_widgets()
        for slide in comic_book_carousel.slides:
            print(slide)
        if self.scroller:
            self.scroller.clear_widgets()
        if self.top_pop:
            self.top_pop.clear_widgets()
        number_pages = int(comic_obj.PageCount)
        max_comic_pages_limit = int(App.get_running_app().config.get(
            "Display", "max_comic_pages_limit"))
        if number_pages <= max_comic_pages_limit:
            x_title = "Pages 1 to %s of %s " % (number_pages, number_pages)
        else:
            if self.last_load == 0:
                x_title = "Pages 1 to %s of %s " % (
                    max_comic_pages_limit,
                    number_pages,
                )
            else:
                x_title = "Pages %s to %s of %s " % (
                    max_comic_pages_limit,
                    (self.last_load + max_comic_pages_limit),
                    number_pages,
                )
        self.str_page_count = x_title
        x_title = f"{self.comic_obj.__str__} {x_title}"
        scroll = MyScrollView(
            size_hint=(1, 1),
            do_scroll_x=True,
            do_scroll_y=False,
            id="page_thumb_scroll",
            scroll_type=["bars", "content"],
        )
        self.dynamic_ids["page_thumb_scroll"] = scroll
        self.page_nav_popup = MyPopup(
            id="page_nav_popup",
            title=x_title,
            pos_hint={"y": 0},
            size_hint=(1, None),
            height=round(dp(320)),
        )
        self.dynamic_ids["page_nav_popup"] = self.page_nav_popup
        self.page_nav_popup.add_widget(scroll)
        self.scroller = scroll
        outer_grid = MyGridLayout(
            rows=1,
            size_hint=(None, None),
            spacing=(5, 0),
            padding=(5, 1),
            id="outtergrd",
        )
        outer_grid.bind(minimum_width=outer_grid.setter("width"))
        scroll.add_widget(outer_grid)
        i = 0
        self.use_sections = False
        if number_pages <= max_comic_pages_limit:
            self.use_sections = False
            for i in range(0, number_pages):
                self.add_pages(comic_book_carousel, outer_grid, comic_obj, i)
        else:
            self.use_sections = True
            if self.last_load == 0:
                z = max_comic_pages_limit
                for i in range(0, number_pages)[0:z]:
                    self.add_pages(comic_book_carousel, outer_grid, comic_obj,
                                   i)
                self.last_load = max_comic_pages_limit
                self.last_section = 0
            else:
                z = self.last_load + max_comic_pages_limit
                for i in range(0, number_pages)[self.last_load:z]:
                    self.add_pages(comic_book_carousel, outer_grid, comic_obj,
                                   i)
                if (self.last_load - max_comic_pages_limit) >= 0:
                    self.last_section = self.last_load - max_comic_pages_limit
                self.last_load = self.last_load + max_comic_pages_limit
            if self.use_sections:
                if i + 1 >= number_pages:
                    self.use_sections = False
                    self.section = "Last"
                elif i + 1 == max_comic_pages_limit:
                    self.section = "First"
                else:
                    self.section = "Section"
        self.close_next_dialog()
        self.close_prev_dialog()
        self.build_top_nav()
        self.next_comic = self.get_next_comic()
        self.prev_comic = self.get_prev_comic()
        self.build_next_comic_dialog()
        self.build_prev_comic_dialog()
        self.app.open_comic_screen = self.comic_obj.Id

    def toggle_full_screen(self):
        if self.full_screen is False:
            Window.fullscreen = True
            self.full_screen is True
        else:
            Window.fullscreen = False

    def open_mag_glass(self):
        comic_book_carousel = self.ids.comic_book_carousel
        current_slide = comic_book_carousel.current_slide
        current_slide.open_mag_glass()

    def on_pre_enter(self):
        self.app.hide_action_bar()
        # self.build_option_pop()

    def on_pre_leave(self, *args):
        self.top_pop.dismiss()
        self.page_nav_popup.dismiss()
        # self.option_pop.dismiss()

    def on_leave(self, *args):
        pass
        # self.app.manager.remove_widget(self)
        # self = None

    def load_UserCurrentPage(self):
        for slide in self.ids.comic_book_carousel.slides:
            if slide.comic_page == self.comic_obj.UserCurrentPage:
                self.ids.comic_book_carousel.load_slide(slide)

    def refresh_callback(self, *args):
        """A method that updates the state of your application
        while the spinner remains on the screen."""
        def refresh_callback(interval):
            pass
            # self.screen.ids.box.clear_widgets()
            # if self.x == 0:
            #     self.x, self.y = 15, 30
            # else:
            #     self.x, self.y = 0, 15
            # self.set_list()
            # self.screen.ids.refresh_layout.refresh_done()
            # self.tick = 0

        Clock.schedule_once(refresh_callback, 1)

    def slide_changed(self, index):  # noqa
        if self.app.open_comic_screen == "None":
            return

        def __update_page(key_val=None):
            db_item = Comic.get(Comic.Id == self.comic_obj.Id)
            for key, value in key_val.items():
                setattr(db_item, key, value)
                setattr(self.comic_obj, key, value)
                if key == "UserLastPageRead":
                    if self.view_mode == "FileOpen" or (
                            self.view_mode == "Sync"
                            and self.comic_obj.is_sync):
                        local_readinglists_screen = self.app.manager.get_screen(
                            "local_readinglists_screen")
                        local_readinglists_screen.page_turn(
                            self.comic_obj.Id, value)
                    else:
                        server_readinglists_screen = self.app.manager.get_screen(
                            "server_readinglists_screen")
                        server_readinglists_screen.page_turn(
                            self.comic_obj.Id, value)
            db_item.save()

        if self.view_mode == "FileOpen" or (self.view_mode == "Sync"
                                            and self.comic_obj.is_sync):

            if index is not None:

                comic_book_carousel = self.ids.comic_book_carousel
                current_page = comic_book_carousel.current_slide.comic_page
                comic_obj = self.comic_obj
                comic_Id = comic_obj.Id
                if self.comic_obj.is_sync:
                    if current_page > self.comic_obj.UserLastPageRead:
                        key_val = {
                            "UserLastPageRead": current_page,
                            "UserCurrentPage": current_page,
                        }
                    else:
                        key_val = {"UserCurrentPage": current_page}
                    Clock.schedule_once(lambda dt, key_value={}: __update_page(
                        key_val=key_val))
                for slide in comic_book_carousel.slides:
                    for child in slide.walk():
                        if child.id is not None:
                            if "comic_scatter" in child.id:
                                if child.zoom_state == "zoomed":
                                    child.do_zoom(False)
        else:

            def updated_progress(results):
                pass

            if index is not None:
                comic_book_carousel = self.ids.comic_book_carousel
                current_page = comic_book_carousel.current_slide.comic_page
                comic_obj = self.comic_obj
                comic_Id = comic_obj.Id
                update_url = f"{self.app.api_url}/Comics/{comic_Id}/Progress"
                if current_page > self.comic_obj.UserLastPageRead:
                    key_val = {
                        "UserLastPageRead": current_page,
                        "UserCurrentPage": current_page,
                    }
                else:
                    key_val = {"UserCurrentPage": current_page}
                Clock.schedule_once(
                    lambda dt, key_value={}: __update_page(key_val=key_val))
                self.fetch_data.update_progress(
                    update_url,
                    current_page,
                    callback=lambda req, results: updated_progress(results),
                )
                server_readinglists_screen = self.app.manager.get_screen(
                    "server_readinglists_screen")
                server_readinglists_screen.page_turn(self.comic_obj.Id,
                                                     current_page)
                for slide in comic_book_carousel.slides:
                    for child in slide.walk():
                        try:
                            if child.id is not None:
                                if "comic_scatter" in child.id:
                                    if child.zoom_state == "zoomed":
                                        child.do_zoom(False)
                        except AttributeError:
                            pass

    def add_pages(self, comic_book_carousel, outer_grid, comic_obj, i):
        t_api_key = self.app.config.get("General", "api_key")

        # fire off dblpage split if server replies size of image is
        # width>height

        def got_page_size(results):
            Logger.debug(results)
            if results["width"] > results["height"]:
                Logger.debug("Size thing Triggered")
                comic_page_image.proxyImage = Loader.image(comic_page_source,
                                                           nocache=True)
                if comic_page_image.proxyImage.loaded:
                    comic_page_image._new_image_downloaded(
                        comic_page_scatter,
                        outer_grid,
                        comic_obj,
                        i,
                        comic_page_source,
                        comic_page_image.proxyImage,
                    )
                else:
                    comic_page_image.proxyImage.bind(on_load=partial(
                        comic_page_image._new_image_downloaded,
                        comic_page_scatter,
                        outer_grid,
                        comic_obj,
                        i,
                        comic_page_source,
                    ))

        strech_image = App.get_running_app().config.get(
            "Display", "stretch_image")

        max_height = App.get_running_app().config.get("Display", "max_height")
        comic_page_scatter = ComicBookPageScatter(
            id="comic_scatter" + str(i),
            comic_page=i,
            do_rotation=False,
            do_translation=False,
            size_hint=(1, 1),
            auto_bring_to_front=True,
            scale_min=1,
        )
        if strech_image == "1":
            s_allow_stretch = True
            s_keep_ratio = False
        else:
            s_allow_stretch = False
            s_keep_ratio = True
        if max_height == "Use Original Size":
            s_url_part = f"/Comics/{comic_obj.Id}/Pages/{i}"
            s_url_api = f"?apiKey={t_api_key}"
        elif max_height == "Use Window Size":
            h = round(dp(Window.height))
            # w = round(dp(Window.height))
            s_url_part = f"/Comics/{comic_obj.Id}/Pages/{i}?height={h}"
            s_url_api = f"&apiKey={t_api_key}"
        else:
            s_max_height = round(dp(max_height))
            s_url_part = (
                f"/Comics/{comic_obj.Id}/Pages/{i}?height={s_max_height}")
            s_url_api = f"&apiKey={t_api_key}"
        if self.view_mode == "FileOpen" or self.comic_obj.is_sync:
            comic_page_source = get_comic_page(comic_obj, i)
        else:
            comic_page_source = f"{self.app.api_url}{s_url_part}{s_url_api}"
        comic_page_image = ComicBookPageImage(
            comic_slug=comic_obj.slug,
            id="pi_" + str(i),
            allow_stretch=s_allow_stretch,
            keep_ratio=s_keep_ratio,
            comic_page=i,
            source=comic_page_source,
        )
        comic_page_scatter.add_widget(comic_page_image)
        comic_book_carousel.add_widget(comic_page_scatter)
        # Let's make the thumbs for popup
        s_height = round(dp(240))

        s_url_part = f"/Comics/{comic_obj.Id}/Pages/{i}?height={s_height}"
        s_url_api = f"&apiKey={t_api_key}"
        if self.view_mode == "FileOpen" or comic_obj.is_sync:
            src_img = get_comic_page(comic_obj, i)
        else:
            src_img = f"{self.app.api_url}{s_url_part}{s_url_api}"
        inner_grid = ThumbPopPageInnerGrid(id="inner_grid" + str(i),
                                           spacing=(0, 0))
        page_thumb = ComicBookPageThumb(
            comic_slug=comic_obj.slug,
            id="page_thumb" + str(i),
            comic_page=i,
            source=src_img,
            allow_stretch=True,
        )

        page_thumb.size_hint_y = None
        page_thumb.height = dp(240)
        inner_grid.add_widget(page_thumb)
        page_thumb.bind(on_release=page_thumb.click)
        smbutton = ThumbPopPagebntlbl(
            text="P%s" % str(i + 1),
            elevation_normal=2,
            padding=(1, 1),
            id=f"page_thumb_lbl{i}",
            comic_slug=comic_obj.slug,
            comic_page=i,
            text_color=(0, 0, 0, 1),
        )
        inner_grid.add_widget(smbutton)
        smbutton.bind(on_release=smbutton.click)
        outer_grid.add_widget(inner_grid)
        if comic_obj.PageCount - 1 == i:
            self.load_UserCurrentPage()
        s_url_part = f"/Comics/{comic_obj.Id}/Pages/{i}/size"
        get_size_url = f"{self.app.api_url}{s_url_part}"
        if self.view_mode == "FileOpen" or self.comic_obj.is_sync:
            width, height = get_file_page_size(comic_page_source)
            data = {"width": width, "height": height}
            got_page_size(data)
        else:
            self.fetch_data.get_page_size_data(
                get_size_url,
                callback=lambda req, results: got_page_size(results),
            )
        # proxyImage = Loader.image(comic_page_source,nocache=True)
        # proxyImage.bind(on_load=partial(
        #                                comic_page_image._new_image_downloaded,
        #                                 comic_page_scatter,outer_grid,comic_obj,
        #                                 i,comic_page_source
        #                                 )
        #                 )
        if comic_obj.PageCount - 1 == i:
            self.last_page_done = True
            self.load_UserCurrentPage()

    def page_nav_popup_open(self):
        self.page_nav_popup.open()
        comic_book_carousel = self.ids.comic_book_carousel
        current_slide = comic_book_carousel.current_slide
        for child in self.walk():
            try:
                if child.id == current_slide.id:
                    current_page = child
                    comic_page = current_page.comic_page
            except AttributeError:
                pass
        # scroller = self.dynamic_ids['page_thumb_scroll']
        # for grandchild in scroller.walk():
        #             c_page_thumb = f'page_thumb{comic_page}'
        #             c_page_lbl = f'page_thumb_lbl{comic_page}'
        #             if grandchild.id == c_page_thumb:
        #                 target_thumb = grandchild
        #                 self.scroller.scroll_to(
        #                     target_thumb, padd7ing=10, animate=True)
        for child in self.page_nav_popup.walk():
            try:
                if child.id == "page_thumb_scroll":
                    scroller = child
                    for grandchild in scroller.walk():
                        c_page_thumb = f"page_thumb{comic_page}"
                        if grandchild.id == c_page_thumb:
                            target_thumb = grandchild
                            self.scroller.scroll_to(target_thumb,
                                                    padding=10,
                                                    animate=True)
            except AttributeError:
                pass

    def build_top_nav(self):
        """
        Build the top popup that contains the readnglist comics
        and links via cover image to open
        them
        """
        t_api_key = self.app.config.get("General", "api_key")
        scroll = CommonComicsScroll(
            id="page_thumb_scroll",
            size_hint=(1, 1),
            do_scroll_x=True,
            do_scroll_y=False,
        )
        self.top_pop = MyPopup(
            id="page_pop",
            title="Comics in List",
            title_align="center",
            content=scroll,
            pos_hint={"top": 1},
            size_hint=(1, None),
            height=round(dp(325)),
        )
        self.top_pop
        grid = CommonComicsOuterGrid(
            id="outtergrd",
            size_hint=(None, None),
            spacing=5,
            padding=(5, 5, 5, 5),
        )
        grid.bind(minimum_width=grid.setter("width"))
        if self.current_page is None:
            if self.pag_pagenum == 0:
                page = self.paginator_obj.page(1)
                c_pag_pagenum = page.number
            else:
                page = self.paginator_obj.page(self.pag_pagenum)
            comics_list = page.object_list
            self.current_page = page
            c_pag_pagenum = page.number
            page_num = self.paginator_obj.num_pages()
            c_readinglist_name = self.readinglist_obj.name
            group_str = f" - Page# {page.number} of {page_num}"
            c_title = f"{c_readinglist_name}{group_str}"
            self.top_pop.title = c_title
        else:
            page = self.current_page
            c_pag_pagenum = page.number
            page_num = self.paginator_obj.num_pages()
            c_readinglist_name = self.readinglist_obj.name
            group_str = f" - Page# {page.number} of {page_num}"
            c_title = f"{c_readinglist_name}{group_str}"
            self.top_pop.title = c_title
            comics_list = page.object_list
        if page.has_previous():
            comic_name = "Prev Page"
            src_thumb = "assets/prev_page.jpg"
            inner_grid = CommonComicsCoverInnerGrid(id="inner_grid" +
                                                    str("prev"),
                                                    padding=(1, 1, 1, 1))
            comic_thumb = CommonComicsCoverImage(source=src_thumb,
                                                 id=str("prev"))
            if self.view_mode == "FileOpen":
                comic_thumb.mode = "FileOpen"
            elif self.view_mode == "Sync":
                comic_thumb.mode = "Sync"
            comic_thumb.readinglist_obj = self.readinglist_obj
            comic_thumb.paginator_obj = self.paginator_obj
            comic_thumb.new_page_num = page.previous_page_number()
            inner_grid.add_widget(comic_thumb)
            comic_thumb.bind(on_release=self.top_pop.dismiss)
            comic_thumb.bind(on_release=self.load_new_page)
            # smbutton = CommonComicsCoverLabel(text=comic_name)
            smbutton = ThumbPopPagebntlbl(
                text=comic_name,
                elevation_normal=2,
                padding=(1, 1),
                id=f"comic_lbl_prev",
                comic_slug="Prev Comic",
                font_size=10.5,
                text_color=(0, 0, 0, 1),
            )
            inner_grid.add_widget(smbutton)
            smbutton.bind(on_release=self.top_pop.dismiss)
            smbutton.bind(on_release=self.load_new_page)
            grid.add_widget(inner_grid)
        for comic in comics_list:
            if (comic.is_sync
                    or (self.view_mode != "Sync" and comic.is_sync is False)
                    or self.view_mode == "FileOpen"):
                comic_name = str(comic.__str__)
                s_url_part = f"/Comics/{comic.Id}/Pages/0?height={round(dp(240))}"  # noqa
                s_url_api = f"&apiKey={t_api_key}"
                if self.view_mode == "FileOpen" or (self.view_mode == "Sync"
                                                    and comic.is_sync):
                    src_thumb = get_comic_page(comic, 0)
                else:
                    src_thumb = f"{self.app.api_url}{s_url_part}{s_url_api}"
                inner_grid = CommonComicsCoverInnerGrid(id="inner_grid" +
                                                        str(comic.Id),
                                                        padding=(0, 0, 0, 0))
                comic_thumb = CommonComicsCoverImage(source=src_thumb,
                                                     id=str(comic.Id),
                                                     comic_obj=comic)
                if self.view_mode == "FileOpen":
                    comic_thumb.mode = "FileOpen"
                elif self.view_mode == "Sync":
                    comic_thumb.mode = "Sync"
                comic_thumb.readinglist_obj = self.readinglist_obj
                comic_thumb.paginator_obj = self.paginator_obj
                comic_thumb.new_page_num = c_pag_pagenum
                comic_thumb.comic_obj = comic
                inner_grid.add_widget(comic_thumb)
                comic_thumb.bind(on_release=self.top_pop.dismiss)
                comic_thumb.bind(on_release=comic_thumb.open_collection)
                # smbutton = CommonComicsCoverLabel(text=comic_name)
                smbutton = ThumbPopPagebntlbl(
                    text=comic_name,
                    elevation_normal=2,
                    padding=(1, 1),
                    id=f"comic_lbl{comic.Id}",
                    comic_slug=comic.slug,
                    font_size=10.5,
                    text_color=(0, 0, 0, 1),
                )
                inner_grid.add_widget(smbutton)
                smbutton.bind(on_release=self.top_pop.dismiss)
                smbutton.bind(on_release=comic_thumb.open_collection)
                grid.add_widget(inner_grid)
        if page.has_next():
            comic_name = "Next Page"
            src_thumb = "assets/next_page.jpg"
            inner_grid = CommonComicsCoverInnerGrid(id="inner_grid" +
                                                    str("next"))
            comic_thumb = CommonComicsCoverImage(source=src_thumb,
                                                 id=str("next"))
            comic_thumb.readinglist_obj = self.readinglist_obj
            comic_thumb.new_page_num = page.next_page_number()
            comic_thumb.paginator_obj = self.paginator_obj
            inner_grid.add_widget(comic_thumb)
            comic_thumb.bind(on_release=self.top_pop.dismiss)
            comic_thumb.bind(on_release=self.load_new_page)
            # smbutton = CommonComicsCoverLabel(text=comic_name)
            smbutton = ThumbPopPagebntlbl(
                text=comic_name,
                elevation_normal=2,
                padding=(1, 1),
                id=f"comic_lbl_next",
                comic_slug="Next Comic",
                font_size=10.5,
                text_color=(0, 0, 0, 1),
            )
            inner_grid.add_widget(smbutton)
            smbutton.bind(on_release=self.top_pop.dismiss)
            smbutton.bind(on_release=self.load_new_page)
            grid.add_widget(inner_grid)
        scroll.add_widget(grid)

    def comicscreen_open_collection_popup(self):
        self.top_pop.open()

    def load_new_page(self, instance):
        new_page = self.paginator_obj.page(instance.new_page_num)
        self.current_page = new_page

        self.build_top_nav()
        self.top_pop.open()

    def load_next_page_comic(self, instance):
        new_page = self.paginator_obj.page(instance.new_page_num)
        self.current_page = new_page
        c_pag_pagenum = new_page.number
        screen = self.app.manager.get_screen("comic_book_screen")
        screen.setup_screen(
            readinglist_obj=self.readinglist_obj,
            paginator_obj=self.paginator_obj,
            pag_pagenum=c_pag_pagenum,
            comic_obj=self.next_comic,
            view_mode=self.view_mode,
        )
        self.app.manager.current = "comic_book_screen"

    def load_prev_page_comic(self, instance):
        new_page = self.paginator_obj.page(instance.new_page_num)
        self.current_page = new_page
        c_pag_pagenum = new_page.number
        screen = self.app.manager.get_screen("comic_book_screen")
        screen.setup_screen(
            readinglist_obj=self.readinglist_obj,
            paginator_obj=self.paginator_obj,
            pag_pagenum=c_pag_pagenum,
            comic_obj=self.prev_comic,
            view_mode=self.view_mode,
        )

    def get_next_comic(self):
        n_paginator = self.paginator_obj
        page = self.current_page
        comic_obj = self.comic_obj
        comics_list = page.object_list
        for x in comics_list:
            if str(x.Id) == str(comic_obj.Id):
                index = comics_list.index(x)
        if comic_obj.Id == comics_list[-1].Id and page.has_next():
            n_page = n_paginator.page(page.next_page_number())
            comics_list = n_page.object_list
            next_comic = comics_list[0]
        else:
            if index >= len(comics_list) - 1:
                if len(comics_list) <= 1 or self.use_sections is True:
                    next_comic = self.comic_obj
                else:
                    next_comic = comics_list[index]
            else:
                if len(comics_list) <= 1 or self.use_sections is True:
                    next_comic = self.comic_obj
                else:
                    next_comic = comics_list[index + 1]
        return next_comic

    # TODO Fix when 1 comic is loaded there should not be a
    # next and prev comic.
    def get_prev_comic(self):
        n_paginator = self.paginator_obj
        page = self.current_page
        comics_list = page.object_list
        comic_obj = self.comic_obj
        for x in comics_list:
            if x.Id == comic_obj.Id:
                index = comics_list.index(x)
        if comic_obj.Id == comics_list[0].Id and page.has_previous():
            n_page = n_paginator.page(page.previous_page_number())
            comics_list = n_page.object_list
            prev_comic = comics_list[-1]
        else:
            if index < len(comics_list):
                if index == 0:
                    if self.section == "Section" or self.section == "Last":
                        prev_comic = self.comic_obj

                    else:
                        prev_comic = comics_list[index]
                else:
                    if self.section == "Section" or self.section == "Last":
                        prev_comic = self.comic_obj
                    else:
                        prev_comic = comics_list[index - 1]
        return prev_comic

    def build_next_comic_dialog(self):
        """ Make popup showing cover for next comic"""
        n_paginator = self.paginator_obj
        page = self.current_page
        comics_list = page.object_list
        comic = self.next_comic
        comic_obj = self.comic_obj
        for x in comics_list:
            if x.Id == comic_obj.Id:
                index = comics_list.index(x)
        if index + 1 == len(comics_list) and page.has_next():
            n_page = n_paginator.page(page.next_page_number())
            comics_list = n_page.object_list
            next_page_number = page.next_page_number()
            c_new_page_num = next_page_number
        else:
            c_new_page_num = page.number
        comic_name = str(comic.__str__)
        t_api_key = self.app.config.get("General", "api_key")
        s_url_part = f"/Comics/{comic.Id}/Pages/0?height={round(dp(240))}"
        s_url_api = f"&apiKey={t_api_key}"
        if self.view_mode == "FileOpen" or comic.is_sync:
            src_thumb = get_comic_page(comic, 0)
        else:
            src_thumb = f"{self.app.api_url}{s_url_part}{s_url_api}"

        inner_grid = CommonComicsCoverInnerGrid(
            id="inner_grid" + str(comic.Id),
            pos_hint={
                "top": 0.99,
                "right": 0.1
            },
        )

        comic_thumb = CommonComicsCoverImage(source=src_thumb,
                                             id=str(comic.Id),
                                             comic_obj=comic)
        if self.view_mode == "FileOpen":
            comic_thumb.mode = "FileOpen"
        comic_thumb.readinglist_obj = self.readinglist_obj
        comic_thumb.comic = comic
        comic_thumb.last_load = self.last_load
        if self.use_sections:
            comic_thumb.last_section = self.last_section
        comic_thumb.paginator_obj = self.paginator_obj
        comic_thumb.new_page_num = c_new_page_num
        inner_grid.add_widget(comic_thumb)

        smbutton = ThumbPopPagebntlbl(text=comic_name,
                                      font_size=12,
                                      text_color=(0, 0, 0, 1))
        inner_grid.add_widget(smbutton)
        content = inner_grid
        if index >= len(comics_list) - 1:
            if self.use_sections:
                dialog_title = "Load Next Section"
            else:
                if index + 1 == page.end_index():
                    dialog_title = "Load Next Page"
                else:
                    dialog_title = "On Last Comic"
        else:
            if self.use_sections:
                dialog_title = "Load Next Section"
            else:
                if index + 1 == page.end_index():
                    dialog_title = "Load Next Page"
                else:
                    dialog_title = "Load Next Comic"

        self.next_dialog = MyPopup(
            id="next_pop",
            title=dialog_title,
            content=content,
            pos_hint={0.5: 0.724},
            size_hint=(None, None),
            size=(dp(280), dp(340)),
        )
        self.next_dialog.bind(on_dismiss=self.next_dialog_closed)
        c_padding = self.next_dialog.width / 4
        CommonComicsCoverInnerGrid.padding = (c_padding, 0, 0, 0)
        comic_thumb.bind(on_release=self.close_next_dialog)
        self.next_nav_comic_thumb = comic_thumb
        # if index >= len(comics_list)-1:
        #     if self.use_sections:
        #         comic_thumb.bind(on_release=comic_thumb.open_next_section)
        #     else:
        #         if len(comics_list) >= 1:
        #             comic_thumb.bind(on_release=self.load_next_page_comic)
        #         else:
        #             return
        # else:
        #     if self.use_sections:
        #         comic_thumb.bind(on_release=comic_thumb.open_next_section)
        #     else:
        #         if len(comics_list) >= 1:
        #             comic_thumb.bind(on_release=self.load_next_page_comic)
        #         else:
        #             comic_thumb.bind(on_release=comic_thumb.open_collection)

        if index >= len(comics_list) - 1:
            if self.use_sections:
                comic_thumb.action_do = "open_next_section"
                comic_thumb.bind(on_release=comic_thumb.do_action)
            else:
                if len(comics_list) >= 1:
                    comic_thumb.action_do = "load_next_page_comic"
                    comic_thumb.bind(on_release=self.load_next_page_comic)
                else:
                    return
        else:
            if self.use_sections:
                comic_thumb.action_do = "open_next_section"
                comic_thumb.bind(on_release=comic_thumb.do_action)
            else:
                if len(comics_list) >= 1:
                    comic_thumb.action_do = "load_next_page_comic"
                    comic_thumb.bind(on_release=self.load_next_page_comic)
                else:
                    comic_thumb.action_do = "open_collection"
                    comic_thumb.bind(on_release=comic_thumb.do_action)

    def build_prev_comic_dialog(self):
        t_api_key = self.app.config.get("General", "api_key")
        n_paginator = self.paginator_obj
        page = self.current_page
        comics_list = page.object_list
        comic = self.prev_comic
        comic_obj = self.comic_obj
        for x in comics_list:
            if x.Id == comic_obj.Id:
                index = comics_list.index(x)
        prev_page_number = 1
        if index == 0 and page.has_previous():
            n_page = n_paginator.page(page.previous_page_number())
            comics_list = n_page.object_list
            prev_page_number = page.previous_page_number()
        comic_name = str(comic.__str__)
        s_url_part = f"/Comics/{comic.Id}/Pages/0?height={round(dp(240))}"
        s_url_api = f"&apiKey={t_api_key}"
        if self.view_mode == "FileOpen" or (self.view_mode == "Sync"
                                            and comic.is_sync):
            src_thumb = get_comic_page(comic, 0)
        else:
            src_thumb = f"{self.app.api_url}{s_url_part}{s_url_api}"
        inner_grid = CommonComicsCoverInnerGrid(
            id="inner_grid" + str(comic.Id),
            pos_hint={
                "top": 0.99,
                "right": 0.1
            },
        )
        comic_thumb = CommonComicsCoverImage(
            source=src_thumb,
            id=str(comic.Id),
            pos_hint={0.5: 0.5},
            comic_obj=comic,
        )
        if self.view_mode == "FileOpen":
            comic_thumb.mode = "FileOpen"
        elif self.view_mode == "Sync":
            comic_thumb.mode = "Sync"
        comic_thumb.readinglist_obj = self.readinglist_obj
        comic_thumb.comic = comic
        if self.use_sections:
            comic_thumb.last_section = self.last_section
        if index == 0 and page.has_previous():
            comic_thumb.new_page_num = prev_page_number
        else:
            comic_thumb.new_page_num = page.number
        comic_thumb.readinglist_obj = self.readinglist_obj
        inner_grid.add_widget(comic_thumb)

        smbutton = ThumbPopPagebntlbl(text=comic_name,
                                      font_size=12,
                                      text_color=(0, 0, 0, 1))
        inner_grid.add_widget(smbutton)
        content = inner_grid
        if index >= len(comics_list) - 1:
            if len(comics_list) >= 1:
                dialog_title = "Load Prev Page"
            else:
                dialog_title = "On First Comic"
        else:
            if index != 0:
                dialog_title = "Load Prev Page"
            else:
                dialog_title = "On First Comic"
        self.prev_dialog = MyPopup(
            id="prev_pop",
            title=dialog_title,
            content=content,
            pos_hint={0.5: 0.724},
            size_hint=(0.4, 0.34),
        )
        self.prev_dialog.bind(on_dismiss=self.prev_dialog_closed)
        c_padding = self.prev_dialog.width / 4
        CommonComicsCoverInnerGrid.padding = (c_padding, 0, 0, 0)
        comic_thumb.bind(on_release=self.prev_dialog.dismiss)
        self.prev_nav_comic_thumb = comic_thumb
        if index < len(comics_list):
            if index == 0:
                if self.use_sections and self.section != "First":
                    comic_thumb.action_do = "open_prev_section"
                    comic_thumb.bind(on_release=comic_thumb.do_action)
                else:
                    if len(comics_list) > 1:
                        comic_thumb.action_do = "load_prev_page_comic"
                        comic_thumb.bind(on_release=self.load_prev_page_comic)
                    else:
                        return
            else:
                if self.use_sections and self.section != "First":
                    comic_thumb.action_do = "open_prev_section"
                    comic_thumb.bind(on_release=comic_thumb.do_action)
                else:
                    if len(comics_list) > 1:
                        comic_thumb.action_do = "load_prev_page_comic"
                        comic_thumb.bind(on_release=self.load_prev_page_comic)
                    else:
                        comic_thumb.action_do = "open_collection"
                        comic_thumb.bind(on_release=comic_thumb.do_action)

    def open_next_dialog(self):
        toast("At last page open next comic")
        self.next_dialog.open()

    def next_dialog_closed(self, *args):
        self.next_dialog_open = False

    def close_next_dialog(self, *args):
        try:
            self.next_dialog.dismiss()
            self.next_dialog_open = False
        except Exception:
            pass

    def open_prev_dialog(self):
        toast("At first page open prev comic")
        self.prev_dialog.open()

    def prev_dialog_closed(self, *args):
        self.next_dialog_open = False

    def close_prev_dialog(self, *args):
        try:
            self.prev_dialog.dismiss()
            self.prev_dialog_open = False
        except Exception:
            pass

    def load_random_comic(self):
        next_screen_name = self.app.manager.next()
        self.app.manager.current = next_screen_name

    def load_next_slide(self):
        comic_book_carousel = self.ids.comic_book_carousel
        comic_scatter = comic_book_carousel.current_slide
        if self.use_sections:
            if comic_book_carousel.next_slide is None:
                if self.next_dialog_open is False:
                    self.open_next_dialog()
                    self.next_dialog_open = True
                else:
                    x = self.next_nav_comic_thumb
                    if x.action_do == "load_next_page_comic":
                        self.load_next_page_comic(self.next_nav_comic_thumb)
                    else:
                        self.next_nav_comic_thumb.do_action()
                    self.close_next_dialog()
                return
            else:
                comic_book_carousel.load_next()
                return
        else:
            if (self.comic_obj.PageCount - 1 == comic_scatter.comic_page
                    and comic_book_carousel.next_slide is None):
                if self.next_dialog_open is False:
                    self.open_next_dialog()
                    self.next_dialog_open = True
                else:
                    x = self.next_nav_comic_thumb
                    if x.action_do == "load_next_page_comic":
                        self.load_next_page_comic(self.next_nav_comic_thumb)
                    else:
                        self.next_nav_comic_thumb.do_action()
                    self.close_next_dialog()
                return
            else:
                comic_book_carousel.load_next()

    def load_prev_slide(self):
        comic_book_carousel = self.ids.comic_book_carousel
        comic_scatter = comic_book_carousel.current_slide
        if self.use_sections:
            if comic_book_carousel.previous_slide is None:
                if self.prev_dialog_open is False:
                    self.open_prev_dialog()
                    self.prev_dialog_open = True
                else:
                    x = self.next_nav_comic_thumb
                    if x.action_do == "load_prev_page_comic":
                        self.load_prev_page_comic(self.prev_nav_comic_thumb)
                    else:
                        self.prev_nav_comic_thumb.do_action()
                    self.close_prev_dialog()
                return
            else:
                comic_book_carousel.load_previous()
                return
        else:
            if (comic_scatter.comic_page == 0
                    and comic_book_carousel.previous_slide is None):
                if self.prev_dialog_open is False:
                    self.open_prev_dialog()
                    self.prev_dialog_open = True
                else:
                    x = self.next_nav_comic_thumb
                    if x.action_do == "load_prev_page_comic":
                        self.load_prev_page_comic(self.prev_nav_comic_thumb)
                    else:
                        self.prev_nav_comic_thumb.do_action()
                    self.close_prev_dialog()
                return
            else:
                comic_book_carousel.load_previous()
                return
                ######

    # def build_option_pop(self):
    #     def call_back_dismiss(instance):
    #         self.option_isopen = False

    #     option_bar = OptionToolBar(comic_Id=self.comic_obj.Id)
    #     self.option_pop = ModalView(
    #         pos_hint={"top": 1}, size_hint=(1, None), height=option_bar.height
    #     )
    #     self.option_pop.add_widget(option_bar)
    #     self.option_pop.bind(on_dismiss=call_back_dismiss)

    def toggle_option_bar(self):
        if self.option_isopen is True:
            self.app.hide_action_bar()
            # self.option_pop.dismiss()
            self.option_isopen = False
        else:
            self.app.show_action_bar()
            # self.option_pop.open()
            self.option_isopen = True
Exemple #18
0
class ServerListsScreen(Screen):
    base_url = StringProperty()
    api_url = StringProperty()

    def __init__(self, **kwargs):
        super(ServerListsScreen, self).__init__(**kwargs)
        self.lists_loaded = BooleanProperty()
        self.lists_loaded = False
        self.app = App.get_running_app()
        self.fetch_data = None
        self.Data = ""
        self.fetch_data = ComicServerConn()
        self.base_url = self.app.base_url
        self.api_url = self.app.api_url

    def on_pre_enter(self):
        self.app.show_action_bar()

    def on_enter(self, *args):
        self.base_url = self.app.base_url
        self.api_url = self.app.api_url
        if self.lists_loaded is False:
            self.get_comicrack_list()
        self.app.set_screen("ComicRack Lists")

    def on_leave(self):
        self.app.list_previous_screens.append(self.name)

    def get_comicrack_list(self):
        if self.lists_loaded is False:
            url_send = f"{self.api_url}/lists/"
            self.fetch_data.get_server_data(url_send, self)

    def node_expand(self, instance, node):
        node.icon = "folder-open"

    def node_collapse(self, instance, node):
        node.icon = "folder"

    def do_expand(self, instance, node):
        self.my_tree.toggle_node(instance)

    def callback_for_menu_items(self, *args):
        toast(args[0])

    def open_readinglist(self, instance, node):
        def __wait_for_open(dt):
            if server_readinglists_screen.loading_done is True:
                self.app.manager.current = "server_readinglists_screen"
                self.loading_event.cancel()

        server_readinglists_screen = self.app.manager.get_screen(
            "server_readinglists_screen")
        server_readinglists_screen.setup_screen()
        server_readinglists_screen.page_number = 1
        readinglist_Id = instance.id
        readinglist_name = (instance.text).split(" : ")[0]
        server_readinglists_screen.list_loaded = False
        query = ReadingList.select().where(ReadingList.slug == readinglist_Id)
        if query.exists():
            Logger.info(f"{readinglist_name} already in Database")
            set_mode = "From DataBase"
        else:
            Logger.info("{} not in Database getting info from server".format(
                readinglist_name))
            set_mode = "From Server"
        # set_mode = 'From Server'
        server_readinglists_screen.loading_done = False
        Clock.schedule_once(
            lambda dt: server_readinglists_screen.collect_readinglist_data(
                readinglist_name=readinglist_name,
                readinglist_Id=readinglist_Id,
                mode=set_mode,
            ))
        self.app.manager.current = "server_readinglists_screen"
        # self.loading_event = Clock.schedule_interval(__wait_for_open, 0.25)

    def got_json(self, req, result):
        self.ids.mytv.clear_widgets()
        self.my_tree = self.ids.mytv
        self.my_tree.clear_widgets()
        self.my_tree.bind(minimum_height=self.my_tree.setter("height"))
        self.my_tree.bind(on_node_expand=self.node_expand)
        self.my_tree.bind(on_node_collapse=self.node_collapse)
        for item in result:
            if item["Name"] != "Library":
                if (item["Type"] == "ComicLibraryListItem"
                        or item["Type"] == "ComicSmartListItem"):
                    new_node = self.my_tree.add_node(
                        TreeViewItem(
                            text=item["Name"],
                            color=(
                                0.9568627450980393,
                                0.2627450980392157,
                                0.21176470588235294,
                                1,
                            ),
                            id=item["Id"],
                        ))
                    new_node.bind(on_touch_down=self.open_readinglist)
                elif item["Type"] == "ComicListItemFolder":
                    parent = self.my_tree.add_node(
                        TreeViewFolder(
                            text=item["Name"],
                            color=(
                                0.9568627450980393,
                                0.2627450980392157,
                                0.21176470588235294,
                                1,
                            ),
                            id=item["Id"],
                        ))
                    parent.bind(on_touch_down=self.do_expand)
                    self.set_files(parent, item["Lists"])
            self.lists_loaded = True

    def set_files(self, parent, child):
        for item in child:
            if (item["Type"] == "ComicLibraryListItem"
                    or item["Type"] == "ComicSmartListItem"
                    or item["Type"] == "ComicIdListItem"):
                new_node = self.my_tree.add_node(
                    TreeViewItem(
                        text=item["Name"],
                        color=(
                            0.9568627450980393,
                            0.2627450980392157,
                            0.21176470588235294,
                            1,
                        ),
                        id=item["Id"],
                    ),
                    parent,
                )
                new_node.bind(on_touch_down=self.open_readinglist)
            elif item["Type"] == "ComicListItemFolder":
                sub_parent = self.my_tree.add_node(
                    TreeViewFolder(
                        text=item["Name"],
                        color=(
                            0.9568627450980393,
                            0.2627450980392157,
                            0.21176470588235294,
                            1,
                        ),
                        id=item["Id"],
                    ),
                    parent,
                )
                sub_parent.bind(on_touch_down=self.do_expand)
                self.set_files(sub_parent, item["Lists"])