Piki is a minimal wiki
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

page.py 15KB

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