Piki is a minimal wiki
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

page.py 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. from django.conf import settings
  2. from django.utils.translation import gettext as _
  3. import fstools
  4. import json
  5. import logging
  6. from pages import messages, url_page
  7. import mycreole
  8. import os
  9. import shutil
  10. import time
  11. from . import timestamp_to_datetime
  12. logger = logging.getLogger(settings.ROOT_LOGGER_NAME).getChild(__name__)
  13. class meta_data(dict):
  14. KEY_CREATION_TIME = "creation_time"
  15. KEY_MODIFIED_TIME = "modified_time"
  16. KEY_MODIFIED_USER = "modified_user"
  17. def __init__(self, meta_filename, page_exists):
  18. self._meta_filename = meta_filename
  19. # Load data from disk
  20. try:
  21. with open(meta_filename, 'r') as fh:
  22. super().__init__(json.load(fh))
  23. except (FileNotFoundError, json.decoder.JSONDecodeError) as e:
  24. super().__init__()
  25. # Add missing information to meta_data
  26. missing_keys = False
  27. if self.KEY_CREATION_TIME not in self:
  28. missing_keys = True
  29. self[self.KEY_CREATION_TIME] = int(time.time())
  30. if self.KEY_MODIFIED_TIME not in self:
  31. self[self.KEY_MODIFIED_TIME] = self[self.KEY_CREATION_TIME]
  32. if missing_keys and page_exists:
  33. self.save()
  34. def update(self, username):
  35. self[self.KEY_MODIFIED_TIME] = int(time.time())
  36. self[self.KEY_MODIFIED_USER] = username
  37. #
  38. self.save()
  39. def save(self):
  40. with open(self._meta_filename, 'w') as fh:
  41. json.dump(self, fh, indent=4)
  42. class base_page(object):
  43. PAGE_FILE_NAME = 'page'
  44. META_FILE_NAME = 'meta.json'
  45. HISTORY_FOLDER_NAME = 'history'
  46. SPLITCHAR = ":"
  47. def __init__(self, path):
  48. if path.startswith(settings.PAGES_ROOT):
  49. self._path = path
  50. else:
  51. self._path = os.path.join(settings.PAGES_ROOT, path.replace("/", 2*self.SPLITCHAR))
  52. self._raw_page_src = None
  53. #
  54. self._meta_data = meta_data(self._meta_filename, self.is_available())
  55. def _load_page_src(self):
  56. if self._raw_page_src is None:
  57. try:
  58. with open(self.filename, 'r') as fh:
  59. self._raw_page_src = fh.read()
  60. except FileNotFoundError:
  61. self._raw_page_src = ""
  62. def _store_history(self):
  63. history_folder = os.path.join(self._path, self.HISTORY_FOLDER_NAME)
  64. # create folder if needed
  65. fstools.mkdir(history_folder)
  66. # identify last_history number
  67. flist = fstools.filelist(history_folder)
  68. flist.sort()
  69. if flist:
  70. hist_number = int(os.path.basename(flist[-1])[:5]) + 1
  71. else:
  72. hist_number = 1
  73. # copy file to history folder
  74. shutil.copy(self.filename, os.path.join(history_folder, "%05d_%s" % (hist_number, self.PAGE_FILE_NAME)))
  75. shutil.copy(self._meta_filename, os.path.join(history_folder, "%05d_%s" % (hist_number, self.META_FILE_NAME)))
  76. def update_page(self, page_txt):
  77. from .search import update_item
  78. if page_txt.replace("\r\n", "\n") != self.raw_page_src:
  79. # Store page history
  80. if self.raw_page_src:
  81. self._store_history()
  82. # save the new page content
  83. fstools.mkdir(os.path.dirname(self.filename))
  84. with open(self.filename, 'w') as fh:
  85. fh.write(page_txt)
  86. # update search index
  87. update_item(self)
  88. # update metadata
  89. self._update_metadata()
  90. return True
  91. return False
  92. @property
  93. def filename(self):
  94. return os.path.join(self._path, self.PAGE_FILE_NAME)
  95. @property
  96. def _meta_filename(self):
  97. return os.path.join(self._path, self.META_FILE_NAME)
  98. @property
  99. def rel_path(self):
  100. return os.path.basename(self._path).replace(2*self.SPLITCHAR, "/")
  101. def rel_path_is_valid(self):
  102. return not self.SPLITCHAR in self.rel_path
  103. def is_available(self):
  104. is_a = os.path.isfile(self.filename)
  105. if not is_a:
  106. logger.info("page.is_available: Not available - %s", self.filename)
  107. return is_a
  108. @property
  109. def title(self):
  110. return os.path.basename(self._path).split("::")[-1]
  111. @property
  112. def raw_page_src(self):
  113. self._load_page_src()
  114. return self._raw_page_src
  115. def _update_metadata(self):
  116. username = None
  117. try:
  118. if self._request.user.is_authenticated:
  119. username = self._request.user.username
  120. else:
  121. logger.warning("Page edit without having a logged in user. This is not recommended. Check your access definitions!")
  122. except AttributeError:
  123. logger.exception("Page edit without having a request object. Check programming!")
  124. self._meta_data.update(username)
  125. class creole_page(base_page):
  126. FOLDER_ATTACHMENTS = "attachments"
  127. def __init__(self, request, path) -> None:
  128. self._request = request
  129. super().__init__(path)
  130. @property
  131. def attachment_path(self):
  132. return os.path.join(os.path.basename(self._path), self.FOLDER_ATTACHMENTS)
  133. def render_to_html(self):
  134. if self.is_available():
  135. return self.render_text(self._request, self.raw_page_src)
  136. else:
  137. messages.unavailable_msg_page(self._request, self.rel_path)
  138. return ""
  139. def render_meta(self):
  140. ctime = timestamp_to_datetime(self._request, self._meta_data.get(self._meta_data.KEY_CREATION_TIME)).strftime('%Y-%m-%d %H:%M')
  141. mtime = timestamp_to_datetime(self._request, self._meta_data.get(self._meta_data.KEY_MODIFIED_TIME)).strftime('%Y-%m-%d %H:%M')
  142. user = self._meta_data.get(self._meta_data.KEY_MODIFIED_USER)
  143. #
  144. meta = f'|{_("Created")}:|{ctime}|\n'
  145. meta += f'|{_("Modified")}:|{mtime}|\n'
  146. meta += f'|{_("Editor")}|{user}|\n\n'
  147. #
  148. return mycreole.render_simple(meta)
  149. def render_text(self, request, txt):
  150. macros = {
  151. "subpages": self.macro_subpages,
  152. "allpages": self.macro_allpages,
  153. }
  154. return mycreole.render(request, txt, self.attachment_path, macros=macros)
  155. def macro_allpages(self, *args, **kwargs):
  156. kwargs["allpages"] = True
  157. return self.macro_subpages(*args, **kwargs)
  158. def macro_subpages(self, *args, **kwargs):
  159. allpages = kwargs.pop("allpages", False)
  160. #
  161. def parse_depth(s: str):
  162. try:
  163. return int(s)
  164. except ValueError:
  165. pass
  166. params = kwargs.get('', '')
  167. startname = ''
  168. depth = parse_depth(params)
  169. if depth is None:
  170. params = params.split(",")
  171. depth = parse_depth(params[0])
  172. if len(params) == 2:
  173. startname = params[1]
  174. elif depth is None:
  175. startname = params[0]
  176. if depth is None:
  177. depth = 9999
  178. #
  179. rv = ""
  180. # create a rel_path list
  181. pathlist = [base_page(path).rel_path for path in fstools.dirlist(settings.PAGES_ROOT, rekursive=False)]
  182. # sort basename
  183. pathlist.sort(key=os.path.basename)
  184. last_char = None
  185. for contentname in pathlist:
  186. #
  187. if (contentname.startswith(self.rel_path) or allpages) and contentname != self.rel_path:
  188. if allpages:
  189. name = contentname
  190. else:
  191. name = contentname[len(self.rel_path)+1:]
  192. if name.count('/') < depth and name.startswith(startname):
  193. if last_char != os.path.basename(name)[0].upper():
  194. last_char = os.path.basename(name)[0].upper()
  195. if last_char is not None:
  196. rv += "</ul>\n"
  197. rv += f'<h3>{last_char}</h3>\n<ul>\n'
  198. rv += f' <li><a href="{url_page(self._request, contentname)}">{name}</a></li>\n'
  199. if len(rv) > 0:
  200. rv += "</ul>\n"
  201. return rv