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.

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