/src/client.erl

https://github.com/jwilberding/beeer.me · Erlang · 75 lines · 58 code · 8 blank · 9 comment · 1 complexity · 2a3e1281e4eb02063eb474a4324ea26f MD5 · raw file

  1. -module(client).
  2. -export([init/0, watch_dir/1, unwatch_dir/1, check_updates/0, request_hash_list/1, send_file/1]).
  3. -include("config.hrl").
  4. %% Init loop that checks watched directory an checks for updates on server
  5. init() ->
  6. io:format("Client started~n").
  7. %% Add directory to watched list
  8. watch_dir(Dir) ->
  9. io:format("Watching: ~s~n", [Dir]).
  10. %% Remove directory to watched list
  11. unwatch_dir(Dir) ->
  12. io:format("UnWatching: ~s~n", [Dir]).
  13. %% Check for updated files on server
  14. check_updates() ->
  15. io:format("Checking for updated files on server~n").
  16. %% Request hash list of file from server, empty list means file does not exist yet
  17. %% TODO: Request via hash of file, not by filename
  18. request_hash_list(Filename) ->
  19. case gen_tcp:connect(?HOST, ?SERVER_PORT, [binary,{packet, 2}]) of
  20. {ok, Socket} ->
  21. io:format("Socket=~p~n",[Socket]),
  22. io:format("Sending: ~p~n", [term_to_binary({?REQ_HASH_LIST, Filename})]),
  23. gen_tcp:send(Socket, term_to_binary({?REQ_HASH_LIST, Filename})),
  24. Reply = binary_to_term(wait_reply()),
  25. case Reply of
  26. {error, nofile} ->
  27. HashList = "File does not exist remotely";
  28. HashList ->
  29. HashList
  30. end,
  31. gen_tcp:close(Socket),
  32. HashList;
  33. Error ->
  34. {error, Error}
  35. end.
  36. %% Sends a new file, we will do this when file does not exist on server
  37. %% TODO: Filename on server should be filename+hash to keep unique
  38. %% TODO: Make return friendly to front end, currently friendly to command line
  39. send_file(Filename) ->
  40. case gen_tcp:connect(?HOST, ?SERVER_PORT, [binary,{packet, 2}]) of
  41. {ok, Socket} ->
  42. io:format("Reading file~n"),
  43. Data = utils:read_file(Filename),
  44. io:format("Converting to term~n"),
  45. TermData = term_to_binary({?NEW_FILE, Filename, Data}),
  46. io:format("Sending data: ~p~n", [size(TermData)]),
  47. ok = gen_tcp:send(Socket, TermData),
  48. io:format("Sent~n"),
  49. gen_tcp:close(Socket),
  50. Reply = binary_to_term(wait_reply()),
  51. case Reply of
  52. {error, Reason} ->
  53. Reason;
  54. ok ->
  55. ok
  56. end;
  57. Error ->
  58. {error, Error}
  59. end.
  60. wait_reply() ->
  61. receive
  62. Reply ->
  63. {tcp, _Port, Data} = Reply,
  64. Data
  65. after 100000 ->
  66. timeout
  67. end.