Skip to content

Instantly share code, notes, and snippets.

@savonarola
Created March 16, 2009 12:46
Show Gist options
  • Save savonarola/79863 to your computer and use it in GitHub Desktop.
Save savonarola/79863 to your computer and use it in GitHub Desktop.
-module(contacts_model).
-behaviour(model).
-export([parent_models/0,new/1,handle/3]).
-include("contacts.hrl").
-define(CONTACTS_PERIOD, (1000000*60*60*24*30) ).
-define(DB_TIMOUT, 10000 ).
-record(state, {user_id,contacts}).
parent_models() -> [].
new(UserId) ->
{ok, #state{user_id=UserId, contacts=undef} }.
handle(Request, State, _Parents) ->
case Request of
get ->
%model:super(Parents, Request),
%model:super(Parents, SuperModel, Request),
NewState = load_contacts(State),
{reply, NewState#state.contacts, State};
{get,ContactUser} ->
NewState = load_contacts(State),
Contact = case lists:filter( fun({_CG,CU}) -> CU =:= ContactUser end, NewState#state.contacts ) of
[] -> undef;
[C|_] -> C
end,
{reply, Contact, NewState};
{add,ContactGroup, ContactUser} ->
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),
{reply, ok, State#state{contacts=undef}};
{remove, ContactUser} ->
User = State#state.user_id,
ets_server:delete(contacts_cache,User),
db_client:write_request(contacts_db_client,User,remove,{User,ContactUser},?DB_TIMOUT).
{reply, ok, State#state{contacts=undef}};
{is_in_contacts, ContactUser} ->
NewState = load_contacts(State),
Res = lists:any( fun(I) -> {_CG,CU} = I, CU =:= ContactUser end, NewState#state.contacts ).
{reply, Res, NewState};
_ -> {no_method, State}
end.
load_contacts(State) ->
case State#state.contacts of
undef ->
User = State#sta.user_id,
LoadedContacts = 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,
State#state{contacts=Contacts};
_ -> State
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment