API:Исследователь:Example5

Материал из КардиоКВАРК
Перейти к: навигация, поиск
#!/usr/bin/env escript
%%! -smp auto -sname test

-define(TIMEOUT, 10000).

main(_) ->
	ok = application:start(inets, permanent),
	ok = application:start(crypto, permanent),
	ok = application:start(asn1, permanent),
	ok = application:start(public_key, permanent),
	ok = application:start(ssl, permanent),
	ok = application:start(jiffy, permanent),
	inets:start(httpc, [{profile, nobody}]),
	inets:start(httpc, [{profile, researcher}]),

	%% login
	Account = jiffy:encode(#{
		<<"id">> => 9999,
		<<"password">> => <<"XXXX">>,
		<<"role">> => 3
	}),
	NobodyOpts = [
		{timeout, ?TIMEOUT},
		{connect_timeout, ?TIMEOUT},
		{ssl, [
			{cacertfile, "cardio-beta-ca-crt.pem"},
			{verify, verify_peer}
		]}
	],
	{ok, {{_, 200, _}, _, Body1}} = httpc:request(
		post,
		{"https://b-api.cardioqvark.ru:1443/account", [], "application/json; charset=utf-8", Account},
		NobodyOpts,
		[{sync, true}, {body_format, binary}],
		nobody
	),
	#{<<"certificate">> := CertData, <<"key">> := KeyData} = jiffy:decode(Body1, [return_maps]),
	Cert = base64:decode(CertData),
	Key = base64:decode(KeyData),
	ResearcherOpts = [
		{timeout, ?TIMEOUT},
		{connect_timeout, ?TIMEOUT},
		{ssl, [
			{cacertfile, "cardio-beta-ca-crt.pem"},
			{cert, Cert},
			{key, {'RSAPrivateKey', Key}},
			{verify, verify_peer}
		]}
	],

	%% read cardiograms
	{ok, {{_, 200, _}, _, Body2}} = httpc:request(
		get,
		{"https://b-api.cardioqvark.ru:1443/cardiogram?desc=1&sampleRate=1000", [{"Range", "items=0-9"}]},
		ResearcherOpts,
		[{sync, true}, {body_format, binary}],
		researcher
	),
	lists:foreach(fun(#{<<"id">> := Id}) ->
		IdStr = integer_to_list(Id),
		{ok, {{_, 200, _}, _, Body3}} = httpc:request(
			get,
			{"https://b-api.cardioqvark.ru:1443/token?type=1&id=" ++ integer_to_list(Id), []},
			ResearcherOpts,
			[{sync, true}, {body_format, binary}],
			researcher
		),
		#{<<"token">> := Token} = jiffy:decode(Body3, [return_maps]),
		{ok, {{_, 200, _}, _, Body4}} = httpc:request(
			get,
			{lists:append(["https://b-g1.cardioqvark.ru/cardiogram/", IdStr, "?type=1"]), [
				{"Authorization", "Token " ++ binary_to_list(Token)}
			]},
			NobodyOpts,
			[{sync, true}, {body_format, binary}],
			nobody
		),
		file:write_file(IdStr ++ "-1k.wav", Body4),
		io:format("~p ok (~p bytes)~n", [Id, size(Body4)])
	end, jiffy:decode(Body2, [return_maps])).