f7bbf7d9c8a2acec645c339a87966b5e869c7072
[kiosk.git] / gkeep_renderer.py
1 # -*- coding: utf-8 -*-
2
3 import gkeepapi
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: str, key) -> 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                 with file_writer.file_writer(filename) as f:
91                     f.write(
92                         f"""
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: {color}; color: #eeeeee; font-size: x-large;">
98 <p style="color: #ffffff; font-size:larger"><B>{note.title}</B></p>
99 <HR style="border-top: 3px solid white;">"""
100                     )
101                     if num_lines >= 12 and max_length < 120:
102                         self.debug_print(
103                             f"{num_lines} lines (max={max_length} chars): two columns"
104                         )
105                         f.write('<TABLE BORDER=0 WIDTH=100%><TR valign="top">')
106                         f.write(
107                             '<TD WIDTH=50% style="color:#eeeeee; font-size:large">\n'
108                         )
109                         f.write("<FONT><UL STYLE='list-style-type:none'>")
110                         count = 0
111                         for x in individual_lines:
112                             f.write(x + "\n")
113                             count += 1
114                             if count == num_lines / 2:
115                                 f.write("</UL></FONT></TD>\n")
116                                 f.write(
117                                     '<TD WIDTH=50% style="color:#eeeeee; font-size:large">\n'
118                                 )
119                                 f.write("<FONT><UL STYLE='list-style-type:none'>")
120                         f.write("</UL></FONT></TD></TR></TABLE></DIV>\n")
121                     else:
122                         self.debug_print(
123                             f"{num_lines} lines (max={max_length} chars): one column"
124                         )
125                         f.write(f"<FONT><UL>{contents}</UL></FONT>")
126                     f.write("</DIV>")
127             else:
128                 self.debug_print(f"Note is empty, deleting {filename}.")
129                 _ = os.path.join(constants.pages_dir, filename)
130                 try:
131                     os.remove(_)
132                 except:
133                     pass
134         return True
135
136
137 # Test
138 # x = gkeep_renderer({"Test", 1234})
139 # x.periodic_render("Test")