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