Piki is a minimal wiki
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

page.py 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. filter_str = ''
  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. filter_str = params[1]
  174. elif depth is None:
  175. filter_str = params[0]
  176. #
  177. rv = ""
  178. # create a page_list
  179. if allpages:
  180. expression = "*"
  181. parent_rel_path = ""
  182. else:
  183. expression = os.path.basename(self._path) + 2 * self.SPLITCHAR + "*"
  184. parent_rel_path = self.rel_path
  185. pl = page_list(
  186. self._request,
  187. [creole_page(self._request, path) for path in fstools.dirlist(settings.PAGES_ROOT, expression=expression, rekursive=False)]
  188. )
  189. return pl.html_list(depth=depth, filter_str=filter_str, parent_rel_path=parent_rel_path)
  190. class page_list(list):
  191. def __init__(self, request, *args, **kwargs):
  192. self._request = request
  193. return super().__init__(*args, **kwargs)
  194. def sort_basename(self):
  195. return list.sort(self, key=lambda x: os.path.basename(x.rel_path))
  196. def creole_list(self, depth=None, filter_str='', parent_rel_path=''):
  197. self.sort_basename()
  198. depth = depth or 9999 # set a random high value if None
  199. #
  200. parent_rel_path = parent_rel_path + "/" if len(parent_rel_path) > 0 else ""
  201. #
  202. rv = ""
  203. last_char = None
  204. for page in self:
  205. name = page.rel_path[len(parent_rel_path):]
  206. if name.startswith(filter_str) and name != filter_str:
  207. if name.count('/') < depth:
  208. first_char = os.path.basename(name)[0].upper()
  209. if last_char != first_char:
  210. last_char = first_char
  211. rv += f"=== {first_char}\n"
  212. rv += f"* [[{url_page(self._request, page.rel_path)} | {name} ]]\n"
  213. return rv
  214. def html_list(self, depth=9999, filter_str='', parent_rel_path=''):
  215. return mycreole.render_simple(self.creole_list(depth, filter_str, parent_rel_path))