Piki is a minimal wiki
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

page.py 8.1KB

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