Changes.
[kiosk.git] / file_writer.py
1 #!/usr/bin/env python3
2
3 import logging
4 import os
5 from uuid import uuid4
6
7 import kiosk_constants
8
9
10 logger = logging.getLogger(__name__)
11
12
13 class file_writer:
14     """Helper context to write a pages file."""
15
16     def __init__(self, filename: str, *, transformations=[]):
17         temp = "temp-" + str(uuid4())
18         self.temp_filename = os.path.join(kiosk_constants.pages_dir, temp)
19         self.full_filename = os.path.join(kiosk_constants.pages_dir, filename)
20         self.xforms = [file_writer.remove_tricky_unicode]
21         self.xforms.extend(transformations)
22         self.f = None
23         logger.info(f"Writing {self.temp_filename}...")
24
25     @staticmethod
26     def remove_tricky_unicode(x: str) -> str:
27         try:
28             x = x.replace("\u2018", "'").replace("\u2019", "'")
29             x = x.replace("\u201c", '"').replace("\u201d", '"')
30             x = x.replace("\u2e3a", "-").replace("\u2014", "-")
31         except:
32             pass
33         return x
34
35     def write(self, data):
36         for xform in self.xforms:
37             data = xform(data)
38         self.f.write(data.encode("utf-8"))
39
40     def __enter__(self):
41         self.f = open(self.temp_filename, "wb")
42         return self
43
44     def __exit__(self, exc_type, exc_value, exc_traceback):
45         self.close()
46         logger.info(f"Copying {self.temp_filename} to {self.full_filename}")
47         cmd = f'/bin/mv -f {self.temp_filename} "{self.full_filename}"'
48         os.system(cmd)
49         print(cmd)
50
51     def done(self):
52         self.close()
53
54     def close(self):
55         self.f.close()
56
57
58 # Test
59 # def toupper(x):
60 #   return x.upper()
61
62 # with file_writer("test", transformations=[toupper]) as fw:
63 #   fw.write(u"Another test!!")