Skip to content

Instantly share code, notes, and snippets.

@savonarola
Created March 19, 2009 11:00
Show Gist options
  • Save savonarola/81759 to your computer and use it in GitHub Desktop.
Save savonarola/81759 to your computer and use it in GitHub Desktop.
-module(contact_model).
-behaviour(model).
-export([init/1,handle/2]).
-include("contacts.hrl").
-define(CONTACTS_PERIOD, (1000000*60*60*24*30) ).
-define(DB_TIMOUT, 10000 ).
-record(state, {user_id}).
init(UserId) ->
{ok, #state{user_id=UserId}}.
handle(Self, get) ->
State = model:state(Self),
{ok, load_contacts(State#state.user_id)};
handle(Self, {get,ContactUser}) ->
State = model:state(Self),
Contact = case lists:filter( fun({_CG,CU}) -> CU =:= ContactUser end, load_contacts(State#state.user_id) ) of
[] -> undef;
[C|_] -> C
end,
{ok, Contact};
handle(Self, {add,ContactGroup, ContactUser}) ->
State = model:state(Self),
User = State#state.user_id,
ets_server:delete(contacts_cache,User),
db_client:write_request(contacts_db_client,User,add,{User,ContactGroup,ContactUser},?DB_TIMOUT),
ok;
handle(Self, {remove, ContactUser}) ->
State = model:state(Self),
User = State#state.user_id,
ets_server:delete(contacts_cache,User),
db_client:write_request(contacts_db_client,User,remove,{User,ContactUser},?DB_TIMOUT),
ok;
handle(Self, {is_in_contacts, ContactUser}) ->
State = model:state(Self),
Res = lists:any( fun(I) -> {_CG,CU} = I, CU =:= ContactUser end, load_contacts(State#state.user_id) ),
{ok, Res}.
load_contacts(User) ->
case ets_server:lookup_first(contacts_cache,User) of
undef ->
Res = db_client:read_request(contacts_db_client,User,?CONTACTS_PERIOD,get,User,?DB_TIMOUT),
Contacts = case Res of
{ok, undef} -> #contacts{user = User};
{ok, C} -> C;
_ -> #contacts{user = User}
end,
error_logger:info_msg( "contact_server:load_contacts Contacts=~p~n", [Contacts] ),
ets_server:insert(contacts_cache,{User, Contacts#contacts.contacts}),
Contacts#contacts.contacts;
CachedContacts -> CachedContacts
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment