Convert to use pyutilz / scottutilz libraries.
[kiosk.git] / gkeep_renderer.py
1 #!/usr/bin/env python3
2
3 import logging
4 import os
5 import re
6 from typing import Dict
7
8 import gkeepapi  # type: ignore
9
10 import kiosk_constants
11 import file_writer
12 import renderer
13 import kiosk_secrets as secrets
14
15
16 logger = logging.getLogger(__file__)
17
18
19 class gkeep_renderer(renderer.abstaining_renderer):
20     def __init__(self, name_to_timeout_dict: Dict[str, int]) -> None:
21         super().__init__(name_to_timeout_dict)
22         self.colors_by_name = {
23             "white": "#002222",
24             "green": "#345920",
25             "darkblue": "#1F3A5F",
26             "blue": "#2D545E",
27             "orange": "#604A19",
28             "red": "#5C2B29",
29             "purple": "#42275E",
30             "pink": "#5B2245",
31             "yellow": "#635D19",
32             "brown": "#442F19",
33             "gray": "#3c3f4c",
34             "teal": "#16504B",
35         }
36         self.keep = gkeepapi.Keep()
37         success = self.keep.login(
38             secrets.google_keep_username,
39             secrets.google_keep_password,
40             secrets.google_keep_mac,
41         )
42         if success:
43             logger.debug("Connected with gkeep.")
44         else:
45             logger.debug("Error connecting with gkeep.")
46
47     def debug_prefix(self) -> str:
48         return "gkeep"
49
50     def periodic_render(self, key: str) -> bool:
51         strikethrough = re.compile("(\u2611[^\n]*)\n", re.UNICODE)
52         #linkify = re.compile(r".*(https?:\/\/\S+).*")
53
54         self.keep.sync()
55         result_list = self.keep.find(labels=[self.keep.findLabel("kiosk")])
56         for note in result_list:
57             title = note.title
58             title = title.replace(" ", "-")
59             title = title.replace("/", "")
60
61             filename = f"{title}_2_3600.html"
62             contents = note.text + "\n"
63             logger.debug(f"Note title '{title}'")
64             if contents != "" and not contents.isspace():
65                 contents = strikethrough.sub("", contents)
66                 logger.debug(f"Note contents:\n{contents}")
67                 contents = contents.replace(
68                     "\u2610 ", '<LI><INPUT TYPE="checkbox">&nbsp;'
69                 )
70                 #contents = linkify.sub(r'<a href="\1">\1</a>', contents)
71
72                 individual_lines = contents.split("\n")
73                 num_lines = len(individual_lines)
74                 contents = ""
75                 for x in individual_lines:
76                     leading_spaces = len(x) - len(x.lstrip(" "))
77                     leading_spaces //= 2
78                     leading_spaces = int(leading_spaces)
79                     x = x.lstrip(" ")
80                     # logger.debug(" * (%d) '%s'" % (leading_spaces, x))
81                     for y in range(0, leading_spaces):
82                         x = "<UL>" + x
83                     for y in range(0, leading_spaces):
84                         x = x + "</UL>"
85                     contents = contents + x + "\n"
86
87                 individual_lines = contents.split("\n")
88                 color = note.color.name.lower()
89                 if color in list(self.colors_by_name.keys()):
90                     color = self.colors_by_name[color]
91                 else:
92                     logger.debug(f"Unknown color '{color}'")
93                 print(f"TITLE: {color} {note.title}")
94                 with file_writer.file_writer(filename) as f:
95                     f.write("""
96 <STYLE type="text/css">
97   a:link { color:#88bfbf; }
98   ul { list-style-type:none; }
99 </STYLE>
100 <DIV STYLE="border-radius:25px; border-style:solid; padding:20px; background-color:%s; color:#eeeeee; font-size:x-large;">
101 """ % color
102                             )
103                     f.write(f"""
104 <p style="color:#ffffff; font-size:larger"><B>{note.title}</B></p>
105 <HR style="border-top:3px solid white;">
106 """
107                             )
108                     if num_lines >= 10:
109                         logger.debug(
110                             f"{num_lines} lines: two column mode"
111                         )
112                         f.write('<TABLE BORDER=0 WIDTH=100%><TR valign="top">')
113                         f.write(
114                             '<TD WIDTH=50% style="color:#eeeeee; font-size:large">\n'
115                         )
116                         f.write("<FONT><UL STYLE='list-style-type:none'>")
117                         count = 0
118                         for x in individual_lines:
119                             f.write(x + "\n")
120                             count += 1
121                             if count == num_lines / 2:
122                                 f.write("</UL></FONT></TD>\n")
123                                 f.write(
124                                     '<TD WIDTH=50% style="color:#eeeeee; font-size:large">\n'
125                                 )
126                                 f.write("<FONT><UL STYLE='list-style-type:none'>")
127                         f.write("</UL></FONT></TD></TR></TABLE></DIV>\n")
128                     else:
129                         logger.debug(
130                             f"{num_lines} lines: one column mode"
131                         )
132                         f.write(f"<FONT><UL>{contents}</UL></FONT>")
133                     f.write("</DIV>")
134             else:
135                 logger.debug(f"Note is empty, deleting {filename}.")
136                 _ = os.path.join(kiosk_constants.pages_dir, filename)
137                 try:
138                     os.remove(_)
139                 except:
140                     pass
141         return True
142
143
144 # Test
145 #logger.setLevel(logging.DEBUG)
146 #ch = logging.StreamHandler()
147 #ch.setLevel(logging.DEBUG)
148 #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
149 #ch.setFormatter(formatter)
150 #logger.addHandler(ch)
151 #x = gkeep_renderer({"Test", 1234})
152 #x.periodic_render("Test")