[IMP] website_sale: clean xml view
[odoo/odoo.git] / addons / website / controllers / main.py
1 # -*- coding: utf-8 -*-
2 import base64
3 import json
4 import logging
5 import cStringIO
6
7 from PIL import Image
8
9 import openerp
10 from openerp.addons.web import http
11 from openerp.addons.web.http import request
12 import werkzeug
13 import werkzeug.exceptions
14 import werkzeug.wrappers
15 import hashlib
16 import os
17
18 logger = logging.getLogger(__name__)
19
20
21 def auth_method_public():
22     registry = openerp.modules.registry.RegistryManager.get(request.db)
23     if not request.session.uid:
24         request.uid = registry['website'].get_public_user().id
25     else:
26         request.uid = request.session.uid
27 http.auth_methods['public'] = auth_method_public
28
29
30 class Website(openerp.addons.web.controllers.main.Home):
31     @http.route('/', type='http', auth="admin")
32     def index(self, **kw):
33         return self.page("website.homepage")
34
35     @http.route('/admin', type='http', auth="none")
36     def admin(self, *args, **kw):
37         return super(Website, self).index(*args, **kw)
38
39     @http.route('/pagenew/<path:path>', type='http', auth="admin")
40     def pagenew(self, path):
41         imd = request.registry['ir.model.data']
42         view = request.registry['ir.ui.view']
43         view_model, view_id = imd.get_object_reference(request.cr, request.uid, 'website', 'default_page')
44         newview_id = view.copy(request.cr, request.uid, view_id)
45         newview = view.browse(request.cr, request.uid, newview_id, context={})
46         newview.write({
47             'arch': newview.arch.replace("website.default_page", path),
48             'name': "page/%s" % path
49         })
50         if '.' in path:
51             module, idname = path.split('.')
52         else:
53             module = False
54             idname = path
55         imd.create(request.cr, request.uid, {
56             'name': idname,
57             'module': module,
58             'model': 'ir.ui.view',
59             'res_id': newview_id,
60             'noupdate': True
61         })
62         return werkzeug.utils.redirect("/page/%s" % path)
63
64     @http.route('/page/<path:path>', type='http', auth="admin")
65     def page(self, path, **kwargs):
66         website = request.registry.get("website")
67         values = website.get_rendering_context({
68             'path': path
69         })
70         try:
71             html = website.render(path, values)
72         except ValueError:
73             html = website.render('website.404', values)
74         return html
75
76     @http.route('/website/customize_template_toggle', type='json', auth='admin') # FIXME: auth
77     def customize_template_set(self, view_id):
78         view_obj = request.registry.get("ir.ui.view")
79         view = view_obj.browse(request.cr, request.uid, int(view_id), context=request.context)
80         if view.inherit_id:
81             print '*', view.inherit_id
82             value = False
83         else:
84             value = view.inherit_option_id and view.inherit_option_id.id or False
85             print '*', view.inherit_id, 'no', value, view
86         view_obj.write(request.cr, request.uid, [view_id], {
87             'inherit_id': value
88         }, context=request.context)
89         print 'Wrote', value, 'on', view_id
90         return True
91
92     @http.route('/website/customize_template_get', type='json', auth='admin') # FIXME: auth
93     def customize_template_get(self, xml_id):
94         view = request.registry.get("ir.ui.view")
95         views = view._views_get(request.cr, request.uid, xml_id, request.context)
96         done = {}
97         result = []
98         for v in views:
99             if v.inherit_option_id:
100                 if v.inherit_option_id.id not in done:
101                     result.append({
102                         'name': v.inherit_option_id.name,
103                         'header': True,
104                         'active': False
105                     })
106                     done[v.inherit_option_id.id] = True
107                 result.append({
108                     'name': v.name,
109                     'id': v.id,
110                     'header': False,
111                     'active': v.inherit_id.id == v.inherit_option_id.id
112                 })
113         return result
114
115     @http.route('/website/attach', type='http', auth='admin') # FIXME: auth
116     def attach(self, CKEditorFuncNum, CKEditor, langCode, upload):
117         req = request.httprequest
118         if req.method != 'POST':
119             return werkzeug.exceptions.MethodNotAllowed(valid_methods=['POST'])
120
121         url = message = None
122         try:
123             attachment_id = request.registry['ir.attachment'].create(request.cr, request.uid, {
124                 'name': upload.filename,
125                 'datas': base64.encodestring(upload.read()),
126                 'datas_fname': upload.filename,
127                 'res_model': 'ir.ui.view',
128             }, request.context)
129             # FIXME: auth=user... no good.
130             url = '/website/attachment/%d' % attachment_id
131         except Exception, e:
132             logger.exception("Failed to upload image to attachment")
133             message = str(e)
134
135         return """<script type='text/javascript'>
136             window.parent.CKEDITOR.tools.callFunction(%d, %s, %s);
137         </script>""" % (int(CKEditorFuncNum), json.dumps(url), json.dumps(message))
138
139     @http.route('/website/attachment/<int:id>', type='http', auth="admin")
140     def attachment(self, id):
141         # FIXME: can't use Binary.image because auth=user and website attachments need to be public
142         attachment = request.registry['ir.attachment'].browse(
143             request.cr, request.uid, id, request.context)
144
145         buf = cStringIO.StringIO(base64.decodestring(attachment.datas))
146
147         image = Image.open(buf)
148         image.thumbnail((1024, 768), Image.ANTIALIAS)
149
150         response = werkzeug.wrappers.Response(status=200, mimetype={
151             'PNG': 'image/png',
152             'JPEG': 'image/jpeg',
153             'GIF': 'image/gif',
154         }[image.format])
155         image.save(response.stream, image.format)
156
157         return response
158
159     @http.route('/website/image', type='http', auth="public")
160     def image(self, model, id, field, **kw):
161         last_update = '__last_update'
162         Model = request.registry[model]
163         headers = [('Content-Type', 'image/png')]
164         etag = request.httprequest.headers.get('If-None-Match')
165         hashed_session = hashlib.md5(request.session_id).hexdigest()
166         retag = hashed_session
167         try:
168             if etag:
169                 date = Model.read(request.cr, request.uid, [id], [last_update], request.context)[0].get(last_update)
170                 if hashlib.md5(date).hexdigest() == etag:
171                     return werkzeug.wrappers.Response(status=304)
172
173             res = Model.read(request.cr, request.uid, [id], [last_update, field], request.context)[0]
174             retag = hashlib.md5(res.get(last_update)).hexdigest()
175             image_base64 = res.get(field)
176
177             if kw.get('resize'):
178                 resize = kw.get('resize').split(',')
179                 if len(resize) == 2 and int(resize[0]) and int(resize[1]):
180                     width = int(resize[0])
181                     height = int(resize[1])
182                     # resize maximum 500*500
183                     if width > 500: width = 500
184                     if height > 500: height = 500
185                     image_base64 = openerp.tools.image_resize_image(base64_source=image_base64, size=(width, height), encoding='base64', filetype='PNG')
186
187             image_data = base64.b64decode(image_base64)
188         except Exception:
189             image_data = open(os.path.join(http.addons_manifest['web']['addons_path'], 'web', 'static', 'src', 'img', 'placeholder.png'), 'rb').read()
190
191         headers.append(('ETag', retag))
192         headers.append(('Content-Length', len(image_data)))
193         try:
194             ncache = int(kw.get('cache'))
195             headers.append(('Cache-Control', 'no-cache' if ncache == 0 else 'max-age=%s' % (ncache)))
196         except:
197             pass
198         return request.make_response(image_data, headers)
199
200     @http.route(['/website/publish/'], type='http', auth="public")
201     def publish(self, **post):
202         _id = int(post['id'])
203         _object = request.registry[post['object']]
204
205         obj = _object.browse(request.cr, request.uid, _id)
206         _object.write(request.cr, request.uid, [_id], {'website_published': not obj.website_published})
207         obj = _object.browse(request.cr, request.uid, _id)
208
209         return obj.website_published and "1" or "0"
210
211 # vim:expandtab:tabstop=4:softtabstop=4:shiftwidth=4: