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