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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import difflib
  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 . import timestamp_to_datetime
  13. logger = logging.getLogger(settings.ROOT_LOGGER_NAME).getChild(__name__)
  14. SPLITCHAR = ":"
  15. HISTORY_FOLDER_NAME = 'history'
  16. def full_path_all_pages(expression="*"):
  17. system_pages = fstools.dirlist(settings.SYSTEM_PAGES_ROOT, expression=expression, rekursive=False)
  18. system_pages = [os.path.join(settings.PAGES_ROOT, os.path.basename(path)) for path in system_pages]
  19. pages = fstools.dirlist(settings.PAGES_ROOT, expression=expression, rekursive=False)
  20. return list(set(system_pages + pages))
  21. class meta_data(dict):
  22. META_FILE_NAME = 'meta.json'
  23. #
  24. KEY_CREATION_TIME = "creation_time"
  25. KEY_MODIFIED_TIME = "modified_time"
  26. KEY_MODIFIED_USER = "modified_user"
  27. KEY_TAGS = "tags"
  28. def __init__(self, path, history_version=None):
  29. self._path = path
  30. self._history_version = history_version
  31. #
  32. # Load data from disk
  33. try:
  34. with open(self.filename, 'r') as fh:
  35. super().__init__(json.load(fh))
  36. except (FileNotFoundError, json.decoder.JSONDecodeError) as e:
  37. super().__init__()
  38. @property
  39. def filename(self):
  40. if not self._history_version:
  41. return os.path.join(self._path, self.META_FILE_NAME)
  42. else:
  43. return self.history_filename(self._history_version)
  44. def history_filename(self, history_version):
  45. return os.path.join(self._path, HISTORY_FOLDER_NAME, "%05d_%s" % (history_version, self.META_FILE_NAME))
  46. def update(self, username, tags):
  47. if username:
  48. self[self.KEY_MODIFIED_TIME] = int(time.time())
  49. self[self.KEY_MODIFIED_USER] = username
  50. if self.KEY_CREATION_TIME not in self:
  51. self[self.KEY_CREATION_TIME] = self[self.KEY_MODIFIED_TIME]
  52. if tags:
  53. self[self.KEY_TAGS] = tags
  54. #
  55. if username or tags:
  56. self.save()
  57. def save(self):
  58. if self._history_version:
  59. logger.error("A history version %05d can not be updated!", self._history_version)
  60. return False
  61. else:
  62. with open(self.filename, 'w') as fh:
  63. json.dump(self, fh, indent=4)
  64. return True
  65. def store_to_history(self, history_number):
  66. history_filename = self.history_filename(history_number)
  67. fstools.mkdir(os.path.dirname(history_filename))
  68. shutil.copy(self.filename, history_filename)
  69. class page_data(object):
  70. PAGE_FILE_NAME = 'page'
  71. def __init__(self, path, history_version=None):
  72. self._history_version = history_version
  73. self._path = path
  74. self._raw_page_src = None
  75. def _load_page_src(self):
  76. if self._raw_page_src is None:
  77. try:
  78. with open(self.filename, 'r') as fh:
  79. self._raw_page_src = fh.read()
  80. except FileNotFoundError:
  81. self._raw_page_src = ""
  82. def update_required(self, page_txt):
  83. return page_txt.replace("\r\n", "\n") != self.raw_page_src
  84. def update_page(self, page_txt):
  85. if self._history_version:
  86. logger.error("A history version %05d can not be updated!", self._history_version)
  87. return False
  88. else:
  89. # save the new page content
  90. fstools.mkdir(os.path.dirname(self.filename))
  91. with open(self.filename, 'w') as fh:
  92. fh.write(page_txt)
  93. self._raw_page_src = page_txt
  94. return True
  95. @property
  96. def filename(self):
  97. if not self._history_version:
  98. return os.path.join(self._path, self.PAGE_FILE_NAME)
  99. else:
  100. return self.history_filename(self._history_version)
  101. def history_filename(self, history_version):
  102. return os.path.join(self._path, HISTORY_FOLDER_NAME, "%05d_%s" % (history_version, self.PAGE_FILE_NAME))
  103. @property
  104. def rel_path(self):
  105. return os.path.basename(self._path).replace(2*SPLITCHAR, "/")
  106. def is_available(self):
  107. is_a = os.path.isfile(self.filename)
  108. if not is_a:
  109. logger.info("page.is_available: Not available - %s", self.filename)
  110. return is_a
  111. @property
  112. def title(self):
  113. return os.path.basename(self._path).split("::")[-1]
  114. @property
  115. def raw_page_src(self):
  116. self._load_page_src()
  117. return self._raw_page_src
  118. def store_to_history(self, history_number):
  119. history_filename = self.history_filename(history_number)
  120. fstools.mkdir(os.path.dirname(history_filename))
  121. shutil.copy(self.filename, history_filename)
  122. class page_django(page_data):
  123. FOLDER_ATTACHMENTS = "attachments"
  124. def __init__(self, request, path, history_version=None) -> None:
  125. self._request = request
  126. super().__init__(path, history_version=history_version)
  127. @property
  128. def attachment_path(self):
  129. return os.path.join(os.path.basename(self._path), self.FOLDER_ATTACHMENTS)
  130. def render_to_html(self):
  131. if self.is_available():
  132. return self.render_text(self._request, self.raw_page_src)
  133. else:
  134. messages.unavailable_msg_page(self._request, self.rel_path)
  135. return ""
  136. def history_numbers_list(self):
  137. history_folder = os.path.join(self._path, HISTORY_FOLDER_NAME)
  138. return list(set([int(os.path.basename(filename)[:5]) for filename in fstools.filelist(history_folder)]))
  139. def render_meta(self, ctime, mtime, user, tags):
  140. #
  141. # Page meta data
  142. #
  143. meta = f'=== {_("Meta data")}\n'
  144. meta += f'|{_("Created")}:|{timestamp_to_datetime(self._request, ctime)}|\n'
  145. meta += f'|{_("Modified")}:|{timestamp_to_datetime(self._request, mtime)}|\n'
  146. meta += f'|{_("Editor")}|{user}|\n'
  147. meta += f'|{_("Tags")}|{tags}|\n'
  148. #
  149. # List of hostory page versions
  150. #
  151. hnl = self.history_numbers_list()
  152. if hnl:
  153. meta += f'=== {_("History")}\n'
  154. meta += f'| ={_("Version")} | ={_("Date")} | ={_("Page")} | ={_("Meta data")} | \n'
  155. # Current
  156. name = _("Current")
  157. meta += f"| {name} \
  158. | {timestamp_to_datetime(self._request, mtime)} \
  159. | [[{url_page(self._request, self.rel_path)} | Page]] \
  160. | [[{url_page(self._request, self.rel_path, meta=None)} | Meta]]\n"
  161. # History
  162. for num in reversed(hnl):
  163. p = page_wrapped(self._request, self._path, history_version=num)
  164. meta += f"| {num} \
  165. | {timestamp_to_datetime(self._request, p.modified_time)} \
  166. | [[{url_page(self._request, p.rel_path, history=num)} | Page]] \
  167. | [[{url_page(self._request, p.rel_path, meta=None, history=num)} | Meta]] (with page changes)\n"
  168. # Diff
  169. html_diff = ""
  170. if self._history_version:
  171. meta += f'=== {_("Page differences")}\n'
  172. #
  173. c = page_django(self._request, self._path)
  174. left_lines = c.raw_page_src.splitlines()
  175. right_lines = self.raw_page_src.splitlines()
  176. html_diff = difflib.HtmlDiff(wrapcolumn=80).make_table(left_lines, right_lines)
  177. #
  178. return mycreole.render_simple(meta) + html_diff
  179. def render_text(self, request, txt):
  180. macros = {
  181. "subpages": self.macro_subpages,
  182. "allpages": self.macro_allpages,
  183. }
  184. return mycreole.render(request, txt, self.attachment_path, macros=macros)
  185. def macro_allpages(self, *args, **kwargs):
  186. kwargs["allpages"] = True
  187. return self.macro_subpages(*args, **kwargs)
  188. def macro_subpages(self, *args, **kwargs):
  189. allpages = kwargs.pop("allpages", False)
  190. #
  191. def parse_depth(s: str):
  192. try:
  193. return int(s)
  194. except ValueError:
  195. pass
  196. params = kwargs.get('', '')
  197. filter_str = ''
  198. depth = parse_depth(params)
  199. if depth is None:
  200. params = params.split(",")
  201. depth = parse_depth(params[0])
  202. if len(params) == 2:
  203. filter_str = params[1]
  204. elif depth is None:
  205. filter_str = params[0]
  206. #
  207. rv = ""
  208. # create a page_list
  209. if allpages:
  210. expression = "*"
  211. parent_rel_path = ""
  212. else:
  213. expression = os.path.basename(self._path) + 2 * SPLITCHAR + "*"
  214. parent_rel_path = self.rel_path
  215. #
  216. pl = page_list(
  217. self._request,
  218. [page_django(self._request, path) for path in full_path_all_pages(expression)]
  219. )
  220. return pl.html_list(depth=depth, filter_str=filter_str, parent_rel_path=parent_rel_path)
  221. class page_list(list):
  222. def __init__(self, request, *args, **kwargs):
  223. self._request = request
  224. return super().__init__(*args, **kwargs)
  225. def sort_basename(self):
  226. return list.sort(self, key=lambda x: os.path.basename(x.rel_path))
  227. def creole_list(self, depth=None, filter_str='', parent_rel_path=''):
  228. self.sort_basename()
  229. depth = depth or 9999 # set a random high value if None
  230. #
  231. parent_rel_path = parent_rel_path + "/" if len(parent_rel_path) > 0 else ""
  232. #
  233. rv = ""
  234. last_char = None
  235. for page in self:
  236. name = page.rel_path[len(parent_rel_path):]
  237. if name.startswith(filter_str) and name != filter_str:
  238. if name.count('/') < depth:
  239. first_char = os.path.basename(name)[0].upper()
  240. if last_char != first_char:
  241. last_char = first_char
  242. rv += f"=== {first_char}\n"
  243. rv += f"* [[{url_page(self._request, page.rel_path)} | {name} ]]\n"
  244. return rv
  245. def html_list(self, depth=9999, filter_str='', parent_rel_path=''):
  246. return mycreole.render_simple(self.creole_list(depth, filter_str, parent_rel_path))
  247. class page_wrapped(object):
  248. """
  249. This class holds different page and meta instances and decides which will be used in which case.
  250. """
  251. def __init__(self, request, path, history_version=None):
  252. """_summary_
  253. Args:
  254. request (_type_): The django request or None (if None, the page functionality is limited)
  255. path (_type_): A rel_path of the django page or the filesystem path to the page
  256. history_version (_type_, optional): The history version of the page to be created
  257. """
  258. self._request = request
  259. #
  260. page_path = self.__page_path__(path)
  261. system_page_path = self.__system_page_path__(path)
  262. # Page
  263. if request:
  264. self._page = page_django(request, page_path, history_version=history_version)
  265. else:
  266. self._page = page_data(page_path, history_version=history_version)
  267. self._page_meta = meta_data(page_path, history_version=history_version)
  268. # System page
  269. if request:
  270. self._system_page = page_django(request, system_page_path)
  271. else:
  272. self._system_page = page_data(system_page_path)
  273. self._system_meta_data = meta_data(system_page_path)
  274. def __page_path__(self, path):
  275. if path.startswith(settings.PAGES_ROOT):
  276. # must be a filesystem path
  277. return path
  278. else:
  279. # must be a relative url
  280. return os.path.join(settings.PAGES_ROOT, path.replace("/", 2*SPLITCHAR))
  281. def __system_page_path__(self, path):
  282. return os.path.join(settings.SYSTEM_PAGES_ROOT, os.path.basename(path))
  283. def __page_choose__(self):
  284. if not self._page.is_available():
  285. return self._system_page
  286. else:
  287. return self._page
  288. def __meta_choose__(self):
  289. if not self._page.is_available():
  290. return self._system_meta_data
  291. else:
  292. return self._page_meta
  293. def __store_history__(self):
  294. if self._page.is_available():
  295. try:
  296. history_number = max(self._page.history_numbers_list()) + 1
  297. except ValueError:
  298. history_number = 1 # no history yet
  299. self._page.store_to_history(history_number)
  300. self._page_meta.store_to_history(history_number)
  301. #
  302. # meta_data
  303. #
  304. @property
  305. def creation_time(self):
  306. meta = self.__meta_choose__()
  307. rv = meta.get(meta.KEY_CREATION_TIME)
  308. return rv
  309. @property
  310. def modified_time(self):
  311. meta = self.__meta_choose__()
  312. rv = meta.get(meta.KEY_MODIFIED_TIME)
  313. return rv
  314. @property
  315. def modified_user(self):
  316. meta = self.__meta_choose__()
  317. rv = meta.get(meta.KEY_MODIFIED_USER)
  318. return rv
  319. @property
  320. def tags(self):
  321. meta = self.__meta_choose__()
  322. rv = meta.get(meta.KEY_TAGS)
  323. return rv
  324. #
  325. # page
  326. #
  327. @property
  328. def attachment_path(self):
  329. page = self.__page_choose__()
  330. rv = page.attachment_path
  331. return rv
  332. @property
  333. def raw_page_src(self):
  334. page = self.__page_choose__()
  335. rv = page.raw_page_src
  336. return rv
  337. @property
  338. def rel_path(self):
  339. page = self.__page_choose__()
  340. rv = page.rel_path
  341. return rv
  342. def render_meta(self):
  343. page = self.__page_choose__()
  344. rv = page.render_meta(self.creation_time, self.modified_time, self.modified_user, self.tags)
  345. return rv
  346. def render_to_html(self):
  347. page = self.__page_choose__()
  348. rv = page.render_to_html()
  349. return rv
  350. def render_text(self, request, txt):
  351. page = self.__page_choose__()
  352. rv = page.render_text(request, txt)
  353. return rv
  354. @property
  355. def title(self):
  356. page = self.__page_choose__()
  357. rv = page.title
  358. return rv
  359. def update_page(self, txt, tags):
  360. if self._page.update_required(txt):
  361. # Store history
  362. self.__store_history__()
  363. # Update page
  364. rv = self._page.update_page(txt)
  365. # Update meta data
  366. username = None
  367. try:
  368. if self._request.user.is_authenticated:
  369. username = self._request.user.username
  370. else:
  371. logger.warning("Page edit without having a logged in user. This is not recommended. Check your access definitions!")
  372. except AttributeError:
  373. logger.exception("Page edit without having a request object. Check programming!")
  374. self._page_meta.update(username, tags)
  375. # Update search index
  376. from pages.search import update_item
  377. update_item(self)
  378. return rv