Somewhat large overhaul to move the kiosk towards using normal python
[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 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, secrets.google_keep_password
39         )
40         if success:
41             logger.debug("Connected with gkeep.")
42         else:
43             logger.debug("Error connecting with gkeep.")
44
45     def debug_prefix(self) -> str:
46         return "gkeep"
47
48     def periodic_render(self, key: str) -> bool:
49         strikethrough = re.compile("(\u2611[^\n]*)\n", re.UNICODE)
50         linkify = re.compile(r".*(https?:\/\/\S+).*")
51
52         self.keep.sync()
53         result_list = self.keep.find(labels=[self.keep.findLabel("kiosk")])
54         for note in result_list:
55             title = note.title
56             title = title.replace(" ", "-")
57             title = title.replace("/", "")
58
59             filename = f"{title}_2_3600.html"
60             contents = note.text + "\n"
61             logger.debug(f"Note title '{title}'")
62             if contents != "" and not contents.isspace():
63                 contents = strikethrough.sub("", contents)
64                 logger.debug(f"Note contents:\n{contents}")
65                 contents = contents.replace(
66                     "\u2610 ", '<LI><INPUT TYPE="checkbox">&nbsp;'
67                 )
68                 contents = linkify.sub(r'<a href="\1">\1</a>', contents)
69
70                 individual_lines = contents.split("\n")
71                 num_lines = len(individual_lines)
72                 max_length = 0
73                 contents = ""
74                 for x in individual_lines:
75                     length = len(x)
76                     if length > max_length:
77                         max_length = length
78                     leading_spaces = len(x) - len(x.lstrip(" "))
79                     leading_spaces //= 2
80                     leading_spaces = int(leading_spaces)
81                     x = x.lstrip(" ")
82                     # logger.debug(" * (%d) '%s'" % (leading_spaces, x))
83                     for y in range(0, leading_spaces):
84                         x = "<UL>" + x
85                     for y in range(0, leading_spaces):
86                         x = x + "</UL>"
87                     contents = contents + x + "\n"
88
89                 individual_lines = contents.split("\n")
90                 color = note.color.name.lower()
91                 if color in list(self.colors_by_name.keys()):
92                     color = self.colors_by_name[color]
93                 else:
94                     logger.debug(f"Unknown color '{color}'")
95                 print(f"TITLE: {color} {note.title}")
96                 with file_writer.file_writer(filename) as f:
97                     f.write("""
98 <STYLE type="text/css">
99   a:link { color:#88bfbf; }
100   ul { list-style-type:none; }
101 </STYLE>
102 <DIV STYLE="border-radius:25px; border-style:solid; padding:20px; background-color:%s; color:#eeeeee; font-size:x-large;">
103 """ % color
104                             )
105                     f.write(f"""
106 <p style="color:#ffffff; font-size:larger"><B>{note.title}</B></p>
107 <HR style="border-top:3px solid white;">
108 """
109                             )
110                     if num_lines >= 12 and max_length < 120:
111                         logger.debug(
112                             f"{num_lines} lines (max={max_length} chars): two columns"
113                         )
114                         f.write('<TABLE BORDER=0 WIDTH=100%><TR valign="top">')
115                         f.write(
116                             '<TD WIDTH=50% style="color:#eeeeee; font-size:large">\n'
117                         )
118                         f.write("<FONT><UL STYLE='list-style-type:none'>")
119                         count = 0
120                         for x in individual_lines:
121                             f.write(x + "\n")
122                             count += 1
123                             if count == num_lines / 2:
124                                 f.write("</UL></FONT></TD>\n")
125                                 f.write(
126                                     '<TD WIDTH=50% style="color:#eeeeee; font-size:large">\n'
127                                 )
128                                 f.write("<FONT><UL STYLE='list-style-type:none'>")
129                         f.write("</UL></FONT></TD></TR></TABLE></DIV>\n")
130                     else:
131                         logger.debug(
132                             f"{num_lines} lines (max={max_length} chars): one column"
133                         )
134                         f.write(f"<FONT><UL>{contents}</UL></FONT>")
135                     f.write("</DIV>")
136             else:
137                 logger.debug(f"Note is empty, deleting {filename}.")
138                 _ = os.path.join(constants.pages_dir, filename)
139                 try:
140                     os.remove(_)
141                 except:
142                     pass
143         return True
144
145
146 # Test
147 #x = gkeep_renderer({"Test", 1234})
148 #x.periodic_render("Test")