35
36:- module(avatar,
37 [ email_gravatar/2, 38 valid_gravatar/1, 39 random_avatar/1, 40 release_avatar/1, 41
42 clean_avatar_cache/0
43 ]). 44:- use_module(library(uri)). 45:- use_module(library(md5)). 46:- use_module(library(lists)). 47:- use_module(library(random)). 48:- use_module(library(apply)). 49:- use_module(library(http/http_path)). 50:- use_module(library(http/http_open)). 51:- use_module(library(error)).
63email_gravatar(Email, AvatarURL) :-
64 downcase_atom(Email, CanonicalEmail),
65 md5_hash(CanonicalEmail, Hash, []),
66 atom_concat('/avatar/', Hash, Path),
67 uri_data(scheme, Components, https),
68 uri_data(authority, Components, 'www.gravatar.com'),
69 uri_data(path, Components, Path),
70 uri_components(AvatarURL, Components).
78:- dynamic
79 gravatar_tested/3. 80
81valid_gravatar(URL) :-
82 gravatar_tested(URL, Time, Result),
83 get_time(Now),
84 ( Now - Time < 300
85 -> !,
86 Result == true
87 ; retractall(gravatar_tested(URL,_,_))
88 ).
89valid_gravatar(URL) :-
90 string_concat(URL, "?d=404", URL2),
91 ( catch(http_open(URL2, In, [method(head)]),
92 error(_,_),
93 fail)
94 -> close(In),
95 Result = true
96 ; Result = false
97 ),
98 get_time(Now),
99 asserta(gravatar_tested(URL, Now, Result)),
100 Result == true.
111random_avatar(AvatarURL) :-
112 avatar_cache(_Size),
113 repeat,
114 findall(I, free_avatar(I), L),
115 ( L == []
116 -> resource_error(avatars)
117 ; random_member(A, L),
118 avatar(A, AvatarURL),
119 with_mutex(avatar, claim_avatar(A)),
120 !
121 ).
122
123free_avatar(I) :-
124 avatar(I, _),
125 \+ used_avatar(I).
126
127claim_avatar(I) :-
128 used_avatar(I), !, fail.
129claim_avatar(I) :-
130 assertz(used_avatar(I)).
136release_avatar(URL0) :-
137 atom_string(URL, URL0),
138 forall(avatar(I, URL),
139 retractall(used_avatar(I))).
140
141clean_avatar_cache :-
142 retractall(avatar_cache_size(_)),
143 retractall(avatar(_,_)).
144
145:- dynamic
146 used_avatar/1,
147 avatar_cache_size/1,
148 avatar/2. 149:- volatile
150 used_avatar/1,
151 avatar_cache_size/1,
152 avatar/2. 153
154avatar_cache(Size) :-
155 avatar_cache_size(Size), !.
156avatar_cache(Size) :-
157 findall(Path, avatar_path(Path), Paths),
158 foldl(assert_avatar, Paths, 0, Size0),
159 assertz(avatar_cache_size(Size0)),
160 Size = Size0.
161
162avatar_path(icons(avatar/File)) :-
163 absolute_file_name(icons(avatar), Dir,
164 [ file_type(directory),
165 solutions(all)
166 ]),
167 directory_files(Dir, Files),
168 member(File, Files),
169 file_name_extension(_, Ext, File),
170 downcase_atom(Ext, LwrExt),
171 image_extension(LwrExt).
172
173image_extension(png).
174image_extension(jpg).
175image_extension(jpeg).
176image_extension(gif).
177
178assert_avatar(Path, N, N2) :-
179 http_absolute_location(Path, HREF, []),
180 assertz(avatar(N, HREF)),
181 N2 is N+1
Avatar management
This module provides access to avatar handling. */