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.

page.py 17KB

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