-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconverseDB.erl
More file actions
382 lines (332 loc) · 15.3 KB
/
converseDB.erl
File metadata and controls
382 lines (332 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
%%=====================================================
%% Abstract
%%
%% This is the module that abstracts away the DB layer
%% and make the information available from the ether
%%
%% TODO: Use Mnesia now to learn it, but next look to
%% use CouchDB... not sure if it adds any real
%% value, but intersting none the less to try.
%%======================================================
%%======================================================
%% Tag the file
%%======================================================
-module(converseDB).
-compile(export_all).
-author("Stephen Bailey").
-email("Stephen.Bailey@stackingit.com").
-vsn( "0.0.0.1" ).
%% get the query list comprehension tied in so we can use it
-include_lib("stdlib/include/qlc.hrl").
-include("DebugMacros.hrl").
%%=====================================================
%% Defines the DB data
%%
%% TODO : Find out how to put this in a hrl file and
%% referenced
%%======================================================
-record( tb_conversation, {
id, %% unique primary Key
author, %% UserID : The person that started this %% information about the mail object
subject, %% string : heading for the conversation
message, %% string : the content
talkers = [], %% [userID,userID,...] people still active in the convesation
listeners = [], %% [UserID,UserID,...] of listeners not active in the conversation
time %% when the message was created
} ).
%% Details about the user
-record( tb_user, {
name, %% primary key for the user, since the name must be unique
userId, %% the person's id so they can change their name if they want to
password %% umm duh the password
} ).
%% This will only keep the current information, to do history trauls, you need to hunt
%% down the conversations.. since this is a less likely use case
%%
%% This will be a bag table so that the primary key is user, but each
%% listening and following mail is unqiue.
-record( tb_userConversation, {
userId,
talker = [], %% an active conversation ID
listener = [] %% an listening conversation ID
} ).
%%=====================================================
%% this just returns a nice list of all of our tables
%% so if I need to do anything with all of htem like nuke
%% them for debug, I only have to update in one place
%%=====================================================
tables() ->
[ tb_user, tb_conversation, tb_userConversation ].
%%=====================================================
%% Create the DB for the First Time.. this should be
%% called only once
%%=====================================================
createDB() ->
mnesia:create_schema( [ node() ] ).
%%=====================================================
%% Start our DB
%% We are only using disk we we might not need to go fast, and we wil use up space
%% quite quickly being mail.. in time I can look at some cunning way to pull the current
%% conversation into memeory since they will be active and the old ones archived off, but for
%% now I just need to get stuff working :-)
%%=====================================================
startDB() ->
mnesia:start(),
%% Okay we are going to make this table a bag so that I can have
%% multiple "mails" per conversation
mnesia:create_table( tb_conversation, [ { attributes, record_info( fields, tb_conversation ) } ,
{ disc_only_copies, [ node() ] },
{ type, set } ] ),
%% now for the user table
%% we make this a set so that only userid is unique
mnesia:create_table( tb_user, [ { attributes, record_info( fields, tb_user ) } ,
{ disc_only_copies, [ node() ] },
{ type, set } ] ),
%% now for the userConversation table
%% we make this a bag so the userid is the key for all "actvie conversations"
mnesia:create_table( tb_userConversation, [ { attributes, record_info( fields, tb_userConversation ) } ,
{ disc_only_copies, [ node() ] },
{ type, set } ] ).
%%=====================================================
%% Add a new user
%%=====================================================
addUser( Name, Password ) ->
%% check if this user already exists
case validateUser( Name ) of
{ user, exists } ->
{ user, already_exists };
{ user, does_not_exist } ->
addUpdateUser(Name, Password );
ERROR ->
exit( { 'converseDB:addUser', ERROR} )
end.
%%=====================================================
%% This will either add a new user or update an existing
%% user
%%=====================================================
addUpdateUser( Name, Password ) ->
UserRecord = #tb_user{ name=Name, userId={now(),node()} , password=Password },
F = fun() ->
mnesia:write( UserRecord )
end,
case mnesia:transaction( F ) of
{atomic,ok} ->
{ user, ok };
Error ->
exit( {'converseDB:addUser'}, Error )
end.
%%=====================================================
%% Validate the user exits
%%=====================================================
validateUser( Name ) ->
%% Define the method to check for the user
F = fun() ->
qlc:e( qlc:q( [ X#tb_user.userId || X <- mnesia:table( tb_user ), X#tb_user.name =:= Name ] ) )
end,
%% do the lookup
case mnesia:transaction(F) of
{aborted, Reason } ->
%% What happen here ?? .. lets get out of here
exit( {'converseDB:validateUser', Reason } );
{atomic, Result } ->
case Result of
[] -> { user, does_not_exist };
_ -> { user, exists }
end
end.
%%=====================================================
%% Validate the user password
%%=====================================================
validatePassword( Name, Password ) ->
F = fun() ->
qlc:e( qlc:q( [ X#tb_user.password || X <- mnesia:table( tb_user ), X#tb_user.name =:= Name ] ) )
end,
case mnesia:transaction(F) of
{aborted, Reason } ->
%% What happen here ?? .. lets get out of here
exit( {'converseDB:validatePassword', Reason } );
{atomic, [Password] } ->
{authentication, pass};
{atomic, _ } ->
{authentication, fail}
end.
%%=====================================================
%% Save a new Conversation
%%=====================================================
addConversation( Author, Password, Subject, Message, Talkers ) ->
%%Validate the password - unless you are the correct person
%%you dont get to impersonate them !!
case validatePassword( Author, Password ) of
{authentication, pass } ->
%%Get our authors ID
AuthorId = getUserId( Author ),
%% Get the userid for these people in the mail
TalkerUserIds = lists:map( fun(X)-> getUserId( X ) end, Talkers ),
%%Define a unique conversationID
ConversationId = {now(),node()},
%%add the author as a talker
AllTalkerIDs = [ AuthorId | TalkerUserIds ],
%% Make a new unique conversation record
Conversation = #tb_conversation{ id=ConversationId,
author=AuthorId ,
subject=Subject,
message=Message,
talkers=AllTalkerIDs,
time=now() },
%% Now we need to create records for each of our people
%% involved in this conversation...
%% Make the act of saving it a method
F = fun() ->
%% add the conversation
mnesia:write( Conversation ),
%% update each of the users with the new conversations
%% that they are now involved in
[ mapUserAsTalker( UserId, ConversationId ) || UserId <- AllTalkerIDs ]
end,
%% Perform the save in a transaction
case mnesia:transaction(F) of
{ atomic, _ } ->
{ conversation, ok, ConversationId };
ERROR ->
exit( { 'converseDB:addConversation', ERROR } )
end;
{AuthFail} -> AuthFail
end.
%%=====================================================
%% This will add a conversation ID to a particular user
%% it is assumed that this will be run in the context of
%% of a transaction
%% hmm there must be a better way instead of having a
%% comment which says when this should be run ??
%%=====================================================
mapUserAsTalker( UserId, ConversationId ) ->
case mnesia:read( tb_userConversation, UserId ) of
[] ->
%%just add a new record
NewUserConversation = #tb_userConversation{ userId=UserId, talker=[ConversationId] },
mnesia:write( NewUserConversation );
[ActiveConversations] ->
Talking = ActiveConversations#tb_userConversation.talker,
%%now save it back
UpdatedConversations = ActiveConversations#tb_userConversation{talker=[ConversationId | Talking ] },
mnesia:write( UpdatedConversations );
Error ->
exit( {'converseDB:mapUserAsTalker',Error} )
end.
%%=====================================================
%% This will opt a user out of an existing conversation
%% this is password protected
%%=====================================================
optOut( UserName, Password, ConversationId ) ->
case validatePassword( UserName, Password ) of
{authentication, pass } ->
F = fun() ->
[ {tb_userConversation, UserId, Talker, Listener} ] = mnesia:read( tb_userConversation, getUserId( UserName ) ),
NewTalkerList = lists:delete( ConversationId, Talker ),
case ( NewTalkerList =:= Talker ) of
true ->
%%check if this was even in the list if not abort
mnesia:abort( { opt_out, error, not_in_conversation } );
false ->
%%save it back
UpdatedRow = #tb_userConversation{userId=UserId,talker=NewTalkerList,listener=Listener},
mnesia:write( UpdatedRow )
end
end,
case mnesia:transaction( F ) of
{aborted, { opt_out, error, not_in_conversation } } ->
{ opt_out, error, not_in_conversation };
{atomic, _ } ->
{ opt_out, ok };
Error ->
exit( {'converseDB:optOut',Error} )
end;
{AuthFail} -> AuthFail
end.
%%=====================================================
%% This will return the Id of a single user
%%=====================================================
getUserId( UserName ) ->
F = fun() ->
qlc:e( qlc:q( [ X#tb_user.userId || X <- mnesia:table( tb_user ), X#tb_user.name =:= UserName ] ) )
end,
case mnesia:transaction( F ) of
{ atomic, [Id] }
-> Id;
Error ->
exit( {"converseDB:getUserId", Error } )
end.
%%=====================================================
%% Given a userId lets get the user name
%%=====================================================
getUserName( UserId ) ->
F = fun() ->
qlc:e( qlc:q( [ X#tb_user.name || X <- mnesia:table( tb_user ), X#tb_user.userId =:= UserId ] ) )
end,
case mnesia:transaction( F ) of
{ atomic, [Name] }
-> Name;
Error ->
exit( {"converseDB:getUserName", Error } )
end.
%%=====================================================
%% Get any new or active conversations for the user by returning
%% only the ID, subject and author
%%=====================================================
getActiveConversations( User, Password ) ->
%%Validate the password
case validatePassword( User, Password ) of
{authentication, pass } ->
% look through the DB to find any conversations that
% this user is still involved in and return them all),
F = fun() ->
qlc:e( qlc:q( [ { {talking, X#tb_userConversation.talker},
{listening, X#tb_userConversation.listener} }
|| X <- mnesia:table( tb_userConversation ),
X#tb_userConversation.userId =:= getUserId( User ) ] ) )
end,
{atomic, [ActiveConversations] } = mnesia:transaction( F ),
ActiveConversations;
{AuthFail} -> AuthFail
end.
%%=====================================================
%% This will return a complete conversation
%%=====================================================
getConversation( ConversationId )->
F = fun()->
mnesia:read( tb_conversation, ConversationId )
end,
case mnesia:transaction(F) of
%%get the conversation without the table name
{atomic, [ { tb_conversation, ConversationId, Author, Subject, Message, Talkers, Listeners, Time } ] } ->
%% return a nicely name tuple with all the conversation information
MakeIntoName = fun(X) -> getUserName( X ) end,
{ {id,ConversationId},
{author,getUserName(Author)}, {subject,Subject}, {message,Message},
{talkers, lists:map(MakeIntoName,Talkers) },
{listeners, lists:map(MakeIntoName,Listeners) },
{time,Time}
};
Error ->
exit( { 'converseDB:getConversation', Error } )
end.
%%=====================================================
%% Set up a debugging environment
%%=====================================================
debugStart() ->
%% get a tracer up for just calls
tracer:trace([?MODULE],[c]),
%% sort out the Mnesia DB
mnesia:stop(), % make sure there is not one running already
mnesia:delete_schema( node() ),
createDB(), % create a DB for this node
startDB(), % create the structure
%%create some users
addUser( "Stephen", "test"),
addUser( "Bob", "test"),
addUser( "Sue", "test"),
%%put in test data for the DB
addConversation( "Stephen", "test", "Subject", "Some interseting Message", [ "Sue" , "Bob" ] ),
addConversation( "Stephen", "test", "test", "Testing", [ "Sue" ] ),
%% get a viewing tool up to look at the DB data
tv:start().