main.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. # -*- coding: utf-8 -*-
  2. import datetime
  3. import werkzeug
  4. from openerp import tools
  5. from openerp.addons.web import http
  6. from openerp.addons.web.controllers.main import login_redirect
  7. from openerp.addons.web.http import request
  8. from openerp.addons.website.models.website import slug
  9. from openerp.osv.orm import browse_record
  10. from openerp.tools.translate import _
  11. from openerp import SUPERUSER_ID
  12. from openerp.tools import html2plaintext
  13. class QueryURL(object):
  14. def __init__(self, path='', path_args=None, **args):
  15. self.path = path
  16. self.args = args
  17. self.path_args = set(path_args or [])
  18. def __call__(self, path=None, path_args=None, **kw):
  19. path = path or self.path
  20. for k, v in self.args.items():
  21. kw.setdefault(k, v)
  22. path_args = set(path_args or []).union(self.path_args)
  23. paths, fragments = [], []
  24. for key, value in kw.items():
  25. if value and key in path_args:
  26. if isinstance(value, browse_record):
  27. paths.append((key, slug(value)))
  28. else:
  29. paths.append((key, value))
  30. elif value:
  31. if isinstance(value, list) or isinstance(value, set):
  32. fragments.append(werkzeug.url_encode([(key, item) for item in value]))
  33. else:
  34. fragments.append(werkzeug.url_encode([(key, value)]))
  35. for key, value in paths:
  36. path += '/' + key + '/%s' % value
  37. if fragments:
  38. path += '?' + '&'.join(fragments)
  39. return path
  40. class WebsiteBlog(http.Controller):
  41. _blog_post_per_page = 20
  42. _post_comment_per_page = 10
  43. def nav_list(self):
  44. blog_post_obj = request.registry['blog.post']
  45. groups = blog_post_obj.read_group(
  46. request.cr, request.uid, [], ['name', 'create_date'],
  47. groupby="create_date", orderby="create_date desc", context=request.context)
  48. for group in groups:
  49. begin_date = datetime.datetime.strptime(group['__domain'][0][2], tools.DEFAULT_SERVER_DATETIME_FORMAT).date()
  50. end_date = datetime.datetime.strptime(group['__domain'][1][2], tools.DEFAULT_SERVER_DATETIME_FORMAT).date()
  51. group['date_begin'] = '%s' % datetime.date.strftime(begin_date, tools.DEFAULT_SERVER_DATE_FORMAT)
  52. group['date_end'] = '%s' % datetime.date.strftime(end_date, tools.DEFAULT_SERVER_DATE_FORMAT)
  53. return groups
  54. @http.route([
  55. '/blog',
  56. '/blog/page/<int:page>',
  57. ], type='http', auth="public", website=True)
  58. def blogs(self, page=1, **post):
  59. cr, uid, context = request.cr, request.uid, request.context
  60. blog_obj = request.registry['blog.post']
  61. total = blog_obj.search(cr, uid, [], count=True, context=context)
  62. pager = request.website.pager(
  63. url='/blog',
  64. total=total,
  65. page=page,
  66. step=self._blog_post_per_page,
  67. )
  68. post_ids = blog_obj.search(cr, uid, [], offset=(page-1)*self._blog_post_per_page, limit=self._blog_post_per_page, context=context)
  69. posts = blog_obj.browse(cr, uid, post_ids, context=context)
  70. blog_url = QueryURL('', ['blog', 'tag'])
  71. return request.website.render("website_blog.latest_blogs", {
  72. 'posts': posts,
  73. 'pager': pager,
  74. 'blog_url': blog_url,
  75. })
  76. @http.route([
  77. '/blog/<model("blog.blog"):blog>',
  78. '/blog/<model("blog.blog"):blog>/page/<int:page>',
  79. '/blog/<model("blog.blog"):blog>/tag/<model("blog.tag"):tag>',
  80. '/blog/<model("blog.blog"):blog>/tag/<model("blog.tag"):tag>/page/<int:page>',
  81. ], type='http', auth="public", website=True)
  82. def blog(self, blog=None, tag=None, page=1, **opt):
  83. """ Prepare all values to display the blog.
  84. :return dict values: values for the templates, containing
  85. - 'blog': current blog
  86. - 'blogs': all blogs for navigation
  87. - 'pager': pager of posts
  88. - 'tag': current tag
  89. - 'tags': all tags, for navigation
  90. - 'nav_list': a dict [year][month] for archives navigation
  91. - 'date': date_begin optional parameter, used in archives navigation
  92. - 'blog_url': help object to create URLs
  93. """
  94. date_begin, date_end = opt.get('date_begin'), opt.get('date_end')
  95. cr, uid, context = request.cr, request.uid, request.context
  96. blog_post_obj = request.registry['blog.post']
  97. blog_obj = request.registry['blog.blog']
  98. blog_ids = blog_obj.search(cr, uid, [], order="create_date asc", context=context)
  99. blogs = blog_obj.browse(cr, uid, blog_ids, context=context)
  100. domain = []
  101. if blog:
  102. domain += [('blog_id', '=', blog.id)]
  103. if tag:
  104. domain += [('tag_ids', 'in', tag.id)]
  105. if date_begin and date_end:
  106. domain += [("create_date", ">=", date_begin), ("create_date", "<=", date_end)]
  107. blog_url = QueryURL('', ['blog', 'tag'], blog=blog, tag=tag, date_begin=date_begin, date_end=date_end)
  108. post_url = QueryURL('', ['blogpost'], tag_id=tag and tag.id or None, date_begin=date_begin, date_end=date_end)
  109. blog_post_ids = blog_post_obj.search(cr, uid, domain, order="create_date desc", context=context)
  110. blog_posts = blog_post_obj.browse(cr, uid, blog_post_ids, context=context)
  111. pager = request.website.pager(
  112. url=blog_url(),
  113. total=len(blog_posts),
  114. page=page,
  115. step=self._blog_post_per_page,
  116. )
  117. pager_begin = (page - 1) * self._blog_post_per_page
  118. pager_end = page * self._blog_post_per_page
  119. blog_posts = blog_posts[pager_begin:pager_end]
  120. tags = blog.all_tags()[blog.id]
  121. values = {
  122. 'blog': blog,
  123. 'blogs': blogs,
  124. 'tags': tags,
  125. 'tag': tag,
  126. 'blog_posts': blog_posts,
  127. 'pager': pager,
  128. 'nav_list': self.nav_list(),
  129. 'blog_url': blog_url,
  130. 'post_url': post_url,
  131. 'date': date_begin,
  132. }
  133. response = request.website.render("website_blog.blog_post_short", values)
  134. return response
  135. @http.route([
  136. '''/blog/<model("blog.blog"):blog>/post/<model("blog.post", "[('blog_id','=',blog[0])]"):blog_post>''',
  137. ], type='http', auth="public", website=True)
  138. def blog_post(self, blog, blog_post, tag_id=None, page=1, enable_editor=None, **post):
  139. """ Prepare all values to display the blog.
  140. :return dict values: values for the templates, containing
  141. - 'blog_post': browse of the current post
  142. - 'blog': browse of the current blog
  143. - 'blogs': list of browse records of blogs
  144. - 'tag': current tag, if tag_id in parameters
  145. - 'tags': all tags, for tag-based navigation
  146. - 'pager': a pager on the comments
  147. - 'nav_list': a dict [year][month] for archives navigation
  148. - 'next_post': next blog post, to direct the user towards the next interesting post
  149. """
  150. cr, uid, context = request.cr, request.uid, request.context
  151. tag_obj = request.registry['blog.tag']
  152. blog_post_obj = request.registry['blog.post']
  153. date_begin, date_end = post.get('date_begin'), post.get('date_end')
  154. pager_url = "/blogpost/%s" % blog_post.id
  155. pager = request.website.pager(
  156. url=pager_url,
  157. total=len(blog_post.website_message_ids),
  158. page=page,
  159. step=self._post_comment_per_page,
  160. scope=7
  161. )
  162. pager_begin = (page - 1) * self._post_comment_per_page
  163. pager_end = page * self._post_comment_per_page
  164. comments = blog_post.website_message_ids[pager_begin:pager_end]
  165. tag = None
  166. if tag_id:
  167. tag = request.registry['blog.tag'].browse(request.cr, request.uid, int(tag_id), context=request.context)
  168. post_url = QueryURL('', ['blogpost'], blogpost=blog_post, tag_id=tag_id, date_begin=date_begin, date_end=date_end)
  169. blog_url = QueryURL('', ['blog', 'tag'], blog=blog_post.blog_id, tag=tag, date_begin=date_begin, date_end=date_end)
  170. if not blog_post.blog_id.id == blog.id:
  171. return request.redirect("/blog/%s/post/%s" % (slug(blog_post.blog_id), slug(blog_post)))
  172. tags = tag_obj.browse(cr, uid, tag_obj.search(cr, uid, [], context=context), context=context)
  173. # Find next Post
  174. all_post_ids = blog_post_obj.search(cr, uid, [('blog_id', '=', blog.id)], context=context)
  175. # should always return at least the current post
  176. current_blog_post_index = all_post_ids.index(blog_post.id)
  177. next_post_id = all_post_ids[0 if current_blog_post_index == len(all_post_ids) - 1 \
  178. else current_blog_post_index + 1]
  179. next_post = next_post_id and blog_post_obj.browse(cr, uid, next_post_id, context=context) or False
  180. values = {
  181. 'tags': tags,
  182. 'tag': tag,
  183. 'blog': blog,
  184. 'blog_post': blog_post,
  185. 'main_object': blog_post,
  186. 'nav_list': self.nav_list(),
  187. 'enable_editor': enable_editor,
  188. 'next_post': next_post,
  189. 'date': date_begin,
  190. 'post_url': post_url,
  191. 'blog_url': blog_url,
  192. 'pager': pager,
  193. 'comments': comments,
  194. }
  195. response = request.website.render("website_blog.blog_post_complete", values)
  196. request.session[request.session_id] = request.session.get(request.session_id, [])
  197. if not (blog_post.id in request.session[request.session_id]):
  198. request.session[request.session_id].append(blog_post.id)
  199. # Increase counter
  200. blog_post_obj.write(cr, SUPERUSER_ID, [blog_post.id], {
  201. 'visits': blog_post.visits+1,
  202. },context=context)
  203. return response
  204. def _blog_post_message(self, user, blog_post_id=0, **post):
  205. cr, uid, context = request.cr, request.uid, request.context
  206. blog_post = request.registry['blog.post']
  207. partner_obj = request.registry['res.partner']
  208. if uid != request.website.user_id.id:
  209. partner_ids = [user.partner_id.id]
  210. else:
  211. partner_ids = blog_post._find_partner_from_emails(
  212. cr, SUPERUSER_ID, 0, [post.get('email')], context=context)
  213. if not partner_ids or not partner_ids[0]:
  214. partner_ids = [partner_obj.create(cr, SUPERUSER_ID, {'name': post.get('name'), 'email': post.get('email')}, context=context)]
  215. message_id = blog_post.message_post(
  216. cr, SUPERUSER_ID, int(blog_post_id),
  217. body=post.get('comment'),
  218. type='comment',
  219. subtype='mt_comment',
  220. author_id=partner_ids[0],
  221. path=post.get('path', False),
  222. context=context)
  223. return message_id
  224. @http.route(['/blogpost/comment'], type='http', auth="public", website=True)
  225. def blog_post_comment(self, blog_post_id=0, **post):
  226. cr, uid, context = request.cr, request.uid, request.context
  227. if not request.session.uid:
  228. return login_redirect()
  229. if post.get('comment'):
  230. user = request.registry['res.users'].browse(cr, uid, uid, context=context)
  231. blog_post = request.registry['blog.post']
  232. blog_post.check_access_rights(cr, uid, 'read')
  233. self._blog_post_message(user, blog_post_id, **post)
  234. blog_post = request.registry['blog.post'].browse(cr, uid, int(blog_post_id), context=context)
  235. return werkzeug.utils.redirect("/blog/%s/post/%s#comments" % (slug(blog_post.blog_id), slug(blog_post)))
  236. def _get_discussion_detail(self, ids, publish=False, **post):
  237. cr, uid, context = request.cr, request.uid, request.context
  238. values = []
  239. mail_obj = request.registry.get('mail.message')
  240. for message in mail_obj.browse(cr, SUPERUSER_ID, ids, context=context):
  241. values.append({
  242. "id": message.id,
  243. "author_name": message.author_id.name,
  244. "author_image": message.author_id.image and \
  245. ("data:image/png;base64,%s" % message.author_id.image) or \
  246. '/website_blog/static/src/img/anonymous.png',
  247. "date": message.date,
  248. 'body': html2plaintext(message.body),
  249. 'website_published' : message.website_published,
  250. 'publish' : publish,
  251. })
  252. return values
  253. @http.route(['/blogpost/post_discussion'], type='json', auth="public", website=True)
  254. def post_discussion(self, blog_post_id, **post):
  255. cr, uid, context = request.cr, request.uid, request.context
  256. publish = request.registry['res.users'].has_group(cr, uid, 'base.group_website_publisher')
  257. user = request.registry['res.users'].browse(cr, uid, uid, context=context)
  258. id = self._blog_post_message(user, blog_post_id, **post)
  259. return self._get_discussion_detail([id], publish, **post)
  260. @http.route('/blogpost/new', type='http', auth="public", website=True)
  261. def blog_post_create(self, blog_id, **post):
  262. cr, uid, context = request.cr, request.uid, request.context
  263. new_blog_post_id = request.registry['blog.post'].create(cr, uid, {
  264. 'blog_id': blog_id,
  265. 'name': _("Blog Post Title"),
  266. 'subtitle': _("Subtitle"),
  267. 'content': '',
  268. 'website_published': False,
  269. }, context=context)
  270. new_blog_post = request.registry['blog.post'].browse(cr, uid, new_blog_post_id, context=context)
  271. return werkzeug.utils.redirect("/blog/%s/post/%s?enable_editor=1" % (slug(new_blog_post.blog_id), slug(new_blog_post)))
  272. @http.route('/blogpost/duplicate', type='http', auth="public", website=True)
  273. def blog_post_copy(self, blog_post_id, **post):
  274. """ Duplicate a blog.
  275. :param blog_post_id: id of the blog post currently browsed.
  276. :return redirect to the new blog created
  277. """
  278. cr, uid, context = request.cr, request.uid, request.context
  279. create_context = dict(context, mail_create_nosubscribe=True)
  280. nid = request.registry['blog.post'].copy(cr, uid, int(blog_post_id), {}, context=create_context)
  281. new_blog_post = request.registry['blog.post'].browse(cr, uid, nid, context=context)
  282. post = request.registry['blog.post'].browse(cr, uid, nid, context)
  283. return werkzeug.utils.redirect("/blog/%s/post/%s?enable_editor=1" % (slug(post.blog_id), slug(new_blog_post)))
  284. @http.route('/blogpost/get_discussion/', type='json', auth="public", website=True)
  285. def discussion(self, post_id=0, path=None, count=False, **post):
  286. cr, uid, context = request.cr, request.uid, request.context
  287. mail_obj = request.registry.get('mail.message')
  288. domain = [('res_id', '=', int(post_id)), ('model', '=', 'blog.post'), ('path', '=', path)]
  289. #check current user belongs to website publisher group
  290. publish = request.registry['res.users'].has_group(cr, uid, 'base.group_website_publisher')
  291. if not publish:
  292. domain.append(('website_published', '=', True))
  293. ids = mail_obj.search(cr, SUPERUSER_ID, domain, count=count)
  294. if count:
  295. return ids
  296. return self._get_discussion_detail(ids, publish, **post)
  297. @http.route('/blogpost/get_discussions/', type='json', auth="public", website=True)
  298. def discussions(self, post_id=0, paths=None, count=False, **post):
  299. ret = []
  300. for path in paths:
  301. result = self.discussion(post_id=post_id, path=path, count=count, **post)
  302. ret.append({"path": path, "val": result})
  303. return ret
  304. @http.route('/blogpost/change_background', type='json', auth="public", website=True)
  305. def change_bg(self, post_id=0, image=None, **post):
  306. if not post_id:
  307. return False
  308. return request.registry['blog.post'].write(request.cr, request.uid, [int(post_id)], {'background_image': image}, request.context)
  309. @http.route('/blog/get_user/', type='json', auth="public", website=True)
  310. def get_user(self, **post):
  311. return [False if request.session.uid else True]