views.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. # -*- coding: utf-8 -*-
  2. """
  3. Monomotapa - A Micro CMS
  4. Copyright (C) 2014, Paul Munday.
  5. PO Box 28228, Portland, OR, USA 97228
  6. paul at paulmunday.net
  7. Modificado por: Rodrigo Garcia 2017 https://rmgss.net/contacto
  8. This program is free software: you can redistribute it and/or modify
  9. it under the terms of the GNU Affero Public License as published by
  10. the Free Software Foundation, either version 3 of the License, or
  11. (at your option) any later version.
  12. This program is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. GNU General Public License for more details.
  16. You should have received a copy of the GNU Affero General Public License
  17. along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. Monomotapa:
  19. a city whose inhabitants are bounded by deep feelings of friendship,
  20. so that they intuit one another's most secret needs and desire.
  21. For instance, if one dreams that his friend is sad, the friend will
  22. perceive the distress and rush to the sleepers rescue.
  23. (Jean de La Fontaine, *Fables choisies, mises en vers*, VIII:11 Paris,
  24. 2nd ed., 1678-9)
  25. cited in :
  26. Alberto Manguel and Gianni Guadalupi, *The Dictionary of Imaginary Places*,
  27. Bloomsbury, London, 1999.
  28. A micro cms written using the Flask microframework, orignally to manage my
  29. personal site. It is designed so that publishing a page requires no more than
  30. dropping a markdown page in the appropriate directory (though you need to edit
  31. a json file if you want it to appear in the top navigation).
  32. It can also display its own source code and run its own unit tests.
  33. The name 'monomotapa' was chosen more or less at random (it shares an initial
  34. with me) as I didn't want to name it after the site and be typing import
  35. paulmunday, or something similar, as that would be strange.
  36. """
  37. from flask import render_template, abort, Markup, escape, request #, make_response
  38. from flask import redirect
  39. from werkzeug import secure_filename
  40. from pygments import highlight
  41. from pygments.lexers import PythonLexer, HtmlDjangoLexer, TextLexer
  42. from pygments.formatters import HtmlFormatter
  43. import markdown
  44. from time import gmtime, strptime, strftime, ctime, mktime
  45. import datetime
  46. import os.path
  47. import os
  48. import subprocess
  49. import json
  50. from collections import OrderedDict
  51. from simplemotds import SimpleMotd
  52. from monomotapa import app
  53. from monomotapa.config import ConfigError
  54. from monomotapa.utils import captcha_comprobar_respuesta, captcha_pregunta_opciones_random
  55. from monomotapa.utils import categorias_de_post, categoriasDePost, categoriasList, cabezaPost
  56. from monomotapa.utils import titulo_legible
  57. from markdown.extensions.toc import TocExtension
  58. json_pattrs = {}
  59. with open(os.path.join('monomotapa','pages.json'), 'r') as pagefile:
  60. json_pattrs = json.load(pagefile)
  61. simplemotd = SimpleMotd("config_simplemotds.json")
  62. class MonomotapaError(Exception):
  63. """create classs for own errors"""
  64. pass
  65. def get_page_attributes(jsonfile):
  66. """Returns dictionary of page_attributes.
  67. Defines additional static page attributes loaded from json file.
  68. N.B. static pages do not need to have attributes defined there,
  69. it is sufficient to have a page.md in src for each /page
  70. possible values are src (name of markdown file to be rendered)
  71. heading, title, and trusted (i.e. allow embeded html in markdown)"""
  72. try:
  73. with open(src_file(jsonfile), 'r') as pagesfile:
  74. page_attributes = json.load(pagesfile)
  75. except IOError:
  76. page_attributes = []
  77. return page_attributes
  78. def get_page_attribute(attr_src, page, attribute):
  79. """returns attribute of page if it exists, else None.
  80. attr_src = dictionary(from get_page_attributes)"""
  81. if page in attr_src and attribute in attr_src[page]:
  82. return attr_src[page][attribute]
  83. else:
  84. return None
  85. # Navigation
  86. def top_navigation(page):
  87. """Generates navigation as an OrderedDict from navigation.json.
  88. Navigation.json consists of a json array(list) "nav_order"
  89. containing the names of the top navigation elements and
  90. a json object(dict) called "nav_elements"
  91. if a page is to show up in the top navigation
  92. there must be an entry present in nav_order but there need not
  93. be one in nav_elements. However if there is the key must be the same.
  94. Possible values for nav_elements are link_text, url and urlfor
  95. The name from nav_order will be used to set the link text,
  96. unless link_text is present in nav_elements.
  97. url and urlfor are optional, however if ommited the url wil be
  98. generated in the navigation by url_for('staticpage', page=[key])
  99. equivalent to @app.route"/page"; def page())
  100. which may not be correct. If a url is supplied it will be used
  101. otherwise if urlfor is supplied it the url will be
  102. generated with url_for(urlfor). url takes precendence so it makes
  103. no sense to supply both.
  104. Web Sign-in is supported by adding a "rel": "me" attribute.
  105. """
  106. with open(src_file('navigation.json'), 'r') as navfile:
  107. navigation = json.load(navfile)
  108. base_nav = OrderedDict({})
  109. for key in navigation["nav_order"]:
  110. nav = {}
  111. nav['base'] = key
  112. nav['link_text'] = key
  113. if key in navigation["nav_elements"]:
  114. elements = navigation["nav_elements"][key]
  115. nav.update(elements)
  116. base_nav[key] = nav
  117. return {'navigation' : base_nav, 'page' : page}
  118. # For pages
  119. class Page:
  120. """Generates pages as objects"""
  121. def __init__(self, page, **kwargs):
  122. """Define attributes for pages (if present).
  123. Sets self.name, self.title, self.heading, self.trusted etc
  124. This is done through indirection so we can update the defaults
  125. (defined in the 'attributes' dictionary) with values from config.json
  126. or pages.json easily without lots of if else statements.
  127. If css is supplied it will overide any default css. To add additional
  128. style sheets on a per page basis specifiy them in pages.json.
  129. The same also applies with hlinks.
  130. css is used to set locally hosted stylesheets only. To specify
  131. external stylesheets use hlinks: in config.json for
  132. default values that will apply on all pages unless overidden, set here
  133. to override the default. Set in pages.json to add after default.
  134. """
  135. # set default attributes
  136. self.page = page.rstrip('/')
  137. self.defaults = get_page_attributes('defaults.json')
  138. self.pages = get_page_attributes('pages.json')
  139. title = titulo_legible(page.lower())
  140. heading = titulo_legible(page.capitalize())
  141. self.categorias = categoriasDePost(self.page)
  142. try:
  143. self.default_template = self.defaults['template']
  144. except KeyError:
  145. raise ConfigError('template not found in default.json')
  146. # will become self.name, self.title, self.heading,
  147. # self.footer, self.internal_css, self.trusted
  148. attributes = {'name' : self.page, 'title' : title,
  149. 'navigation' : top_navigation(self.page),
  150. 'heading' : heading, 'footer' : None,
  151. 'css' : None , 'hlinks' :None, 'internal_css' : None,
  152. 'trusted': False,
  153. 'preview-chars': 250
  154. }
  155. # contexto extra TODO: revisar otra forma de incluir un contexto
  156. self.contexto = {}
  157. self.contexto['consejo'] = simplemotd.getMotdContent()
  158. # set from defaults
  159. attributes.update(self.defaults)
  160. # override with kwargs
  161. attributes.update(kwargs)
  162. # override attributes if set in pages.json
  163. if page in self.pages:
  164. attributes.update(self.pages[page])
  165. # set attributes (as self.name etc) using indirection
  166. for attribute, value in attributes.items():
  167. setattr(self, attribute, value)
  168. setattr(self,attribute, value)
  169. # reset these as we want to append rather than overwrite if supplied
  170. if 'css' in kwargs:
  171. self.css = kwargs['css']
  172. elif 'css' in self.defaults:
  173. self.css = self.defaults['css']
  174. if 'hlinks' in kwargs:
  175. self.hlinks = kwargs['hlinks']
  176. elif 'hlinks' in self.defaults:
  177. self.hlinks = self.defaults['hlinks']
  178. # append hlinks and css from pages.json rather than overwriting
  179. # if css or hlinks are not supplied they are set to default
  180. if page in self.pages:
  181. if 'css' in self.pages[page]:
  182. self.css = self.css + self.pages[page]['css']
  183. if 'hlinks' in self.pages[page]:
  184. self.hlinks = self.hlinks + self.pages[page]['hlinks']
  185. # append heading to default if set in config
  186. if app.config['default_title']:
  187. self.title = app.config['default_title'] + self.title
  188. def _get_markdown(self):
  189. """returns rendered markdown or 404 if source does not exist"""
  190. src = self.get_page_src(self.page, 'src', 'md')
  191. if src is None:
  192. abort(404)
  193. else:
  194. return render_markdown(src, self.trusted)
  195. def get_page_src(self, page, directory=None, ext=None):
  196. """"return path of file (used to generate page) if it exists,
  197. or return none.
  198. Also returns the template used to render that page, defaults
  199. to static.html.
  200. It will optionally add an extension, to allow
  201. specifiying pages by route."""
  202. # is it stored in a config
  203. pagename = get_page_attribute(self.pages, page, 'src')
  204. if not pagename:
  205. pagename = page + get_extension(ext)
  206. if os.path.exists(src_file(pagename , directory)):
  207. return src_file(pagename, directory)
  208. else:
  209. return None
  210. def get_template(self, page):
  211. """returns the template for the page"""
  212. pagetemplate = get_page_attribute(self.pages, page, 'template')
  213. if not pagetemplate:
  214. pagetemplate = self.default_template
  215. if os.path.exists(src_file(pagetemplate , 'templates')):
  216. return pagetemplate
  217. else:
  218. raise MonomotapaError("Template: %s not found" % pagetemplate)
  219. def generate_page(self, contents=None):
  220. """return a page generator function.
  221. For static pages written in Markdown under src/.
  222. contents are automatically rendered.
  223. N.B. See note above in about headers"""
  224. if not contents:
  225. contents = self._get_markdown()
  226. template = self.get_template(self.page)
  227. return render_template(template,
  228. contents = Markup(contents),
  229. **vars(self)
  230. )
  231. # helper functions
  232. def src_file(name, directory=None):
  233. """return potential path to file in this app"""
  234. if not directory:
  235. return os.path.join( 'monomotapa', name)
  236. else:
  237. return os.path.join('monomotapa', directory, name)
  238. def get_extension(ext):
  239. '''constructs extension, adding or stripping leading . as needed.
  240. Return null string for None'''
  241. if ext is None:
  242. return ''
  243. elif ext[0] == '.':
  244. return ext
  245. else:
  246. return '.%s' % ext
  247. def render_markdown(srcfile, trusted=False):
  248. """Return markdown file rendered as html. Defaults to untrusted:
  249. html characters (and character entities) are escaped
  250. so will not be rendered. This departs from markdown spec
  251. which allows embedded html."""
  252. try:
  253. with open(srcfile, 'r') as f:
  254. src = f.read()
  255. if trusted == True:
  256. return markdown.markdown(src,
  257. extensions=['codehilite',
  258. TocExtension(permalink=True)])
  259. else:
  260. return markdown.markdown(escape(src),
  261. extensions=['codehilite',
  262. TocExtension(permalink=True)])
  263. except IOError:
  264. return None
  265. def render_pygments(srcfile, lexer_type):
  266. """returns src(file) marked up with pygments"""
  267. if lexer_type == 'python':
  268. with open(srcfile, 'r') as f:
  269. src = f.read()
  270. contents = highlight(src, PythonLexer(), HtmlFormatter())
  271. elif lexer_type == 'html':
  272. with open(srcfile, 'r') as f:
  273. src = f.read()
  274. contents = highlight(src, HtmlDjangoLexer(), HtmlFormatter())
  275. # default to TextLexer for everything else
  276. else:
  277. with open(srcfile, 'r') as f:
  278. src = f.read()
  279. contents = highlight(src, TextLexer(), HtmlFormatter())
  280. return contents
  281. def get_pygments_css(style=None):
  282. """returns css for pygments, use as internal_css"""
  283. if style is None:
  284. style = 'friendly'
  285. return HtmlFormatter(style=style).get_style_defs('.highlight')
  286. def heading(text, level):
  287. """return as html heading at h[level]"""
  288. heading_level = 'h%s' % str(level)
  289. return '\n<%s>%s</%s>\n' % (heading_level, text, heading_level)
  290. def posts_list(ordenar_por_fecha=True, ordenar_por_nombre=False):
  291. '''Retorna una lista con los nombres de archivos con extension .md
  292. dentro de la cappeta src/posts, por defecto retorna una lista con
  293. la tupla (nombre_archivo, fecha_subida)'''
  294. lista_posts = []
  295. lp = []
  296. if ordenar_por_nombre:
  297. try:
  298. ow = os.walk("monomotapa/src/posts")
  299. p , directorios , archs = ow.__next__()
  300. except OSError:
  301. print ("[posts] - Error: Cant' os.walk() on monomotapa/src/posts except OSError")
  302. else:
  303. for arch in archs:
  304. if arch.endswith(".md") and not arch.startswith("#") \
  305. and not arch.startswith("~") and not arch.startswith("."):
  306. lista_posts.append(arch)
  307. lista_posts.sort()
  308. return lista_posts
  309. if ordenar_por_fecha:
  310. try:
  311. ow = os.walk("monomotapa/src/posts")
  312. p,d,files=ow.__next__()
  313. except OSError:
  314. print ("[posts] - Error: Can't os.walk() on monomotapa/src/posts except OSError.")
  315. else:
  316. for f in files:
  317. nombre_con_ruta = os.path.join("monomotapa/src/posts", f)
  318. if not f.endswith("~") and not f.startswith("#") and not f.startswith("."):
  319. secs_modificacion = SecsModificacionPostDesdeJson(f, json_pattrs)
  320. ultima_modificacion = os.path.getmtime(nombre_con_ruta)
  321. lp.append((secs_modificacion, ultima_modificacion, f))
  322. lp.sort()
  323. lp.reverse()
  324. # colocando fecha en formato
  325. for tupla in lp:
  326. #fecha = strftime("a, %d %b %Y %H:%M:%S", ctime(tupla[0]))
  327. cfecha = ctime(tupla[1])
  328. #fecha = strptime("%a %b %d %H:%M:%S %Y", cfecha)
  329. lista_posts.append((cfecha, tupla[2]))
  330. return lista_posts
  331. def categorias_list(categoria=None):
  332. """ Rotorna una lista con los nombres de posts y el numero de posts que
  333. pertenecen a la categoria dada o a cada categoria.
  334. Las categorias se obtienen analizando la primera linea de cada archivo .md
  335. an la carpeta donde se almacenan los posts.
  336. Si no se especifica `categoria' cada elemento de la lista devuelta es:
  337. (nombre_categoria, numero_posts, [nombres_posts])
  338. si se especifica `categoria' cada elemento de la lista devuelta es:
  339. (numero_posts, [nombres_posts]
  340. """
  341. lista_posts = posts_list(ordenar_por_nombre=True)
  342. lista_categorias = []
  343. if categoria is not None:
  344. c = 0
  345. posts = []
  346. for post in lista_posts:
  347. nombre_arch = "monomotapa/src/posts/"+post
  348. with open(nombre_arch, 'r') as file:
  349. linea = file.readline().decode("utf-8")
  350. lc = linea.split("[#")[1:]
  351. for cad in lc:
  352. cat = cad.split("]")[0]
  353. if cat == categoria:
  354. c += 1
  355. posts.append(post)
  356. lista_categorias = (c, posts)
  357. return lista_categorias
  358. dic_categorias = {}
  359. for post in lista_posts:
  360. nombre_arch = "monomotapa/src/posts/"+post
  361. with open(nombre_arch, 'r') as fil:
  362. linea = fil.readline().decode('utf-8') # primera linea
  363. # extrayendo las categorias y registrando sus ocurrencias
  364. # ejemplo: catgorías: [#reflexión](categoria/reflexion) [#navidad](categoria/navidad)
  365. # extrae: [reflexion,navidad]
  366. lc = linea.split("[#")[1:]
  367. for cad in lc:
  368. cat = cad.split("]")[0]
  369. if cat not in dic_categorias:
  370. dic_categorias[cat] = (1,[post]) # nuevo registro por categoria
  371. else:
  372. tupla = dic_categorias[cat]
  373. c = tupla[0] + 1
  374. lis = tupla[1]
  375. if post not in lis:
  376. lis.append(post)
  377. dic_categorias[cat] = (c, lis)
  378. # convirtiendo en lista
  379. for k, v in dic_categorias.iteritems():
  380. lista_categorias.append((k,v[0],v[1]))
  381. lista_categorias.sort()
  382. lista_categorias.reverse()
  383. return lista_categorias
  384. def cabeza_post(archivo , max_caracteres=250, categorias=True):
  385. """ Devuelve las primeras lineas de una archivo de post (en formato markdown)
  386. con un maximo numero de caracteres excluyendo titulos en la cabeza devuelta.
  387. Si se especifica `categorias' en True
  388. Se devuelve una lista de la forma:
  389. (cabeza_post, categorias)
  390. donde categorias son cadenas con los nombres de las categorias a la que
  391. pertenece el post
  392. """
  393. cabeza_post = ""
  394. cats = []
  395. with open(os.path.join("monomotapa/src/posts",archivo)) as file:
  396. # analizando si hay titulos al principio
  397. # Se su pone que la primera linea es de categorias
  398. for linea in file.readlines():
  399. linea = linea.decode("utf-8")
  400. if linea.startswith(u"categorías:") or linea.startswith("categorias"):
  401. if categorias:
  402. cats = categoriasDePost(archivo)
  403. #cats = categorias_de_post(archivo)
  404. else:
  405. # evitando h1, h2
  406. if linea.startswith("##") or linea.startswith("#"):
  407. cabeza_post += " "
  408. else:
  409. cabeza_post += linea
  410. if len(cabeza_post) >= max_caracteres:
  411. break
  412. cabeza_post = cabeza_post[0:max_caracteres-1]
  413. if categorias:
  414. return (cabeza_post, cats)
  415. return cabeza_post
  416. def ultima_modificacion_archivo(archivo):
  417. """ Retorna una cadena indicando la fecha de ultima modificacion del
  418. `archivo' dado, se asume que `archivo' esta dentro la carpeta "monomotapa/src"
  419. Retorna una cadena vacia en caso de no poder abrir `archivo'
  420. """
  421. try:
  422. ts = strptime(ctime(os.path.getmtime("monomotapa/src/"+archivo+".md")))
  423. return strftime("%d %B %Y", ts)
  424. except OSError:
  425. return ""
  426. def SecsModificacionPostDesdeJson(archivo, dict_json):
  427. ''' dado el post con nombre 'archivo' busca en 'dict_json' el
  428. attribute 'date' y luego obtiene los segundos totales desde
  429. esa fecha.
  430. Si no encuentra 'date' para 'archivo' en 'dict.json'
  431. retorna los segundos totales desde la ultima modificacion
  432. del archivo de post directamente (usa os.path.getmtime)
  433. '''
  434. nombre = archivo.split('.md')[0] # no contar extension .md
  435. nombre_con_ruta = os.path.join("monomotapa/src/posts", archivo)
  436. date_str = dict_json.get('posts/'+nombre, {}).\
  437. get('attributes',{}).\
  438. get('date','')
  439. if date_str == '':
  440. # el post no tiene "date" en pages.json
  441. return os.path.getmtime(nombre_con_ruta)
  442. else:
  443. time_struct = strptime(date_str, '%Y-%m-%d')
  444. dt = datetime.datetime.fromtimestamp(mktime(time_struct))
  445. return (dt - datetime.datetime(1970,1,1)).total_seconds()
  446. def noticias_recientes(cantidad=11, max_caracteres=250,
  447. categoria=None, pagina=0):
  448. '''Devuelve una lista con hasta `cantidad' de posts mas recientes,
  449. un maximo de `max_caracteres' de caracteres del principio del post y
  450. el numero total de posts encontrados
  451. Si se proporciona `categoria' devuelve la lista de posts solamente
  452. pertenecientes esa categoria.
  453. Si `pagina' > 0 se devulve hasta `cantidad' numero de posts en el
  454. rango de [ cantidad*pagina : cantidad*(pagina+1)]
  455. Cada elemento de la lista devuelta contiene:
  456. (nombre_post, ultima_modificacion, cabeza_archivo, categorias)
  457. Al final se retorna: (lista_posts, numero_de_posts)
  458. '''
  459. lista_posts = []
  460. lp = []
  461. num_posts = 0
  462. posts_en_categoria = []
  463. if categoria is not None:
  464. #posts_en_categoria = categorias_list(categoria)[1]
  465. posts_en_categoria = categoriasList(categoria)[1]
  466. # categoria especial fotos
  467. if categoria == "fotos":
  468. l = []
  469. for p in posts_en_categoria:
  470. l.append(p + '.md')
  471. posts_en_categoria = l
  472. try:
  473. ow = os.walk("monomotapa/src/posts")
  474. p,d,files = ow.__next__()
  475. #p,d,files=ow.next()
  476. except OSError:
  477. print ("[posts] - Error: Can't os.walk() on monomotapa/src/posts except OSError.")
  478. else:
  479. for f in files:
  480. nombre_con_ruta = os.path.join("monomotapa/src/posts", f)
  481. if not f.endswith("~") and not f.startswith("#") and not f.startswith("."):
  482. secs_modificacion = SecsModificacionPostDesdeJson(f, json_pattrs)
  483. ultima_modificacion = os.path.getmtime(nombre_con_ruta)
  484. previewChars = json_pattrs.get('posts/'+f[:-3], {}).\
  485. get('attributes', {}).\
  486. get('preview-chars', max_caracteres)
  487. if categoria is not None:
  488. if f in posts_en_categoria:
  489. lp.append((secs_modificacion,
  490. ultima_modificacion,
  491. previewChars,
  492. f))
  493. num_posts += 1
  494. else:
  495. lp.append((secs_modificacion,
  496. ultima_modificacion,
  497. previewChars,
  498. f))
  499. num_posts += 1
  500. lp.sort()
  501. lp.reverse()
  502. # seleccionado por paginas
  503. lp = lp[cantidad*pagina : cantidad*(pagina+1)]
  504. # colocando fecha en formato
  505. for tupla in lp:
  506. cfecha = ctime(tupla[1])
  507. nombre_post = tupla[3].split(os.sep)[-1]
  508. previewChars = tupla[2]
  509. #contenido = cabeza_post(tupla[3], max_caracteres=previewChars)[0]
  510. #categorias = cabeza_post(tupla[3], max_caracteres=previewChars)[1]
  511. contenido = cabezaPost(tupla[3], max_caracteres=previewChars)[0]
  512. categorias = cabezaPost(tupla[3], max_caracteres=previewChars)[1]
  513. cabeza_archivo = markdown.markdown(escape(contenido))
  514. lista_posts.append((nombre_post[:-3], cfecha, \
  515. cabeza_archivo, categorias))
  516. return (lista_posts, num_posts)
  517. def noticias_relacionadas(cantidad=5, nombre=None):
  518. """Retorna una lista con posts relacionadas, es decir que tienen son de las
  519. mismas categorias que el post con nombre `nombre'.
  520. Cada elemento de la lista de posts contiene el nombre del post
  521. """
  522. #categorias = categorias_de_post(nombre) ## TODO: corregir categorias de post
  523. categorias = categoriasDePost(nombre)
  524. numero = 0
  525. if categorias is None:
  526. return None
  527. posts = []
  528. for categoria in categorias:
  529. #lista = categorias_list(categoria)[1] # nombres de posts
  530. lista = categoriasList(categoria)[1]
  531. numero += len(lista)
  532. for nombre_post in lista:
  533. if nombre_post + '.md' != nombre:
  534. posts.append(nombre_post)
  535. if numero >= cantidad:
  536. return posts
  537. return posts
  538. def rss_ultimos_posts_jinja(cantidad=15):
  539. """Retorna una lista de los ultimos posts preparados para
  540. ser renderizados (usando jinja) como un feed rss
  541. Examina cada post del mas reciente al menos reciente, en
  542. total `cantidad' posts. Por cada post devuelve:
  543. id: id which identifies the entry using a
  544. universally unique and permanent URI
  545. author: Get or set autor data. An author element is a dict containing a
  546. name, an email adress and a uri.
  547. category: A categories has the following fields:
  548. - *term* identifies the category
  549. - *scheme* identifies the categorization scheme via a URI.
  550. - *label* provides a human-readable label for display
  551. comments: Get or set the the value of comments which is the url of the
  552. comments page for the item.
  553. content: Get or set the cntent of the entry which contains or links to the
  554. complete content of the entry.
  555. description(no contiene): Get or set the description value which is the item synopsis.
  556. Description is an RSS only element.
  557. link: Get or set link data. An link element is a dict with the fields
  558. href, rel, type, hreflang, title, and length. Href is mandatory for
  559. ATOM.
  560. pubdate(no contiene): Get or set the pubDate of the entry which indicates when the entry
  561. was published.
  562. title: the title value of the entry. It should contain a human
  563. readable title for the entry.
  564. updated: the updated value which indicates the last time the entry
  565. was modified in a significant way.
  566. """
  567. lista_posts = []
  568. lp = []
  569. num_posts = 0
  570. try:
  571. ow = os.walk("monomotapa/src/posts")
  572. p,d,files=ow.next()
  573. except OSError:
  574. print ("[posts] - Error: Can't os.walk() on monomotapa/src/posts except OSError.")
  575. else:
  576. for f in files:
  577. nombre_con_ruta = os.path.join("monomotapa/src/posts", f)
  578. if not f.endswith("~") and not f.startswith("#") and not f.startswith("."):
  579. lp.append((os.path.getmtime(nombre_con_ruta), f))
  580. num_posts += 1
  581. if num_posts > cantidad:
  582. break
  583. lp.sort()
  584. lp.reverse()
  585. # colocando fecha en formato
  586. for tupla in lp:
  587. nombre_post = tupla[1].split(os.sep)[-1]
  588. #contenido = cabeza_post(tupla[1], max_caracteres=149999)
  589. contenido = cabezaPost(tupla[1], max_caracteres=149999)
  590. id_post = "https://rmgss.net/posts/"+nombre_post[:-3]
  591. #categorias = categorias_de_post(nombre_post)
  592. categorias = categoriasDePost(nombre_post)
  593. dict_categorias = {}
  594. c = ""
  595. for cat in categorias:
  596. c += cat + " "
  597. dict_categorias['label'] = c
  598. #dict_categorias['term'] = c
  599. html = markdown.markdown(escape(contenido), ['codehilite'])
  600. link = id_post
  601. pubdate = ctime(tupla[0])
  602. title = titulo_legible(nombre_post[:-3]) # no incluir '.md'
  603. updated = pubdate
  604. dict_feed_post = {
  605. "id":id_post,
  606. "author": "Rodrigo Garcia",
  607. "category" : categorias,
  608. "content": html,
  609. "link" : id_post,
  610. "updated" : updated,
  611. "title": title
  612. }
  613. lista_posts.append(dict_feed_post)
  614. return lista_posts
  615. ###### Define routes
  616. @app.errorhandler(404)
  617. def page_not_found(e):
  618. """ provides basic 404 page"""
  619. defaults = get_page_attributes('defaults.json')
  620. try:
  621. css = defaults['css']
  622. except KeyError:
  623. css = None
  624. pages = get_page_attributes('pages.json')
  625. if '404' in pages:
  626. if'css' in pages['404']:
  627. css = pages['404']['css']
  628. return render_template('static.html',
  629. title = "404::page not found", heading = "Page Not Found",
  630. navigation = top_navigation('404'),
  631. css = css,
  632. contents = Markup(
  633. "This page is not there, try somewhere else.")), 404
  634. @app.route('/users/', defaults={'page': 1})
  635. @app.route('/users/page/<int:page>')
  636. @app.route("/", defaults={'pagina':0})
  637. @app.route('/<int:pagina>')
  638. def index(pagina):
  639. """provides index page"""
  640. index_page = Page('index')
  641. lista_posts_recientes, total_posts = noticias_recientes(pagina=pagina)
  642. index_page.contexto['lista_posts_recientes'] = lista_posts_recientes
  643. index_page.contexto['total_posts'] = total_posts
  644. index_page.contexto['pagina_actual'] = int(pagina)
  645. return index_page.generate_page()
  646. # default route is it doe not exist elsewhere
  647. @app.route("/<path:page>")
  648. def staticpage(page):
  649. """ display a static page rendered from markdown in src
  650. i.e. displays /page or /page/ as long as src/page.md exists.
  651. srcfile, title and heading may be set in the pages global
  652. (ordered) dictionary but are not required"""
  653. static_page = Page(page)
  654. return static_page.generate_page()
  655. @app.route("/posts/<page>")
  656. def rposts(page):
  657. """ Mustra las paginas dentro la carpeta posts, no es coincidencia
  658. que en este ultimo directorio se guarden los posts.
  659. Ademas incrusta en el diccionario de contexto de la pagina la
  660. fecha de ultima modificacion del post
  661. """
  662. static_page = Page("posts/"+page)
  663. ultima_modificacion = ultima_modificacion_archivo("posts/"+page)
  664. static_page.contexto['relacionadas'] = noticias_relacionadas(nombre=page+".md")
  665. static_page.contexto['ultima_modificacion'] = ultima_modificacion
  666. return static_page.generate_page()
  667. @app.route("/posts")
  668. def indice_posts():
  669. """ Muestra una lista de todos los posts
  670. """
  671. lista_posts_fecha = posts_list()
  672. #lista_posts_categoria = categorias_list()
  673. lista_posts_categoria = categoriasList()
  674. static_page = Page("posts")
  675. static_page.contexto['lista_posts_fecha'] = lista_posts_fecha
  676. static_page.contexto['lista_posts_categoria'] = lista_posts_categoria
  677. return static_page.generate_page()
  678. @app.route("/posts/categorias")
  679. def lista_categorias():
  680. """ Muestra una lista de las categorias , los posts pertenecen
  681. a cada una y un conteo"""
  682. #lista_categorias = categorias_list()
  683. lista_categorias = categoriasList()
  684. static_page = Page("categorias")
  685. static_page.contexto['lista_posts_categoria'] = lista_categorias
  686. #return (str(lista_categorias))
  687. return static_page.generate_page()
  688. @app.route("/posts/categoria/<categoria>")
  689. def posts_de_categoria(categoria):
  690. """ Muestra los posts que perteneces a la categoria dada
  691. """
  692. lista_posts = []
  693. if categoria == "fotos": # caegoria especial fotos
  694. lista_posts, total_posts = noticias_recientes(max_caracteres=1250,categoria=categoria)
  695. static_page = Page("fotos")
  696. static_page.contexto['categoria_actual'] = categoria
  697. static_page.contexto['lista_posts_recientes'] = lista_posts
  698. return static_page.generate_page()
  699. #lista_posts = categorias_list(categoria=categoria)
  700. lista_posts = categoriasList(categoria=categoria)
  701. static_page = Page("categorias")
  702. static_page.contexto['categoria_actual'] = categoria
  703. static_page.contexto['lista_posts_categoria'] = lista_posts
  704. return static_page.generate_page()
  705. @app.route("/posts/recientes", defaults={'pagina':0})
  706. @app.route("/posts/recientes/<int:pagina>")
  707. def posts_recientes(pagina):
  708. """ muestra una lista de los posts mas recientes
  709. TODO: terminar
  710. """
  711. lista_posts, total_posts = noticias_recientes(max_caracteres=368,
  712. pagina=pagina)
  713. static_page = Page("recientes")
  714. static_page.contexto['lista_posts_recientes'] = lista_posts
  715. static_page.contexto['total_posts'] = total_posts
  716. static_page.contexto['pagina_actual'] = pagina
  717. #return (str(lista_posts))
  718. return static_page.generate_page()
  719. @app.route("/contacto", methods=['GET'])
  720. def contacto():
  721. tupla_captcha = captcha_pregunta_opciones_random()
  722. if tupla_captcha is None:
  723. return ("<br>Parece un error interno!</br>")
  724. pregunta = tupla_captcha[0]
  725. opciones = tupla_captcha[1]
  726. static_page = Page("contacto")
  727. static_page.contexto['pregunta'] = pregunta
  728. static_page.contexto['opciones'] = opciones
  729. return static_page.generate_page()
  730. @app.route("/contactoe", methods=['POST'])
  731. def comprobar_mensaje():
  732. """ Comprueba que el mensaje enviado por la caja de texto sea valido
  733. y si lo es, guarda un archivo de texto con los detalles"""
  734. errors = []
  735. if request.method == "POST":
  736. # comprobando validez
  737. nombre = request.form["nombre"]
  738. dir_respuesta = request.form['dir_respuesta']
  739. mensaje = request.form['mensaje']
  740. pregunta = request.form['pregunta']
  741. respuesta = request.form['respuesta']
  742. if len(mensaje) < 2 or mensaje.startswith(" "):
  743. errors.append("Mensaje invalido")
  744. if not captcha_comprobar_respuesta(pregunta, respuesta):
  745. errors.append("Captcha invalido")
  746. if len(errors) > 0:
  747. return str(errors)
  748. # guardando texto
  749. texto = "Remitente: "+nombre
  750. texto += "\nResponder_a: "+dir_respuesta
  751. texto += "\n--- mensaje ---\n"
  752. texto += mensaje
  753. # TODO: cambiar a direccion especificada en archivo de configuracion
  754. dt = datetime.datetime.now()
  755. nombre = "m_"+str(dt.day)+"_"+str(dt.month)+\
  756. "_"+str(dt.year)+"-"+str(dt.hour)+\
  757. "-"+str(dt.minute)+"-"+str(dt.second)
  758. with open(os.path.join("fbs",nombre), "wb") as f:
  759. f.write(texto.encode("utf-8"))
  760. return redirect("/mensaje_enviado", code=302)
  761. @app.route("/mensaje_enviado")
  762. def mensaje_enviado():
  763. static_page = Page("mensaje_enviado")
  764. return static_page.generate_page()
  765. @app.route("/rss")
  766. def rss_feed():
  767. """Genera la cadena rss con las 15 ultimas noticias del sitio
  768. TODO: Agregar mecenismo para no generar los rss feeds y solo
  769. devolver el archivo rss.xml generado anteriormente. Esto
  770. quiere decir solamente generar el rss_feed cuando se haya hecho
  771. un actualizacion en los posts mas reciente que la ultima vez
  772. que se genero el rss_feed
  773. """
  774. #return str(rss_ultimos_posts_jinja())
  775. return render_template("rss.html",
  776. contents = rss_ultimos_posts_jinja())
  777. #**vars(self)
  778. #)
  779. ##### specialized pages
  780. @app.route("/source")
  781. def source():
  782. """Display source files used to render a page"""
  783. source_page = Page('source', title = "view the source code",
  784. #heading = "Ver el código fuente",
  785. heading = "Ver el codigo fuente",
  786. internal_css = get_pygments_css())
  787. page = request.args.get('page')
  788. # get source for markdown if any. 404's for non-existant markdown
  789. # unless special page eg source
  790. pagesrc = source_page.get_page_src(page, 'src', 'md')
  791. special_pages = ['source', 'unit-tests', '404']
  792. if not page in special_pages and pagesrc is None:
  793. abort(404)
  794. # set enable_unit_tests to true in config.json to allow
  795. # unit tests to be run through the source page
  796. if app.config['enable_unit_tests']:
  797. contents = '''<p><a href="/unit-tests" class="button">Run unit tests
  798. </a></p>'''
  799. # render tests.py if needed
  800. if page == 'unit-tests':
  801. contents += heading('tests.py', 2)
  802. contents += render_pygments('tests.py', 'python')
  803. else:
  804. contents = ''
  805. # render views.py
  806. contents += heading('views.py', 2)
  807. contents += render_pygments(source_page.get_page_src('views.py'),
  808. 'python')
  809. # render markdown if present
  810. if pagesrc:
  811. contents += heading(os.path.basename(pagesrc), 2)
  812. contents += render_pygments(pagesrc, 'markdown')
  813. # render jinja templates
  814. contents += heading('base.html', 2)
  815. contents += render_pygments(
  816. source_page.get_page_src('base.html', 'templates'), 'html')
  817. template = source_page.get_template(page)
  818. contents += heading(template, 2)
  819. contents += render_pygments(
  820. source_page.get_page_src(template, 'templates'), 'html')
  821. return source_page.generate_page(contents)
  822. @app.route("/unit-tests")
  823. def unit_tests():
  824. """display results of unit tests"""
  825. unittests = Page('unit-tests', heading = "Test Results",
  826. internal_css = get_pygments_css())
  827. # exec unit tests in subprocess, capturing stderr
  828. capture = subprocess.Popen(["python", "tests.py"],
  829. stdout = subprocess.PIPE, stderr = subprocess.PIPE)
  830. output = capture.communicate()
  831. results = output[1]
  832. contents = '''<p>
  833. <a href="/unit-tests" class="button">Run unit tests</a>
  834. </p><br>\n
  835. <div class="output" style="background-color:'''
  836. if 'OK' in results:
  837. color = "#ddffdd"
  838. result = "TESTS PASSED"
  839. else:
  840. color = "#ffaaaa"
  841. result = "TESTS FAILING"
  842. contents += ('''%s">\n<strong>%s</strong>\n<pre>%s</pre>\n</div>\n'''
  843. % (color, result, results))
  844. # render test.py
  845. contents += heading('tests.py', 2)
  846. contents += render_pygments('tests.py', 'python')
  847. return unittests.generate_page(contents)