#!/usr/bin/env python3 import logging import os import re from typing import Dict import gkeepapi # type: ignore import kiosk_constants import file_writer import renderer import kiosk_secrets as secrets logger = logging.getLogger(__name__) class gkeep_renderer(renderer.abstaining_renderer): def __init__(self, name_to_timeout_dict: Dict[str, int]) -> None: super().__init__(name_to_timeout_dict) self.colors_by_name = { "white": "#002222", "green": "#345920", "darkblue": "#1F3A5F", "blue": "#2D545E", "orange": "#604A19", "red": "#5C2B29", "purple": "#42275E", "pink": "#5B2245", "yellow": "#635D19", "brown": "#442F19", "gray": "#3c3f4c", "teal": "#16504B", } self.keep = gkeepapi.Keep() self.token_file = "./.google_keep_token" if os.path.exists(self.token_file): logger.debug("Attempting to reuse persisted Google Keep login token...") try: with open(self.token_file, "r") as rf: token = "".join(rf.readlines()).strip() self.keep.resume(secrets.google_keep_username, token) logger.debug("Successfully reused existing login token.") except gkeepapi.exception.LoginException: logger.warning("Invalid token, attempting to re-login.") if not self.keep.login( secrets.google_keep_username, secrets.google_keep_password, secrets.google_keep_mac, ): raise Exception("Error connecting with Google Keep?!") logger.debug("Successfully logged in with Google Keep") def debug_prefix(self) -> str: return "gkeep" def periodic_render(self, key: str) -> bool: strikethrough = re.compile("(\u2611[^\n]*)\n", re.UNICODE) # linkify = re.compile(r".*(https?:\/\/\S+).*") self.keep.sync() result_list = self.keep.find(labels=[self.keep.findLabel("kiosk")]) for note in result_list: title = note.title title = title.replace(" ", "-") title = title.replace("/", "") filename = f"{title}_2_3600.html" contents = note.text + "\n" logger.debug(f"Note title '{title}'") if contents != "" and not contents.isspace(): contents = strikethrough.sub("", contents) logger.debug(f"Note contents:\n{contents}") contents = contents.replace( "\u2610 ", '
  •  ' ) # contents = linkify.sub(r'\1', contents) individual_lines = contents.split("\n") num_lines = len(individual_lines) contents = "" for x in individual_lines: leading_spaces = len(x) - len(x.lstrip(" ")) leading_spaces //= 2 leading_spaces = int(leading_spaces) x = x.lstrip(" ") # logger.debug(" * (%d) '%s'" % (leading_spaces, x)) for y in range(0, leading_spaces): x = "" contents = contents + x + "\n" individual_lines = contents.split("\n") color = note.color.name.lower() if color in list(self.colors_by_name.keys()): color = self.colors_by_name[color] else: logger.debug(f"Unknown color '{color}'") print(f"TITLE: {color} {note.title}") with file_writer.file_writer(filename) as f: f.write( """
    """ % color ) f.write( f"""

    {note.title}


    """ ) if num_lines >= 10: logger.debug(f"{num_lines} lines: two column mode") f.write('') f.write( '\n") f.write( '
    \n' ) f.write("
      ") count = 0 for x in individual_lines: f.write(x + "\n") count += 1 if count == num_lines / 2: f.write("
    \n' ) f.write("
      ") f.write("
    ") else: logger.debug(f"{num_lines} lines: one column mode") f.write(f"") f.write("") else: logger.debug(f"Note is empty, deleting {filename}.") _ = os.path.join(kiosk_constants.pages_dir, filename) try: os.remove(_) except: pass if self.token_file: token = self.keep.getMasterToken() os.umask(0) descriptor = os.open( path=self.token_file, flags=(os.O_WRONLY | os.O_CREAT | os.O_TRUNC), mode=0o600, ) with open(descriptor, "w") as wf: print(token, file=wf) logger.debug("Saved Google Keep token successfully.") return True # Test # logger.setLevel(logging.DEBUG) # ch = logging.StreamHandler() # ch.setLevel(logging.DEBUG) # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # ch.setFormatter(formatter) # logger.addHandler(ch) # x = gkeep_renderer({"Test", 1234}) # x.periodic_render("Test")