oauth.erl 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. -module(oauth).
  2. -export([get/2, get/3, get/4]).
  3. -export([post/2, post/3, post/4]).
  4. -export([tokens/1]).
  5. -export([token/1]).
  6. -export([token_secret/1]).
  7. -export([params_from_string/1]).
  8. get(URL, Consumer) ->
  9. fetch({get, URL, []}, Consumer).
  10. get(URL, Consumer, {oauth_tokens, Tokens}) ->
  11. fetch({get, URL, []}, Consumer, Tokens);
  12. get(URL, Consumer, Params) ->
  13. fetch({get, URL, Params}, Consumer, []).
  14. get(URL, Consumer, {oauth_tokens, Tokens}, Params) ->
  15. fetch({get, URL, Params}, Consumer, Tokens).
  16. post(URL, Consumer) ->
  17. fetch({post, URL, []}, Consumer).
  18. post(URL, Consumer, {oauth_tokens, Tokens}) ->
  19. fetch({post, URL, []}, Consumer, Tokens);
  20. post(URL, Consumer, Params) ->
  21. fetch({post, URL, Params}, Consumer, []).
  22. post(URL, Consumer, {oauth_tokens, Tokens}, Params) ->
  23. fetch({post, URL, Params}, Consumer, Tokens).
  24. tokens({ok, {_,_,Data}}) ->
  25. {ok, {oauth_tokens, params_from_string(Data)}};
  26. tokens(Term) ->
  27. Term.
  28. token({oauth_tokens, Tokens}) ->
  29. proplists:get_value(oauth_token, Tokens).
  30. token_secret({oauth_tokens, Tokens}) ->
  31. proplists:get_value(oauth_token_secret, Tokens).
  32. fetch({Method, URL, Params}, Consumer) ->
  33. fetch({Method, URL, Params}, Consumer, []).
  34. fetch({Method, URL, Params}, Consumer, Tokens) ->
  35. SignedURL = oauth_request:url(Method, URL, Params, Consumer, Tokens),
  36. http:request(Method, {SignedURL, _Headers=[]}, [], []).
  37. params_from_string(Data) ->
  38. lists:map(fun param_from_string/1, explode($&, Data)).
  39. param_from_string(Data) when is_list(Data) ->
  40. param_from_string(break_at($=, Data));
  41. param_from_string({K, V}) ->
  42. {list_to_atom(oauth_util:percent_decode(K)), oauth_util:percent_decode(V)}.
  43. explode(_Sep, []) ->
  44. [];
  45. explode(Sep, Chars) ->
  46. explode(Sep, break_at(Sep, Chars), []).
  47. explode(_Sep, {Param, []}, Params) ->
  48. lists:reverse([Param|Params]);
  49. explode(Sep, {Param, Etc}, Params) ->
  50. explode(Sep, break_at(Sep, Etc), [Param|Params]).
  51. break_at(Sep, Chars) ->
  52. case lists:splitwith(fun(C) -> C =/= Sep end, Chars) of
  53. Result={_, []} ->
  54. Result;
  55. {Before, [Sep|After]} ->
  56. {Before, After}
  57. end.