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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. from django.conf import settings
  2. from django.contrib.auth.models import User, Group
  3. from django.db import models
  4. from django.utils.translation import gettext as _
  5. from simple_history.models import HistoricalRecords
  6. from datetime import datetime
  7. import difflib
  8. import logging
  9. import os
  10. from zoneinfo import ZoneInfo
  11. from users.models import get_userprofile
  12. from pages import url_page
  13. import mycreole
  14. logger = logging.getLogger(settings.ROOT_LOGGER_NAME).getChild(__name__)
  15. class PikiPage(models.Model):
  16. SAVE_ON_CHANGE_FIELDS = ["rel_path", "page_txt", "tags", "deleted", "owner", "group"]
  17. #
  18. rel_path = models.CharField(unique=True, max_length=1000)
  19. page_txt = models.TextField(max_length=50000)
  20. tags = models.CharField(max_length=1000, null=True, blank=True)
  21. deleted = models.BooleanField(default=False)
  22. #
  23. creation_time = models.DateTimeField(null=True, blank=True)
  24. creation_user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, related_name="creation_user")
  25. modified_time = models.DateTimeField(null=True, blank=True)
  26. modified_user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, related_name="modified_user")
  27. #
  28. owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, related_name="owner")
  29. group = models.ForeignKey(Group, null=True, blank=True, on_delete=models.SET_NULL, related_name="group")
  30. # owner_perms
  31. owner_perms_read = models.BooleanField(default=True)
  32. owner_perms_write = models.BooleanField(default=True)
  33. # group_perms
  34. group_perms_read = models.BooleanField(default=True)
  35. group_perms_write = models.BooleanField(default=True)
  36. # other_perms
  37. other_perms_read = models.BooleanField(default=True)
  38. other_perms_write = models.BooleanField(default=False)
  39. #
  40. history = HistoricalRecords()
  41. def __init__(self, *args, **kwargs):
  42. super().__init__(*args, **kwargs)
  43. def prepare_save(self, request):
  44. # Set date
  45. tmd = datetime.now(tz=ZoneInfo("UTC")).replace(microsecond=0)
  46. self.creation_time = self.creation_time or tmd
  47. self.modified_time = tmd
  48. # Set user
  49. self.creation_user = self.creation_user or request.user
  50. self.owner = self.owner or request.user
  51. self.modified_user = request.user
  52. def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
  53. if self.id and not force_update:
  54. orig = PikiPage.objects.get(id=self.id)
  55. for key in self.SAVE_ON_CHANGE_FIELDS:
  56. if getattr(self, key) != getattr(orig, key):
  57. break
  58. else:
  59. self.save_needed = False
  60. return False
  61. self.save_needed = True
  62. return models.Model.save(self, force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
  63. #
  64. # Set history datetime to modified datetime
  65. #
  66. @property
  67. def _history_date(self):
  68. return self.modified_time
  69. @_history_date.setter
  70. def _history_date(self, value):
  71. self.modified_time = value
  72. #
  73. # My information
  74. #
  75. @property
  76. def title(self):
  77. return self.rel_path.split("/")[-1]
  78. #
  79. # My methods
  80. #
  81. def render_to_html(self, request, history=None):
  82. if history:
  83. h = self.history.get(history_id=history)
  84. return self.render_text(request, h.page_txt)
  85. else:
  86. return self.render_text(request, self.page_txt)
  87. def user_datetime(self, request, dtm):
  88. try:
  89. up = get_userprofile(request.user)
  90. except AttributeError:
  91. tz = ZoneInfo("UTC")
  92. else:
  93. tz = ZoneInfo(up.timezone)
  94. #
  95. return datetime.astimezone(dtm, tz)
  96. def render_meta(self, request, history):
  97. # Page information
  98. meta = f'= {_("Meta data")}\n'
  99. meta += f'|{_("Created by")}:|{self.creation_user}|\n'
  100. meta += f'|{_("Created at")}:|{self.user_datetime(request, self.creation_time)}|\n'
  101. meta += f'|{_("Modified by")}:|{self.modified_user}|\n'
  102. meta += f'|{_("Modified at")}:|{self.user_datetime(request, self.modified_time)}|\n'
  103. meta += f'|{_("Owner")}:|{self.owner or "---"}|\n'
  104. meta += f'|{_("Group")}:|{self.group or "---"}|\n'
  105. meta += f'|{_("Tags")}|{self.tags or "---"}|\n'
  106. #
  107. # List of history page versions
  108. #
  109. hl = self.history.all()[1:]
  110. if len(hl) > 0:
  111. meta += f'= {_("History")}\n'
  112. meta += f'| ={_("Version")} | ={_("Date")} | ={_("Page")} | ={_("Meta data")} | ={_("Page changed")} | ={_("Tags changed")} | \n'
  113. # Current
  114. name = _("Current")
  115. meta += f"| {name} \
  116. | {self.user_datetime(request, self.modified_time)} \
  117. | [[{url_page(self.rel_path)} | Page]] \
  118. | [[{url_page(self.rel_path, meta=None)} | Meta]] |"
  119. page_content = self.page_txt.replace("\r\n", "\n").strip("\n")
  120. tags = self.tags
  121. for h_page in hl:
  122. page_changed = page_content != h_page.page_txt.replace("\r\n", "\n").strip("\n")
  123. tags_changed = tags != h_page.tags
  124. if page_changed or tags_changed:
  125. meta += " %s |" % ("Yes" if page_changed else "No")
  126. meta += " %s |" % ("Yes" if tags_changed else "No")
  127. meta += "\n"
  128. meta += f"| {h_page.history_id} \
  129. | {self.user_datetime(request, h_page.modified_time)} \
  130. | [[{url_page(self.rel_path, history=h_page.history_id)} | Page]] \
  131. | [[{url_page(self.rel_path, meta=None, history=h_page.history_id)} | Meta]] (with diff to current) |"
  132. page_content = h_page.page_txt[:].replace("\r\n", "\n").strip("\n")
  133. tags = h_page.tags
  134. meta += " --- | --- |\n"
  135. # Diff
  136. html_diff = ""
  137. if history:
  138. h_page = self.history.get(history_id=history)
  139. #
  140. meta += f'= {_("Page differences")}\n'
  141. #
  142. left_lines = self.page_txt.splitlines()
  143. right_lines = h_page.page_txt.splitlines()
  144. html_diff = difflib.HtmlDiff(wrapcolumn=80).make_table(left_lines, right_lines, "Current page", "Page Version %d" % history)
  145. #
  146. return mycreole.render_simple(meta) + html_diff
  147. #
  148. # Creole stuff
  149. #
  150. def render_text(self, request, txt):
  151. macros = {
  152. "subpages": self.macro_subpages,
  153. "allpages": self.macro_allpages,
  154. "subpagetree": self.macro_subpagetree,
  155. "allpagestree": self.macro_allpagestree,
  156. }
  157. return mycreole.render(request, txt, self.rel_path, macros=macros)
  158. def macro_subpages(self, *args, **kwargs):
  159. return self.macro_pages(*args, **kwargs)
  160. def macro_allpages(self, *args, **kwargs):
  161. kwargs["allpages"] = True
  162. return self.macro_pages(*args, **kwargs)
  163. def macro_allpagestree(self, *args, **kwargs):
  164. kwargs["allpages"] = True
  165. kwargs["tree"] = True
  166. return self.macro_pages(*args, **kwargs)
  167. def macro_subpagetree(self, * args, **kwargs):
  168. kwargs["tree"] = True
  169. return self.macro_pages(*args, **kwargs)
  170. def macro_pages(self, *args, **kwargs):
  171. allpages = kwargs.pop("allpages", False)
  172. tree = kwargs.pop("tree", False)
  173. #
  174. def parse_depth(s: str):
  175. try:
  176. return int(s)
  177. except ValueError:
  178. pass
  179. params = kwargs.get('', '')
  180. filter_str = ''
  181. depth = parse_depth(params)
  182. if depth is None:
  183. params = params.split(",")
  184. depth = parse_depth(params[0])
  185. if len(params) == 2:
  186. filter_str = params[1]
  187. elif depth is None:
  188. filter_str = params[0]
  189. #
  190. if not allpages:
  191. filter_str = os.path.join(self.rel_path, filter_str)
  192. #
  193. pages = PikiPage.objects.filter(rel_path__contains=filter_str)
  194. pl = page_list([p for p in pages if not p.deleted])
  195. #
  196. if tree:
  197. return "<pre>\n" + page_tree(pl).html() + "</pre>\n"
  198. else:
  199. return pl.html_list(depth=depth, filter_str=filter_str, parent_rel_path='' if allpages else self.rel_path)
  200. class page_list(list):
  201. def __init__(self, *args, **kwargs):
  202. return super().__init__(*args, **kwargs)
  203. def sort_basename(self):
  204. return list.sort(self, key=lambda x: os.path.basename(x.rel_path))
  205. def creole_list(self, depth=None, filter_str='', parent_rel_path=''):
  206. self.sort_basename()
  207. depth = depth or 9999 # set a random high value if None
  208. #
  209. rv = ""
  210. last_char = None
  211. for page in self:
  212. if page.rel_path.startswith(filter_str) and page.rel_path != filter_str:
  213. name = page.rel_path[len(parent_rel_path):].lstrip("/")
  214. if name.count('/') < depth:
  215. first_char = os.path.basename(name)[0].upper()
  216. if last_char != first_char:
  217. last_char = first_char
  218. rv += f"=== {first_char}\n"
  219. rv += f"* [[{url_page(page.rel_path)} | {name} ]]\n"
  220. return rv
  221. def html_list(self, depth=9999, filter_str='', parent_rel_path=''):
  222. return mycreole.render_simple(self.creole_list(depth, filter_str, parent_rel_path))
  223. class page_tree(dict):
  224. T_PATTERN = "├── "
  225. L_PATTERN = "└── "
  226. I_PATTERN = "│ "
  227. D_PATTERN = " "
  228. def __init__(self, pl: page_list):
  229. super().__init__()
  230. for page in pl:
  231. store_item = self
  232. for entry in page.rel_path.split("/"):
  233. if not entry in store_item:
  234. store_item[entry] = {}
  235. store_item = store_item[entry]
  236. def html(self, rel_path=None, fill=""):
  237. base = self
  238. try:
  239. for key in rel_path.split("/"):
  240. base = base[key]
  241. except AttributeError:
  242. rel_path = ''
  243. #
  244. rv = ""
  245. #
  246. l = len(base)
  247. for entry in sorted(list(base.keys())):
  248. l -= 1
  249. page_path = os.path.join(rel_path, entry)
  250. try:
  251. PikiPage.objects.get(rel_path=page_path)
  252. except PikiPage.DoesNotExist:
  253. pass
  254. else:
  255. entry = f'<a href="{url_page(page_path)}">{entry}</a>'
  256. rv += fill + (self.L_PATTERN if l == 0 else self.T_PATTERN) + entry + "\n"
  257. rv += self.html(page_path, fill=fill+(self.D_PATTERN if l == 0 else self.I_PATTERN))
  258. return rv