def sitemap_xml_index(self): cr, uid, context = request.cr, ecore.SUPERUSER_ID, request.context ira = request.registry['ir.attachment'] iuv = request.registry['ir.ui.view'] mimetype ='application/xml;charset=utf-8' content = None def create_sitemap(url, content): return ira.create(cr, uid, dict( datas=content.encode('base64'), mimetype=mimetype, type='binary', name=url, url=url, ), context=context) sitemap = ira.search_read(cr, uid, [('url', '=' , '/sitemap.xml'), ('type', '=', 'binary')], ('datas', 'create_date'), context=context) if sitemap: # Check if stored version is still valid server_format = ecore.tools.misc.DEFAULT_SERVER_DATETIME_FORMAT create_date = datetime.datetime.strptime(sitemap[0]['create_date'], server_format) delta = datetime.datetime.now() - create_date if delta < SITEMAP_CACHE_TIME: content = sitemap[0]['datas'].decode('base64') if not content: # Remove all sitemaps in ir.attachments as we're going to regenerated them sitemap_ids = ira.search(cr, uid, [('url', '=like' , '/sitemap%.xml'), ('type', '=', 'binary')], context=context) if sitemap_ids: ira.unlink(cr, uid, sitemap_ids, context=context) pages = 0 locs = request.website.sudo(user=request.website.user_id.id).enumerate_pages() while True: values = { 'locs': islice(locs, 0, LOC_PER_SITEMAP), 'url_root': request.httprequest.url_root[:-1], } urls = iuv.render(cr, uid, 'website.sitemap_locs', values, context=context) if urls.strip(): content = iuv.render(cr, uid, 'website.sitemap_xml', dict(content=urls), context=context) pages += 1 last = create_sitemap('/sitemap-%d.xml' % pages, content) else: break if not pages: return request.not_found() elif pages == 1: ira.write(cr, uid, last, dict(url="/sitemap.xml", name="/sitemap.xml"), context=context) else: # Sitemaps must be split in several smaller files with a sitemap index content = iuv.render(cr, uid, 'website.sitemap_index_xml', dict( pages=range(1, pages + 1), url_root=request.httprequest.url_root, ), context=context) create_sitemap('/sitemap.xml', content) return request.make_response(content, [('Content-Type', mimetype)])
def print_saleorder(self): cr, uid, context = request.cr, SUPERUSER_ID, request.context sale_order_id = request.session.get('sale_last_order_id') if sale_order_id: pdf = request.registry['report'].get_pdf(cr, uid, [sale_order_id], 'sale.report_saleorder', data=None, context=context) pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))] return request.make_response(pdf, headers=pdfhttpheaders) else: return request.redirect('/shop')
def livechat_lib(self, ext, **kwargs): asset = AssetsBundle("im_livechat.external_lib") mock_attachment = getattr(asset, ext)() if isinstance(mock_attachment, list): # suppose that CSS asset will not required to be split in pages mock_attachment = mock_attachment[0] # can't use /web/content directly because we don't have attachment ids (attachments must be created) status, headers, content = binary_content(id=mock_attachment.id, unique=asset.checksum) content_base64 = base64.b64decode(content) if content else '' headers.append(('Content-Length', len(content_base64))) return request.make_response(content_base64, headers)
def slide_download(self, slide): if slide.download_security == 'public' or (slide.download_security == 'user' and request.session.uid): filecontent = base64.b64decode(slide.datas) disposition = 'attachment; filename=%s.pdf' % werkzeug.urls.url_quote(slide.name) return request.make_response( filecontent, [('Content-Type', 'application/pdf'), ('Content-Length', len(filecontent)), ('Content-Disposition', disposition)]) elif not request.session.uid and slide.download_security == 'user': return werkzeug.utils.redirect('/web?redirect=/slides/slide/%s' % (slide.id)) return request.website.render("website.403")
def livechat_lib(self, ext, **kwargs): asset = AssetsBundle("im_livechat.external_lib") mock_attachment = getattr(asset, ext)() if isinstance( mock_attachment, list ): # suppose that CSS asset will not required to be split in pages mock_attachment = mock_attachment[0] # can't use /web/content directly because we don't have attachment ids (attachments must be created) status, headers, content = binary_content(id=mock_attachment.id, unique=asset.checksum) content_base64 = base64.b64decode(content) if content else '' headers.append(('Content-Length', len(content_base64))) return request.make_response(content_base64, headers)
def slide_download(self, slide): if slide.download_security == 'public' or ( slide.download_security == 'user' and request.session.uid): filecontent = base64.b64decode(slide.datas) disposition = 'attachment; filename=%s.pdf' % werkzeug.urls.url_quote( slide.name) return request.make_response( filecontent, [('Content-Type', 'application/pdf'), ('Content-Length', len(filecontent)), ('Content-Disposition', disposition)]) elif not request.session.uid and slide.download_security == 'user': return werkzeug.utils.redirect('/web?redirect=/slides/slide/%s' % (slide.id)) return request.website.render("website.403")
def avatar(self, res_model, res_id, partner_id): headers = [[('Content-Type', 'image/png')]] content = 'R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' # default image is one white pixel if res_model in request.env: try: # if the current user has access to the document, get the partner avatar as sudo() request.env[res_model].browse(res_id).check_access_rule('read') if partner_id in request.env[res_model].browse(res_id).sudo().exists().message_ids.mapped('author_id').ids: status, headers, content = binary_content(model='res.partner', id=partner_id, field='image_medium', default_mimetype='image/png', env=request.env(user=ecore.SUPERUSER_ID)) if status == 304: return werkzeug.wrappers.Response(status=304) except AccessError: pass image_base64 = base64.b64decode(content) headers.append(('Content-Length', len(image_base64))) response = request.make_response(image_base64, headers) response.status = str(status) return response
def avatar(self, res_model, res_id, partner_id): headers = [[('Content-Type', 'image/png')]] content = 'R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' # default image is one white pixel if res_model in request.env: try: # if the current user has access to the document, get the partner avatar as sudo() request.env[res_model].browse(res_id).check_access_rule('read') if partner_id in request.env[res_model].browse(res_id).sudo( ).exists().message_ids.mapped('author_id').ids: status, headers, content = binary_content( model='res.partner', id=partner_id, field='image_medium', default_mimetype='image/png', env=request.env(user=ecore.SUPERUSER_ID)) if status == 304: return werkzeug.wrappers.Response(status=304) except AccessError: pass image_base64 = base64.b64decode(content) headers.append(('Content-Length', len(image_base64))) response = request.make_response(image_base64, headers) response.status = str(status) return response
def status_http(self): resp = """ <!DOCTYPE HTML> <html> <head> <title>eCore's PosBox</title> <style> body { width: 480px; margin: 60px auto; font-family: sans-serif; text-align: justify; color: #6B6B6B; } .device { border-bottom: solid 1px rgb(216,216,216); padding: 9px; } .device:nth-child(2n) { background:rgb(240,240,240); } </style> </head> <body> <h1>Hardware Status</h1> <p>The list of enabled drivers and their status</p> """ statuses = self.get_status() for driver in statuses: status = statuses[driver] if status['status'] == 'connecting': color = 'black' elif status['status'] == 'connected': color = 'green' else: color = 'red' resp += "<h3 style='color:" + color + ";'>" + driver + ' : ' + status[ 'status'] + "</h3>\n" resp += "<ul>\n" for msg in status['messages']: resp += '<li>' + msg + '</li>\n' resp += "</ul>\n" resp += """ <h2>Connected Devices</h2> <p>The list of connected USB devices as seen by the posbox</p> """ devices = commands.getoutput("lsusb").split('\n') count = 0 resp += "<div class='devices'>\n" for device in devices: device_name = device[device.find('ID') + 2:] device_id = device_name.split()[0] if not (device_id in BANNED_DEVICES): resp += "<div class='device' data-device='" + device + "'>" + device_name + "</div>\n" count += 1 if count == 0: resp += "<div class='device'>No USB Device Found</div>" resp += "</div>\n</body>\n</html>\n\n" return request.make_response( resp, { 'Cache-Control': 'no-cache', 'Content-Type': 'text/html; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', })
def sitemap_xml_index(self): cr, uid, context = request.cr, ecore.SUPERUSER_ID, request.context ira = request.registry['ir.attachment'] iuv = request.registry['ir.ui.view'] mimetype ='application/xml;charset=utf-8' content = None def create_sitemap(url, content): ira.create(cr, uid, dict( datas=content.encode('base64'), mimetype=mimetype, type='binary', name=url, url=url, ), context=context) sitemap = ira.search_read(cr, uid, [('url', '=' , '/sitemap.xml'), ('type', '=', 'binary')], ('datas', 'create_date'), context=context) if sitemap: # Check if stored version is still valid server_format = ecore.tools.misc.DEFAULT_SERVER_DATETIME_FORMAT create_date = datetime.datetime.strptime(sitemap[0]['create_date'], server_format) delta = datetime.datetime.now() - create_date if delta < SITEMAP_CACHE_TIME: content = sitemap[0]['datas'].decode('base64') if not content: # Remove all sitemaps in ir.attachments as we're going to regenerated them sitemap_ids = ira.search(cr, uid, [('url', '=like' , '/sitemap%.xml'), ('type', '=', 'binary')], context=context) if sitemap_ids: ira.unlink(cr, uid, sitemap_ids, context=context) pages = 0 first_page = None locs = request.website.sudo(user=request.website.user_id.id).enumerate_pages() while True: start = pages * LOC_PER_SITEMAP values = { 'locs': islice(locs, start, start + LOC_PER_SITEMAP), 'url_root': request.httprequest.url_root[:-1], } urls = iuv.render(cr, uid, 'website.sitemap_locs', values, context=context) if urls.strip(): page = iuv.render(cr, uid, 'website.sitemap_xml', dict(content=urls), context=context) if not first_page: first_page = page pages += 1 create_sitemap('/sitemap-%d.xml' % pages, page) else: break if not pages: return request.not_found() elif pages == 1: content = first_page else: # Sitemaps must be split in several smaller files with a sitemap index content = iuv.render(cr, uid, 'website.sitemap_index_xml', dict( pages=range(1, pages + 1), url_root=request.httprequest.url_root, ), context=context) create_sitemap('/sitemap.xml', content) return request.make_response(content, [('Content-Type', mimetype)])
def status_http(self): resp = """ <!DOCTYPE HTML> <html> <head> <title>eCore's PosBox</title> <style> body { width: 480px; margin: 60px auto; font-family: sans-serif; text-align: justify; color: #6B6B6B; } .device { border-bottom: solid 1px rgb(216,216,216); padding: 9px; } .device:nth-child(2n) { background:rgb(240,240,240); } </style> </head> <body> <h1>Hardware Status</h1> <p>The list of enabled drivers and their status</p> """ statuses = self.get_status() for driver in statuses: status = statuses[driver] if status['status'] == 'connecting': color = 'black' elif status['status'] == 'connected': color = 'green' else: color = 'red' resp += "<h3 style='color:"+color+";'>"+driver+' : '+status['status']+"</h3>\n" resp += "<ul>\n" for msg in status['messages']: resp += '<li>'+msg+'</li>\n' resp += "</ul>\n" resp += """ <h2>Connected Devices</h2> <p>The list of connected USB devices as seen by the posbox</p> """ devices = commands.getoutput("lsusb").split('\n') count = 0 resp += "<div class='devices'>\n" for device in devices: device_name = device[device.find('ID')+2:] device_id = device_name.split()[0] if not (device_id in BANNED_DEVICES): resp+= "<div class='device' data-device='"+device+"'>"+device_name+"</div>\n" count += 1 if count == 0: resp += "<div class='device'>No USB Device Found</div>" resp += "</div>\n</body>\n</html>\n\n" return request.make_response(resp,{ 'Cache-Control': 'no-cache', 'Content-Type': 'text/html; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', })
def export_xls(self, data, token): jdata = json.loads(data) nbr_measures = jdata['nbr_measures'] workbook = xlwt.Workbook() worksheet = workbook.add_sheet(jdata['title'][:30]) header_bold = xlwt.easyxf( "font: bold on; pattern: pattern solid, fore_colour gray25;") header_plain = xlwt.easyxf( "pattern: pattern solid, fore_colour gray25;") bold = xlwt.easyxf("font: bold on;") # Step 1: writing headers headers = jdata['headers'] # x,y: current coordinates # carry: queue containing cell information when a cell has a >= 2 height # and the drawing code needs to add empty cells below x, y, carry = 1, 0, deque() for i, header_row in enumerate(headers): worksheet.write(i, 0, '', header_plain) for header in header_row: while (carry and carry[0]['x'] == x): cell = carry.popleft() for i in range(nbr_measures): worksheet.write(y, x + i, '', header_plain) if cell['height'] > 1: carry.append({'x': x, 'height': cell['height'] - 1}) x = x + nbr_measures style = header_plain if 'expanded' in header else header_bold for i in range(header['width']): worksheet.write(y, x + i, header['title'] if i == 0 else '', style) if header['height'] > 1: carry.append({'x': x, 'height': header['height'] - 1}) x = x + header['width'] while (carry and carry[0]['x'] == x): cell = carry.popleft() for i in range(nbr_measures): worksheet.write(y, x + i, '', header_plain) if cell['height'] > 1: carry.append({'x': x, 'height': cell['height'] - 1}) x = x + nbr_measures x, y = 1, y + 1 # Step 2: measure row if nbr_measures > 1: worksheet.write(y, 0, '', header_plain) for measure in jdata['measure_row']: style = header_bold if measure['is_bold'] else header_plain worksheet.write(y, x, measure['measure'], style) x = x + 1 y = y + 1 # Step 3: writing data x = 0 for row in jdata['rows']: worksheet.write(y, x, row['indent'] * ' ' + row['title'], header_plain) for cell in row['values']: x = x + 1 if cell.get('is_bold', False): worksheet.write(y, x, cell['value'], bold) else: worksheet.write(y, x, cell['value']) x, y = 0, y + 1 response = request.make_response( None, headers=[('Content-Type', 'application/vnd.ms-excel'), ('Content-Disposition', 'attachment; filename=table.xls;') ], cookies={'fileToken': token}) workbook.save(response.stream) return response
def export_xls(self, data, token): jdata = json.loads(data) nbr_measures = jdata['nbr_measures'] workbook = xlwt.Workbook() worksheet = workbook.add_sheet(jdata['title'][:30]) header_bold = xlwt.easyxf("font: bold on; pattern: pattern solid, fore_colour gray25;") header_plain = xlwt.easyxf("pattern: pattern solid, fore_colour gray25;") bold = xlwt.easyxf("font: bold on;") # Step 1: writing headers headers = jdata['headers'] # x,y: current coordinates # carry: queue containing cell information when a cell has a >= 2 height # and the drawing code needs to add empty cells below x, y, carry = 1, 0, deque() for i, header_row in enumerate(headers): worksheet.write(i,0, '', header_plain) for header in header_row: while (carry and carry[0]['x'] == x): cell = carry.popleft() for i in range(nbr_measures): worksheet.write(y, x+i, '', header_plain) if cell['height'] > 1: carry.append({'x': x, 'height':cell['height'] - 1}) x = x + nbr_measures style = header_plain if 'expanded' in header else header_bold for i in range(header['width']): worksheet.write(y, x + i, header['title'] if i == 0 else '', style) if header['height'] > 1: carry.append({'x': x, 'height':header['height'] - 1}) x = x + header['width']; while (carry and carry[0]['x'] == x): cell = carry.popleft() for i in range(nbr_measures): worksheet.write(y, x+i, '', header_plain) if cell['height'] > 1: carry.append({'x': x, 'height':cell['height'] - 1}) x = x + nbr_measures x, y = 1, y + 1 # Step 2: measure row if nbr_measures > 1: worksheet.write(y,0, '', header_plain) for measure in jdata['measure_row']: style = header_bold if measure['is_bold'] else header_plain worksheet.write(y, x, measure['measure'], style); x = x + 1 y = y + 1 # Step 3: writing data x = 0 for row in jdata['rows']: worksheet.write(y, x, row['indent'] * ' ' + row['title'], header_plain) for cell in row['values']: x = x + 1 if cell.get('is_bold', False): worksheet.write(y, x, cell['value'], bold) else: worksheet.write(y, x, cell['value']) x, y = 0, y + 1 response = request.make_response(None, headers=[('Content-Type', 'application/vnd.ms-excel'), ('Content-Disposition', 'attachment; filename=table.xls;')], cookies={'fileToken': token}) workbook.save(response.stream) return response