mod_http_avatar/mod_http_avatar.lua
changeset 3088 5b4e7db5943c
parent 3087 46d71b38bc16
child 5724 0f103a6e9ba4
equal deleted inserted replaced
3087:46d71b38bc16 3088:5b4e7db5943c
     3 --
     3 --
     4 -- This project is MIT/X11 licensed. Please see the
     4 -- This project is MIT/X11 licensed. Please see the
     5 -- COPYING file in the source package for more information.
     5 -- COPYING file in the source package for more information.
     6 
     6 
     7 local base64 = require"util.encodings".base64;
     7 local base64 = require"util.encodings".base64;
       
     8 local sha1 = require"util.hashes".sha1;
     8 local st = require"util.stanza";
     9 local st = require"util.stanza";
     9 module:depends"http";
    10 module:depends"http";
    10 
    11 
    11 local vcard_storage = module:open_store"vcard";
    12 local vcard_storage = module:open_store"vcard";
    12 
    13 
    14 <rect width='150' height='150' fill='#888' stroke-width='1' stroke='#000'/>
    15 <rect width='150' height='150' fill='#888' stroke-width='1' stroke='#000'/>
    15 <text x='75' y='100' text-anchor='middle' font-size='100'>?</text>
    16 <text x='75' y='100' text-anchor='middle' font-size='100'>?</text>
    16 </svg>]];
    17 </svg>]];
    17 
    18 
    18 local function get_avatar(event, path)
    19 local function get_avatar(event, path)
    19 	local response = event.response;
    20 	local request, response = event.request, event.response;
    20 	local photo_type, binval;
    21 	local photo_type, binval;
    21 	local vcard, err = vcard_storage:get(path);
    22 	local vcard, err = vcard_storage:get(path);
    22 	if vcard then
    23 	if vcard then
    23 		vcard = st.deserialize(vcard);
    24 		vcard = st.deserialize(vcard);
    24 		local photo = vcard:get_child("PHOTO", "vcard-temp");
    25 		local photo = vcard:get_child("PHOTO", "vcard-temp");
    30 	if not photo_type or not binval then
    31 	if not photo_type or not binval then
    31 		response.status_code = 404;
    32 		response.status_code = 404;
    32 		response.headers.content_type = "image/svg+xml";
    33 		response.headers.content_type = "image/svg+xml";
    33 		return default_avatar;
    34 		return default_avatar;
    34 	end
    35 	end
       
    36 	local avatar = base64.decode(binval);
       
    37 	local hash = sha1(avatar, true);
       
    38 	if request.headers.if_none_match == hash then
       
    39 		return 304;
       
    40 	end
    35 	response.headers.content_type = photo_type;
    41 	response.headers.content_type = photo_type;
    36 	return base64.decode(binval);
    42 	response.headers.etag = hash;
       
    43 	return avatar;
    37 end
    44 end
    38 
    45 
    39 module:provides("http", {
    46 module:provides("http", {
    40 	route = {
    47 	route = {
    41 		["GET /*"] = get_avatar;
    48 		["GET /*"] = get_avatar;