From 4dd83294848ee879894560c636b0c65b80346091 Mon Sep 17 00:00:00 2001 From: Tobias Reisinger <tobias@msrg.cc> Date: Sat, 29 Aug 2020 09:10:50 +0200 Subject: [PATCH 1/9] add: more tests --- CMakeLists.txt | 46 +++++++------ .../tavern_tests/0.1.test_basics.tavern.yaml | 16 +++++ .../1.1.controller_relays_basic.tavern.yaml | 68 ++++++++++++++++++- tests/tavern_tests/3.0.tags.tavern.yaml | 51 ++++++++++++++ tests/tavern_utils/validate_tag.py | 27 ++------ 5 files changed, 166 insertions(+), 42 deletions(-) create mode 100644 tests/tavern_tests/0.1.test_basics.tavern.yaml diff --git a/CMakeLists.txt b/CMakeLists.txt index a763453..5f6f722 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -43,21 +43,8 @@ add_custom_target(run DEPENDS core WORKING_DIRECTORY ${CMAKE_BINARY_DIR} ) -add_custom_target(debug - COMMAND valgrind -s ./core start - DEPENDS core - WORKING_DIRECTORY ${CMAKE_BINARY_DIR} -) -add_custom_target(debug-leak - COMMAND valgrind --leak-check=full --show-leak-kinds=all ./core start - DEPENDS core - WORKING_DIRECTORY ${CMAKE_BINARY_DIR} -) -add_custom_target(debug-callgrind - COMMAND valgrind --tool=callgrind ./core start - DEPENDS core - WORKING_DIRECTORY ${CMAKE_BINARY_DIR} -) + + add_custom_target(docs COMMAND doxygen WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} @@ -73,8 +60,27 @@ add_custom_target(test-callgrind DEPENDS core WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/tests ) -add_custom_target(coverage - COMMAND gcovr -s --root ${CMAKE_SOURCE_DIR} -e ${CMAKE_SOURCE_DIR}/vendor --html-details ${CMAKE_BINARY_DIR}/coverage.html --html-title "Emgauwa Core Coverage" ${CMAKE_BINARY_DIR}/CMakeFiles/core.dir - DEPENDS test - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} -) + +IF(CMAKE_BUILD_TYPE MATCHES DEBUG) + message("debug mode") + add_custom_target(debug + COMMAND valgrind -s ./core start + DEPENDS core + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + ) + add_custom_target(debug-leak + COMMAND valgrind --leak-check=full --show-leak-kinds=all ./core start + DEPENDS core + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + ) + add_custom_target(debug-callgrind + COMMAND valgrind --tool=callgrind ./core start + DEPENDS core + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + ) + add_custom_target(coverage + COMMAND gcovr -s --root ${CMAKE_SOURCE_DIR} -e ${CMAKE_SOURCE_DIR}/vendor --html-details ${CMAKE_BINARY_DIR}/coverage.html --html-title "Emgauwa Core Coverage" ${CMAKE_BINARY_DIR}/CMakeFiles/core.dir + DEPENDS test + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + ) +ENDIF(CMAKE_BUILD_TYPE MATCHES DEBUG) diff --git a/tests/tavern_tests/0.1.test_basics.tavern.yaml b/tests/tavern_tests/0.1.test_basics.tavern.yaml new file mode 100644 index 0000000..14ac8b5 --- /dev/null +++ b/tests/tavern_tests/0.1.test_basics.tavern.yaml @@ -0,0 +1,16 @@ +test_name: "[test_basics] Test basic calls" + +stages: +- name: "[test_basics] get index" + request: + url: "http://localhost:5000/" + method: GET + response: + status_code: 200 + +- name: "[test_basics] get 404" + request: + url: "http://localhost:5000/invalid_url_for_testing_do_not_use" + method: GET + response: + status_code: 404 diff --git a/tests/tavern_tests/1.1.controller_relays_basic.tavern.yaml b/tests/tavern_tests/1.1.controller_relays_basic.tavern.yaml index f0d1750..285d2d5 100644 --- a/tests/tavern_tests/1.1.controller_relays_basic.tavern.yaml +++ b/tests/tavern_tests/1.1.controller_relays_basic.tavern.yaml @@ -26,7 +26,7 @@ stages: extra_kwargs: relay_count: !int "{returned_relay_count:d}" -- name: "[controller_relays_basic] get controller relays, check length" +- name: "[controller_relays_basic] get controller relay" request: method: GET url: "http://localhost:5000/api/v1/controllers/{returned_id}/relays/5" @@ -40,3 +40,69 @@ stages: function: validate_relay:check_number extra_kwargs: number: 5 + +- name: "[controller_relays_basic] get controller relay with invalid uid" + request: + method: GET + url: "http://localhost:5000/api/v1/controllers/INVALID-UUID/relays/5" + response: + status_code: 400 + +- name: "[controller_relays_basic] get controller relay with unavailable uid" + request: + method: GET + url: "http://localhost:5000/api/v1/controllers/00000000-0000-0000-0000-000000000000/relays/5" + response: + status_code: 404 + +- name: "[controller_relays_basic] get controller relay with invalid number" + request: + method: GET + url: "http://localhost:5000/api/v1/controllers/{returned_id}/relays/not_a_number" + response: + status_code: 404 + +- name: "[controller_relays_basic] get controller relay with unavailable number" + request: + method: GET + url: "http://localhost:5000/api/v1/controllers/{returned_id}/relays/9001" + response: + status_code: 404 + + + + +- name: "[controller_relays_basic] pulse relay" + request: + method: POST + url: "http://localhost:5000/api/v1/controllers/{returned_id}/relays/6/pulse" + response: + status_code: 200 + +- name: "[controller_relays_basic] pulse relay with invalid uid" + request: + method: POST + url: "http://localhost:5000/api/v1/controllers/INVALID-UUID/relays/6/pulse" + response: + status_code: 400 + +- name: "[controller_relays_basic] pulse relay with unavailable uid" + request: + method: POST + url: "http://localhost:5000/api/v1/controllers/00000000-0000-0000-0000-000000000000/relays/6/pulse" + response: + status_code: 404 + +- name: "[controller_relays_basic] pulse relay with invalid number" + request: + method: POST + url: "http://localhost:5000/api/v1/controllers/{returned_id}/relays/not_a_number/pulse" + response: + status_code: 404 + +- name: "[controller_relays_basic] pulse relay with unavailable number" + request: + method: POST + url: "http://localhost:5000/api/v1/controllers/{returned_id}/relays/9001/pulse" + response: + status_code: 404 diff --git a/tests/tavern_tests/3.0.tags.tavern.yaml b/tests/tavern_tests/3.0.tags.tavern.yaml index d4ef67f..37734f8 100644 --- a/tests/tavern_tests/3.0.tags.tavern.yaml +++ b/tests/tavern_tests/3.0.tags.tavern.yaml @@ -98,6 +98,13 @@ stages: controller_id: "{returned_id}" tag: "{returned_tag}" +- name: "[tags] get returned tag with relays and schedules" + request: + method: GET + url: "http://localhost:5000/api/v1/tags/{returned_tag}" + response: + status_code: 200 + - name: "[tags] get tags" request: method: GET @@ -106,3 +113,47 @@ stages: status_code: 200 verify_response_with: function: validate_tag:multiple + +- name: "[tags] get unavailable tag" + request: + method: GET + url: "http://localhost:5000/api/v1/tags/invalid_unavailable_tag" + response: + status_code: 404 + +- name: "[tags] post tag" + request: + method: POST + url: "http://localhost:5000/api/v1/tags/" + json: + tag: "unused_tag_1" + response: + status_code: 201 + +- name: "[tags] get posted tag" + request: + method: GET + url: "http://localhost:5000/api/v1/tags/unused_tag_1" + response: + status_code: 200 + +- name: "[tags] delete posted tag" + request: + method: DELETE + url: "http://localhost:5000/api/v1/tags/unused_tag_1" + response: + status_code: 200 + +- name: "[tags] get deleted tag" + request: + method: GET + url: "http://localhost:5000/api/v1/tags/unused_tag_1" + response: + status_code: 404 + +- name: "[tags] delete deleted tag again" + request: + method: DELETE + url: "http://localhost:5000/api/v1/tags/unused_tag_1" + response: + status_code: 404 diff --git a/tests/tavern_utils/validate_tag.py b/tests/tavern_utils/validate_tag.py index 1e907e5..6a3004a 100644 --- a/tests/tavern_utils/validate_tag.py +++ b/tests/tavern_utils/validate_tag.py @@ -11,24 +11,9 @@ def multiple(response): for tag in response.json(): _verify_single(tag) -#def find(response, name=None, number=None, controller_id=None, tag=None): -# print(response.json()) -# for tag in response.json(): -# if number != None and number != tag.get("number"): -# continue -# -# if name != None and name != tag.get("name"): -# continue -# -# if controller_id != None and controller_id != tag.get("controller_id"): -# continue -# -# if tag != None: -# found_in_response = False -# for response_tag in tag.get("tags"): -# if response_tag == tag: -# found_in_response = True -# if not found_in_response: -# continue -# return -# assert False, "tag not found in list" +def find(response, tag): + print(response.json()) + for response_tag in response.json(): + if response_tag == tag: + return + assert False, "tag not found in list" From 7275d66c865a672ed54875ef2be8bad56556fca3 Mon Sep 17 00:00:00 2001 From: Tobias Reisinger <tobias@msrg.cc> Date: Sat, 29 Aug 2020 09:52:49 +0200 Subject: [PATCH 2/9] fix: tests had a dependency on emgauwa-webapp --- tests/core.testing.ini | 2 +- tests/run_tests.sh | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/core.testing.ini b/tests/core.testing.ini index c3710a1..811a43b 100644 --- a/tests/core.testing.ini +++ b/tests/core.testing.ini @@ -1,7 +1,7 @@ [core] server-port = 5000 database = core.sqlite -content-dir = /usr/share/webapps/emgauwa +content-dir = . not-found-file = 404.html not-found-file-mime = text/html not-found-content = 404 - NOT FOUND diff --git a/tests/run_tests.sh b/tests/run_tests.sh index cbfbdb1..ec36b70 100755 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -40,6 +40,8 @@ controller_id=$! cd $working_dir +touch $working_dir/index.html + cp $1 $working_dir/core cp $source_dir/core.testing.ini $working_dir/core.ini From f67b7e9e0fe0a0a0c3a14622fe2f4aae25e85786 Mon Sep 17 00:00:00 2001 From: Tobias Reisinger <tobias@msrg.cc> Date: Sat, 29 Aug 2020 22:58:02 +0200 Subject: [PATCH 3/9] add: basic macro functions add: better migration handling (transactions) --- CMakeLists.txt | 26 +++++++++--------- include/models/junction_macro.h | 7 +++++ sql/cache.sql | 2 ++ sql/migration_0.sql | 14 +++++----- sql/migration_1.sql | 28 +++++++++++++++++++ src/database.c | 48 +++++++++++++++++++++------------ src/models/junction_macro.c | 33 +++++++++++++++++++++++ 7 files changed, 122 insertions(+), 36 deletions(-) create mode 100644 include/models/junction_macro.h create mode 100644 sql/migration_1.sql create mode 100644 src/models/junction_macro.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 5f6f722..532a906 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -44,24 +44,18 @@ add_custom_target(run WORKING_DIRECTORY ${CMAKE_BINARY_DIR} ) +add_custom_target(test + COMMAND ./run_tests.sh ${CMAKE_BINARY_DIR}/core "--leak-check=full --show-leak-kinds=all --track-origins=yes" + DEPENDS core + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/tests +) add_custom_target(docs COMMAND doxygen WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} ) -add_custom_target(test - COMMAND ./run_tests.sh ${CMAKE_BINARY_DIR}/core "--leak-check=full --show-leak-kinds=all --track-origins=yes" - DEPENDS core - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/tests -) -add_custom_target(test-callgrind - COMMAND ./run_tests.sh ${CMAKE_BINARY_DIR}/core "--tool=callgrind" - DEPENDS core - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/tests -) - -IF(CMAKE_BUILD_TYPE MATCHES DEBUG) +IF(CMAKE_BUILD_TYPE MATCHES Debug) message("debug mode") add_custom_target(debug COMMAND valgrind -s ./core start @@ -83,4 +77,10 @@ IF(CMAKE_BUILD_TYPE MATCHES DEBUG) DEPENDS test WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} ) -ENDIF(CMAKE_BUILD_TYPE MATCHES DEBUG) + + add_custom_target(test-callgrind + COMMAND ./run_tests.sh ${CMAKE_BINARY_DIR}/core "--tool=callgrind" + DEPENDS core + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/tests + ) +ENDIF(CMAKE_BUILD_TYPE MATCHES Debug) diff --git a/include/models/junction_macro.h b/include/models/junction_macro.h new file mode 100644 index 0000000..6998c50 --- /dev/null +++ b/include/models/junction_macro.h @@ -0,0 +1,7 @@ +#ifndef CORE_JUNCTION_MACRO_H +#define CORE_JUNCTION_MACRO_H + +int +junction_macro_insert(int macro_id, int relay_id, int schedule_id, uint8_t weekday); + +#endif /* CORE_JUNCTION_MACRO_H */ diff --git a/sql/cache.sql b/sql/cache.sql index 5ca7471..3e4ce21 100644 --- a/sql/cache.sql +++ b/sql/cache.sql @@ -1,3 +1,5 @@ +-- a key-value table used for the json-cache + CREATE TABLE cache ( key STRING PRIMARY KEY, diff --git a/sql/migration_0.sql b/sql/migration_0.sql index 12dda72..939b907 100644 --- a/sql/migration_0.sql +++ b/sql/migration_0.sql @@ -1,4 +1,6 @@ -create table controllers +-- base migration + +CREATE TABLE controllers ( id INTEGER PRIMARY KEY @@ -14,7 +16,7 @@ create table controllers NOT NULL ); -create table relays +CREATE TABLE relays ( id INTEGER PRIMARY KEY @@ -28,7 +30,7 @@ create table relays ON DELETE CASCADE ); -create table schedules +CREATE TABLE schedules ( id INTEGER PRIMARY KEY @@ -40,7 +42,7 @@ create table schedules periods BLOB ); -create table tags +CREATE TABLE tags ( id INTEGER PRIMARY KEY @@ -50,7 +52,7 @@ create table tags UNIQUE ); -create table junction_tag +CREATE TABLE junction_tag ( tag_id INTEGER NOT NULL @@ -64,7 +66,7 @@ create table junction_tag ON DELETE CASCADE ); -create table junction_relay_schedule +CREATE TABLE junction_relay_schedule ( weekday SMALLINT NOT NULL, diff --git a/sql/migration_1.sql b/sql/migration_1.sql new file mode 100644 index 0000000..da01bf0 --- /dev/null +++ b/sql/migration_1.sql @@ -0,0 +1,28 @@ +-- migration to add macros + +CREATE TABLE macros +( + id INTEGER + PRIMARY KEY + AUTOINCREMENT, + uid BLOB + NOT NULL + UNIQUE, + name VARCHAR(128) +); + +CREATE TABLE junction_macro +( + macro_id INTEGER + NOT NULL + REFERENCES macros (id) + ON DELETE CASCADE, + relay_id INTEGER + REFERENCES relays (id) + ON DELETE CASCADE, + schedule_id INTEGER + REFERENCES schedules (id) + ON DELETE CASCADE, + weekday SMALLINT + NOT NULL +); diff --git a/src/database.c b/src/database.c index 02fd75a..a0f5aeb 100644 --- a/src/database.c +++ b/src/database.c @@ -5,6 +5,7 @@ #include <database.h> #include <sql/migration_0.h> +#include <sql/migration_1.h> sqlite3 *global_database; static int in_transaction; @@ -32,11 +33,35 @@ database_free() sqlite3_close(global_database); } +static void +database_migrate_step_simple(int level, const char* sql_migration) +{ + LOGGER_INFO("migrating LEVEL %d\n", level); + char* err_msg; + + sqlite3_exec(global_database, "BEGIN TRANSACTION;", NULL, NULL, NULL); + + int rc = sqlite3_exec(global_database, sql_migration, NULL, NULL, &err_msg); + if(rc) + { + LOGGER_CRIT("couldn't migrate LEVEL %d (%s)\n", level, err_msg); + sqlite3_exec(global_database, "ROLLBACK TRANSACTION;", NULL, NULL, NULL); + exit(1); + } + + LOGGER_DEBUG("storing new user_version %d\n", level + 1); + char pragma_query[32]; + sprintf(pragma_query, "PRAGMA user_version=%d;", level + 1); + sqlite3_exec(global_database, pragma_query, 0, 0, 0); + + sqlite3_exec(global_database, "COMMIT TRANSACTION;", NULL, NULL, NULL); +} + void database_migrate() { uint16_t version_num = 0; - int s, rc; + int s; sqlite3_stmt *stmt; sqlite3_prepare_v2(global_database, "PRAGMA user_version;", -1, &stmt, NULL); s = sqlite3_step(stmt); @@ -49,31 +74,20 @@ database_migrate() version_num = 0; } - uint16_t new_version_num = version_num; - char* err_msg; - sqlite3_finalize(stmt); switch(version_num) { case 0: - LOGGER_INFO("migrating LEVEL 0\n"); - rc = sqlite3_exec(global_database, (const char *)sql_migration_0_sql, NULL, NULL, &err_msg); - if(rc) - { - LOGGER_CRIT("couldn't migrate LEVEL 0 (%s)\n", err_msg); - exit(1); - } - new_version_num = 1; + database_migrate_step_simple(0, (const char*)sql_migration_0_sql); + __attribute__ ((fallthrough)); + case 1: + database_migrate_step_simple(1, (const char*)sql_migration_1_sql); + __attribute__ ((fallthrough)); default: break; } - char pragma_query[32]; - sprintf(pragma_query, "PRAGMA user_version=%d;", new_version_num); - sqlite3_exec(global_database, pragma_query, 0, 0, 0); - LOGGER_DEBUG("storing new user_version %d\n", new_version_num); - return; } diff --git a/src/models/junction_macro.c b/src/models/junction_macro.c new file mode 100644 index 0000000..6ff7b89 --- /dev/null +++ b/src/models/junction_macro.c @@ -0,0 +1,33 @@ +#include <stdlib.h> +#include <stdint.h> +#include <stddef.h> + +#include <models/junction_macro.h> +#include <logger.h> +#include <macros.h> +#include <database.h> + +int +junction_macro_insert(int macro_id, int relay_id, int schedule_id, uint8_t weekday) +{ + int rc; + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "INSERT INTO junction_macro(macro_id, schedule_id, relay_id, weekday) values (?1, ?2, ?3);", -1, &stmt, NULL); + + sqlite3_bind_int(stmt, 1, macro_id); + sqlite3_bind_int(stmt, 2, relay_id); + sqlite3_bind_int(stmt, 3, schedule_id); + sqlite3_bind_int(stmt, 4, weekday); + + rc = sqlite3_step(stmt); + if (rc != SQLITE_DONE) + { + LOGGER_ERR("error inserting data: %s", sqlite3_errmsg(global_database)); + return 1; + } + + sqlite3_finalize(stmt); + + return 0; +} From 0103b0b2ff6bb5ab57a3325f8d0d3f8cd8f43d67 Mon Sep 17 00:00:00 2001 From: Tobias Reisinger <tobias@msrg.cc> Date: Sat, 29 Aug 2020 23:51:45 +0200 Subject: [PATCH 4/9] add: more basic macro stuff add: more efficient relay loading (only ids) --- include/cache.h | 11 +- include/models/junction_relay_schedule.h | 3 + include/models/macro.h | 45 +++ src/cache.c | 37 +- src/models/junction_relay_schedule.c | 11 + src/models/macro.c | 451 +++++++++++++++++++++++ src/models/schedule.c | 4 +- 7 files changed, 555 insertions(+), 7 deletions(-) create mode 100644 include/models/macro.h create mode 100644 src/models/macro.c diff --git a/include/cache.h b/include/cache.h index 8fde368..3e2ff7c 100644 --- a/include/cache.h +++ b/include/cache.h @@ -36,7 +36,6 @@ void cache_invalidate_relay(int relay_id, int status_relay); - void cache_put_json_controller(int controller_id, char *controller_json); @@ -47,6 +46,16 @@ void cache_invalidate_controller(int controller_id); +void +cache_put_json_macro(int macro_id, char *macro_json); + +char* +cache_get_json_macro(int macro_id); + +void +cache_invalidate_macro(int macro_id); + + void cache_invalidate_tagged(int tag_id); diff --git a/include/models/junction_relay_schedule.h b/include/models/junction_relay_schedule.h index d8ef168..e3c81ac 100644 --- a/include/models/junction_relay_schedule.h +++ b/include/models/junction_relay_schedule.h @@ -10,4 +10,7 @@ junction_relay_schedule_remove_for_relay(int relay_id); int junction_relay_schedule_insert_weekdays(int relay_id, int *schedule_ids); +int* +junction_relay_schedule_get_relay_ids_with_schedule(int schedule_id); + #endif /* CORE_MODELS_JUNCTION_RELAY_SCHEDULE_H */ diff --git a/include/models/macro.h b/include/models/macro.h new file mode 100644 index 0000000..b59dd23 --- /dev/null +++ b/include/models/macro.h @@ -0,0 +1,45 @@ +#ifndef CORE_MACRO_H +#define CORE_MACRO_H + +#include <uuid/uuid.h> + +#include <cJSON.h> + +#include <constants.h> +#include <models/period.h> + +typedef struct +{ + int id; + uuid_t uid; + char name[MAX_NAME_LENGTH + 1]; +} macro_t; + +int +macro_save(macro_t *macro); + +int +macro_remove(macro_t *macro); + +void +macro_free(macro_t *macro); + +void +macro_free_list(macro_t **macro); + +cJSON* +macro_to_json(macro_t *macro); + +void +macro_free_list(macro_t **macros_list); + +macro_t* +macro_get_by_id(int id); + +macro_t* +macro_get_by_uid(uuid_t uid); + +macro_t** +macro_get_all(); + +#endif /* CORE_MACRO_H */ diff --git a/src/cache.c b/src/cache.c index 2636ead..cc1d716 100644 --- a/src/cache.c +++ b/src/cache.c @@ -2,6 +2,7 @@ #include <logger.h> #include <sql/cache.h> #include <models/junction_tag.h> +#include <models/junction_relay_schedule.h> sqlite3 *cache_database; @@ -134,14 +135,14 @@ cache_invalidate_schedule(int schedule_id) sprintf(key, "schedule_json:%d", schedule_id); cache_invalidate(key); - relay_t **relays = relay_get_with_schedule(schedule_id); + int *relay_ids = junction_relay_schedule_get_relay_ids_with_schedule(schedule_id); - for(int i = 0; relays[i] != NULL; ++i) + for(int i = 0; relay_ids[i] != 0; ++i) { - cache_invalidate_relay(relays[i]->id, -1); + cache_invalidate_relay(relay_ids[i], -1); } - relay_free_list(relays); + free(relay_ids); } @@ -208,6 +209,34 @@ cache_invalidate_controller(int controller_id) cache_invalidate(key); } + + +void +cache_put_json_macro(int macro_id, char *macro_json) +{ + char key[32]; + sprintf(key, "macro_json:%d", macro_id); + cache_insert_value(key, macro_json); +} + +char* +cache_get_json_macro(int macro_id) +{ + char key[32]; + sprintf(key, "macro_json:%d", macro_id); + return cache_get_value(key); +} + +void +cache_invalidate_macro(int macro_id) +{ + char key[32]; + sprintf(key, "macro_json:%d", macro_id); + cache_invalidate(key); +} + + + void cache_invalidate_tagged(int tag_id) { diff --git a/src/models/junction_relay_schedule.c b/src/models/junction_relay_schedule.c index e2b2309..9ceed85 100644 --- a/src/models/junction_relay_schedule.c +++ b/src/models/junction_relay_schedule.c @@ -87,3 +87,14 @@ junction_relay_schedule_remove_for_relay(int relay_id) return rc == SQLITE_DONE; } + +int* +junction_relay_schedule_get_relay_ids_with_schedule(int schedule_id) +{ + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "SELECT relay_id FROM junction_relay_schedule WHERE schedule_id=?1;", -1, &stmt, NULL); + sqlite3_bind_int(stmt, 1, schedule_id); + + return database_helper_get_ids(stmt); +} diff --git a/src/models/macro.c b/src/models/macro.c new file mode 100644 index 0000000..1aa234e --- /dev/null +++ b/src/models/macro.c @@ -0,0 +1,451 @@ +#include <stdlib.h> +#include <string.h> +#include <sqlite3.h> + +#include <cache.h> +#include <cJSON.h> +#include <logger.h> +#include <database.h> +#include <models/macro.h> +#include <models/junction_macro.h> +#include <models/schedule.h> +#include <models/tag.h> + +static int +db_update_insert(macro_t *macro, sqlite3_stmt *stmt) +{ + LOGGER_DEBUG("saving macro '%s' into database (id: %d)\n", macro->name, macro->id); + + int rc; + + sqlite3_bind_int(stmt, 1, macro->id); + sqlite3_bind_blob(stmt, 2, macro->uid, sizeof(uuid_t), SQLITE_STATIC); + sqlite3_bind_text(stmt, 3, macro->name, -1, SQLITE_STATIC); + + rc = sqlite3_step(stmt); + + sqlite3_finalize(stmt); + + free(periods_blob); + + return rc != SQLITE_DONE; +} +static macro_t* +macro_db_select_mapper(sqlite3_stmt *stmt) +{ + const uint16_t *periods_blob; + macro_t *new_macro = malloc(sizeof(macro_t)); + for(int i = 0; i < sqlite3_column_count(stmt); i++) + { + const char *name = sqlite3_column_name(stmt, i); + switch(name[0]) + { + case 'i': // id + new_macro->id = sqlite3_column_int(stmt, i); + break; + case 'n': // name + strncpy(new_macro->name, (const char*)sqlite3_column_text(stmt, i), MAX_NAME_LENGTH); + new_macro->name[MAX_NAME_LENGTH] = '\0'; + break; + case 'u': // uid + uuid_copy(new_macro->uid, (const unsigned char*)sqlite3_column_blob(stmt, i)); + break; + default: // ignore columns not implemented + break; + } + } + return new_macro; +} + +static macro_t** +macro_db_select(sqlite3_stmt *stmt) +{ + macro_t **all_macros = malloc(sizeof(macro_t*)); + + int row = 0; + + for(;;) + { + int s; + + s = sqlite3_step(stmt); + if (s == SQLITE_ROW) + { + macro_t *new_macro = macro_db_select_mapper(stmt); + row++; + + all_macros = (macro_t**)realloc(all_macros, sizeof(macro_t*) * (row + 1)); + all_macros[row - 1] = new_macro; + } + else + { + if(s == SQLITE_DONE) + { + break; + } + else + { + LOGGER_ERR("error selecting macros from database: %s\n", sqlite3_errstr(s)); + break; + } + } + } + sqlite3_finalize(stmt); + all_macros[row] = NULL; + return all_macros; +} + +int +macro_save(macro_t *macro) +{ + int opened_transaction = database_transaction_begin(); + + sqlite3_stmt *stmt; + if(macro->id) + { + sqlite3_prepare_v2(global_database, "UPDATE macros SET uid = ?2, name = ?3, periods = ?4 WHERE id=?1;", -1, &stmt, NULL); + } + else + { + sqlite3_prepare_v2(global_database, "INSERT INTO macros(uid, name, periods) values (?2, ?3, ?4);", -1, &stmt, NULL); + } + + int result = db_update_insert(macro, stmt); + + if(result) + { + if(macro->id) + { + LOGGER_ERR("error inserting data: %s\n", sqlite3_errmsg(global_database)); + } + else + { + LOGGER_ERR("error updating data: %s\n", sqlite3_errmsg(global_database)); + } + + if(opened_transaction) + { + database_transaction_rollback(); + } + } + else + { + if(!macro->id) + { + macro->id = sqlite3_last_insert_rowid(global_database); + } + + if(opened_transaction) + { + database_transaction_commit(); + } + } + + cache_invalidate_macro(macro->id); + + return result; +} + +int +macro_remove(macro_t *macro) +{ + sqlite3_stmt *stmt; + if(!macro->id) + { + return 0; + } + + sqlite3_prepare_v2(global_database, "DELETE FROM macros WHERE id=?1;", -1, &stmt, NULL); + sqlite3_bind_int(stmt, 1, macro->id); + + int rc = sqlite3_step(stmt); + + sqlite3_finalize(stmt); + + return rc != SQLITE_DONE; +} + +int +macro_is_protected(macro_t *macro) +{ + uuid_t tmp_uuid; + + memset(tmp_uuid, 0, sizeof(uuid_t)); + memcpy(tmp_uuid, "off", 3); + if(uuid_compare(macro->uid, tmp_uuid) == 0) + { + return 1; + } + + memset(tmp_uuid, 0, sizeof(uuid_t)); + memcpy(tmp_uuid, "on", 2); + if(uuid_compare(macro->uid, tmp_uuid) == 0) + { + return 1; + } + + return 0; +} + +void +macro_free(macro_t *macro) +{ + free(macro->periods); + free(macro); +} + +void +macro_free_list(macro_t **macros) +{ + for(int i = 0; macros[i] != NULL; ++i) + { + macro_free(macros[i]); + } + free(macros); +} + +uint16_t* +macro_periods_to_blob(macro_t *macro) +{ + uint16_t *blob = malloc(sizeof(uint16_t) * ((macro->periods_count * 2) + 1)); + + blob[0] = macro->periods_count; + + for(int i = 0; i < macro->periods_count; i++) + { + blob[(i * 2) + 1] = macro->periods[i].start; + blob[(i * 2) + 2] = macro->periods[i].end; + } + return blob; +} + +cJSON* +macro_to_json(macro_t *macro) +{ + cJSON *json; + + char *cached = cache_get_json_macro(macro->id); + if(cached) + { + json = cJSON_CreateRaw(cached); + free(cached); + return json; + } + + char uuid_str[UUID_STR_LEN]; + macro_uid_unparse(macro->uid, uuid_str); + + LOGGER_DEBUG("JSONifying macro %s\n", uuid_str); + + json = cJSON_CreateObject(); + + cJSON *json_name = cJSON_CreateString(macro->name); + if(json_name == NULL) + { + cJSON_Delete(json); + return NULL; + } + cJSON_AddItemToObject(json, "name", json_name); + + cJSON *json_id = cJSON_CreateString(uuid_str); + if(json_name == NULL) + { + cJSON_Delete(json); + return NULL; + } + cJSON_AddItemToObject(json, "id", json_id); + + cJSON *json_tags = cJSON_CreateArray(); + int *tags_ids = junction_tag_get_tags_for_macro_id(macro->id); + if(tags_ids != NULL) + { + for(int i = 0; tags_ids[i] != 0; ++i) + { + char *tag = tag_get_tag(tags_ids[i]); + if(tag == NULL) + { + continue; + } + + cJSON *json_tag = cJSON_CreateString(tag); + if (json_tag == NULL) + { + LOGGER_DEBUG("failed to add tag from string '%s'\n", tag); + free(tag); + continue; + } + cJSON_AddItemToArray(json_tags, json_tag); + free(tag); + } + free(tags_ids); + } + cJSON_AddItemToObject(json, "tags", json_tags); + + char *json_str = cJSON_Print(json); + cache_put_json_macro(macro->id, json_str); + cJSON_Delete(json); + + json = cJSON_CreateRaw(json_str); + free(json_str); + return json; +} + +macro_t* +macro_get_by_id_or_off(int id) +{ + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "SELECT * FROM macros WHERE id = ?1;", -1, &stmt, NULL); + sqlite3_bind_int(stmt, 1, id); + + macro_t **sql_result = macro_db_select(stmt); + + macro_t *result = sql_result[0]; + free(sql_result); + + if(result) + { + return result; + } + + uuid_t tmp_uuid; + memset(tmp_uuid, 0, sizeof(uuid_t)); + memcpy(tmp_uuid, "off", 3); + + return macro_get_by_uid(tmp_uuid); +} + +macro_t* +macro_get_by_id(int id) +{ + LOGGER_DEBUG("getting macro [id=%d] from database\n", id); + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "SELECT * FROM macros WHERE id = ?1;", -1, &stmt, NULL); + sqlite3_bind_int(stmt, 1, id); + + macro_t **sql_result = macro_db_select(stmt); + + macro_t *result = sql_result[0]; + free(sql_result); + + return result; +} + +macro_t* +macro_get_by_uid_or_off(uuid_t uid) +{ + char uuid_str[UUID_STR_LEN]; + macro_uid_unparse(uid, uuid_str); + LOGGER_DEBUG("getting macro [uid=%s] or off from database\n", uuid_str); + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "SELECT * FROM macros WHERE uid = ?1;", -1, &stmt, NULL); + sqlite3_bind_blob(stmt, 1, uid, sizeof(uuid_t), SQLITE_STATIC); + + macro_t **sql_result = macro_db_select(stmt); + + macro_t *result = sql_result[0]; + free(sql_result); + + if(result) + { + return result; + } + + uuid_t tmp_uuid; + memset(tmp_uuid, 0, sizeof(uuid_t)); + memcpy(tmp_uuid, "off", 3); + + return macro_get_by_uid(tmp_uuid); +} + +macro_t* +macro_get_by_uid(uuid_t uid) +{ + char uuid_str[UUID_STR_LEN]; + macro_uid_unparse(uid, uuid_str); + LOGGER_DEBUG("getting macro [uid=%s] from database\n", uuid_str); + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "SELECT * FROM macros WHERE uid = ?1;", -1, &stmt, NULL); + sqlite3_bind_blob(stmt, 1, uid, sizeof(uuid_t), SQLITE_STATIC); + + macro_t **sql_result = macro_db_select(stmt); + + macro_t *result = sql_result[0]; + free(sql_result); + + return result; +} + +macro_t** +macro_get_relay_weekdays(int relay_id) +{ + LOGGER_DEBUG("getting macros [relay_id=%d] from database\n", relay_id); + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "SELECT macros.* FROM macros INNER JOIN junction_relay_macro ON macros.id == junction_relay_macro.macro_id WHERE junction_relay_macro.relay_id = ?1 ORDER BY junction_relay_macro.weekday ASC", -1, &stmt, NULL); + sqlite3_bind_int(stmt, 1, relay_id); + + return macro_db_select(stmt); +} + +macro_t** +macro_get_all() +{ + LOGGER_DEBUG("getting all macros from database\n"); + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "SELECT * FROM macros;", -1, &stmt, NULL); + + return macro_db_select(stmt); + +} + +int +macro_uid_parse(const char *uid_str, uuid_t result) +{ + if(strcmp("off", uid_str) == 0) + { + memset(result, 0, sizeof(uuid_t)); + memcpy(result, "off", 3); + return 0; + } + if(strcmp("on", uid_str) == 0) + { + memset(result, 0, sizeof(uuid_t)); + memcpy(result, "on", 2); + return 0; + } + + if(uuid_parse(uid_str, result)) + { + return 1; + } + return 0; +} + +void +macro_uid_unparse(const uuid_t uid, char *result) +{ + uuid_t tmp_uuid; + + memset(tmp_uuid, 0, sizeof(uuid_t)); + memcpy(tmp_uuid, "off", 3); + if(uuid_compare(uid, tmp_uuid) == 0) + { + strcpy(result, "off"); + return; + } + + memset(tmp_uuid, 0, sizeof(uuid_t)); + memcpy(tmp_uuid, "on", 2); + if(uuid_compare(uid, tmp_uuid) == 0) + { + strcpy(result, "on"); + return; + } + + uuid_unparse(uid, result); +} diff --git a/src/models/schedule.c b/src/models/schedule.c index abb6850..9225007 100644 --- a/src/models/schedule.c +++ b/src/models/schedule.c @@ -46,8 +46,8 @@ schedule_db_select_mapper(sqlite3_stmt *stmt) new_schedule->id = sqlite3_column_int(stmt, i); break; case 'n': // name - strncpy(new_schedule->name, (const char*)sqlite3_column_text(stmt, i), 127); - new_schedule->name[127] = '\0'; + strncpy(new_schedule->name, (const char*)sqlite3_column_text(stmt, i), MAX_NAME_LENGTH); + new_schedule->name[MAX_NAME_LENGTH] = '\0'; break; case 'p': // periods periods_blob = sqlite3_column_blob(stmt, i); From 6a2b94ef1c8b37f625700c9044adc1afeb91b413 Mon Sep 17 00:00:00 2001 From: Tobias Reisinger <tobias@msrg.cc> Date: Sun, 30 Aug 2020 17:22:51 +0200 Subject: [PATCH 5/9] fix: allow program to compile --- src/models/macro.c | 74 +++------------------------------------------- 1 file changed, 4 insertions(+), 70 deletions(-) diff --git a/src/models/macro.c b/src/models/macro.c index 1aa234e..803cea7 100644 --- a/src/models/macro.c +++ b/src/models/macro.c @@ -26,14 +26,11 @@ db_update_insert(macro_t *macro, sqlite3_stmt *stmt) sqlite3_finalize(stmt); - free(periods_blob); - return rc != SQLITE_DONE; } static macro_t* macro_db_select_mapper(sqlite3_stmt *stmt) { - const uint16_t *periods_blob; macro_t *new_macro = malloc(sizeof(macro_t)); for(int i = 0; i < sqlite3_column_count(stmt); i++) { @@ -190,7 +187,6 @@ macro_is_protected(macro_t *macro) void macro_free(macro_t *macro) { - free(macro->periods); free(macro); } @@ -204,21 +200,6 @@ macro_free_list(macro_t **macros) free(macros); } -uint16_t* -macro_periods_to_blob(macro_t *macro) -{ - uint16_t *blob = malloc(sizeof(uint16_t) * ((macro->periods_count * 2) + 1)); - - blob[0] = macro->periods_count; - - for(int i = 0; i < macro->periods_count; i++) - { - blob[(i * 2) + 1] = macro->periods[i].start; - blob[(i * 2) + 2] = macro->periods[i].end; - } - return blob; -} - cJSON* macro_to_json(macro_t *macro) { @@ -233,7 +214,7 @@ macro_to_json(macro_t *macro) } char uuid_str[UUID_STR_LEN]; - macro_uid_unparse(macro->uid, uuid_str); + uuid_unparse(macro->uid, uuid_str); LOGGER_DEBUG("JSONifying macro %s\n", uuid_str); @@ -256,7 +237,7 @@ macro_to_json(macro_t *macro) cJSON_AddItemToObject(json, "id", json_id); cJSON *json_tags = cJSON_CreateArray(); - int *tags_ids = junction_tag_get_tags_for_macro_id(macro->id); + int *tags_ids = NULL; //junction_tag_get_tags_for_macro_id(macro->id); if(tags_ids != NULL) { for(int i = 0; tags_ids[i] != 0; ++i) @@ -336,7 +317,7 @@ macro_t* macro_get_by_uid_or_off(uuid_t uid) { char uuid_str[UUID_STR_LEN]; - macro_uid_unparse(uid, uuid_str); + uuid_unparse(uid, uuid_str); LOGGER_DEBUG("getting macro [uid=%s] or off from database\n", uuid_str); sqlite3_stmt *stmt; @@ -364,7 +345,7 @@ macro_t* macro_get_by_uid(uuid_t uid) { char uuid_str[UUID_STR_LEN]; - macro_uid_unparse(uid, uuid_str); + uuid_unparse(uid, uuid_str); LOGGER_DEBUG("getting macro [uid=%s] from database\n", uuid_str); sqlite3_stmt *stmt; @@ -402,50 +383,3 @@ macro_get_all() return macro_db_select(stmt); } - -int -macro_uid_parse(const char *uid_str, uuid_t result) -{ - if(strcmp("off", uid_str) == 0) - { - memset(result, 0, sizeof(uuid_t)); - memcpy(result, "off", 3); - return 0; - } - if(strcmp("on", uid_str) == 0) - { - memset(result, 0, sizeof(uuid_t)); - memcpy(result, "on", 2); - return 0; - } - - if(uuid_parse(uid_str, result)) - { - return 1; - } - return 0; -} - -void -macro_uid_unparse(const uuid_t uid, char *result) -{ - uuid_t tmp_uuid; - - memset(tmp_uuid, 0, sizeof(uuid_t)); - memcpy(tmp_uuid, "off", 3); - if(uuid_compare(uid, tmp_uuid) == 0) - { - strcpy(result, "off"); - return; - } - - memset(tmp_uuid, 0, sizeof(uuid_t)); - memcpy(tmp_uuid, "on", 2); - if(uuid_compare(uid, tmp_uuid) == 0) - { - strcpy(result, "on"); - return; - } - - uuid_unparse(uid, result); -} From 9d2c48d64513f121b1385921157ba707ea18878b Mon Sep 17 00:00:00 2001 From: Tobias Reisinger <tobias@msrg.cc> Date: Fri, 4 Sep 2020 00:28:49 +0200 Subject: [PATCH 6/9] add: macro endpoints add: basic macro support fix: database locking with lock-pointer fix: memory leaks --- .drone.yml | 18 +- .editorconfig | 4 + include/database.h | 10 +- include/endpoints/api_v1_macros.h | 18 ++ include/models/junction_macro.h | 7 - include/models/macro.h | 1 + include/models/macro_action.h | 27 ++ sql/migration_1.sql | 2 +- src/cache.c | 17 +- src/command.c | 6 +- src/database.c | 36 +-- src/endpoint.c | 2 +- src/endpoints/api_v1_controllers_STR.c | 3 +- .../api_v1_controllers_STR_relays_INT.c | 37 ++- .../api_v1_controllers_STR_relays_INT_pulse.c | 9 +- src/endpoints/api_v1_macros.c | 257 ++++++++++++++++++ src/endpoints/api_v1_schedules.c | 1 + src/endpoints/api_v1_schedules_STR.c | 3 +- src/endpoints/api_v1_tags.c | 5 +- src/endpoints/api_v1_tags_STR.c | 3 +- src/models/controller.c | 13 +- src/models/junction_macro.c | 33 --- src/models/junction_relay_schedule.c | 6 +- src/models/junction_tag.c | 2 + src/models/macro.c | 126 +++------ src/models/macro_action.c | 139 ++++++++++ src/models/relay.c | 13 +- src/models/schedule.c | 13 +- src/router.c | 6 + tests/run_tests.sh | 2 +- 30 files changed, 606 insertions(+), 213 deletions(-) create mode 100644 include/endpoints/api_v1_macros.h delete mode 100644 include/models/junction_macro.h create mode 100644 include/models/macro_action.h create mode 100644 src/endpoints/api_v1_macros.c delete mode 100644 src/models/junction_macro.c create mode 100644 src/models/macro_action.c diff --git a/.drone.yml b/.drone.yml index ce40462..3394189 100644 --- a/.drone.yml +++ b/.drone.yml @@ -29,12 +29,12 @@ steps: image: serguzim/emgauwa-builder pull: always commands: - - tar xzf emgauwa-controller.tar.gz - - cd controller - - mkdir build - - cd build - - cmake -DWIRING_PI_DEBUG=on .. - - make + - tar xzf emgauwa-controller.tar.gz + - cd controller + - mkdir build + - cd build + - cmake -DWIRING_PI_DEBUG=on .. + - make - name: test image: serguzim/emgauwa-builder @@ -47,6 +47,12 @@ steps: - cmake .. - make test +- name: show-log-valgrind + image: bash + pull: always + commands: + - cat tests/testing_latest/valgrind.log + - name: gitea_release image: plugins/gitea-release settings: diff --git a/.editorconfig b/.editorconfig index ab2168d..146a218 100644 --- a/.editorconfig +++ b/.editorconfig @@ -10,3 +10,7 @@ end_of_line = lf insert_final_newline = true indent_style = space indent_size = 4 + +[*.yml] +indent_style = space +indent_size = 2 diff --git a/include/database.h b/include/database.h index dde8177..c393013 100644 --- a/include/database.h +++ b/include/database.h @@ -3,6 +3,8 @@ #include <sqlite3.h> +typedef int database_transaction_lock; + extern sqlite3 *global_database; void @@ -15,14 +17,14 @@ void database_migrate(); -int -database_transaction_begin(); +void +database_transaction_begin(database_transaction_lock *lock); void -database_transaction_commit(); +database_transaction_commit(database_transaction_lock *lock); void -database_transaction_rollback(); +database_transaction_rollback(database_transaction_lock *lock); int diff --git a/include/endpoints/api_v1_macros.h b/include/endpoints/api_v1_macros.h new file mode 100644 index 0000000..6a15961 --- /dev/null +++ b/include/endpoints/api_v1_macros.h @@ -0,0 +1,18 @@ +#ifndef CORE_ENDPOINTS_API_V1_MACROS_H +#define CORE_ENDPOINTS_API_V1_MACROS_H + +#include <router.h> + +void +api_v1_macros_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response); + +void +api_v1_macros_POST(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response); + +//void +//api_v1_tags_STR_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response); + +//void +//api_v1_tags_STR_DELETE(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response); + +#endif /* CORE_ENDPOINTS_API_V1_MACROS_H */ diff --git a/include/models/junction_macro.h b/include/models/junction_macro.h deleted file mode 100644 index 6998c50..0000000 --- a/include/models/junction_macro.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef CORE_JUNCTION_MACRO_H -#define CORE_JUNCTION_MACRO_H - -int -junction_macro_insert(int macro_id, int relay_id, int schedule_id, uint8_t weekday); - -#endif /* CORE_JUNCTION_MACRO_H */ diff --git a/include/models/macro.h b/include/models/macro.h index b59dd23..0ceb1ca 100644 --- a/include/models/macro.h +++ b/include/models/macro.h @@ -7,6 +7,7 @@ #include <constants.h> #include <models/period.h> +#include <models/macro_action.h> typedef struct { diff --git a/include/models/macro_action.h b/include/models/macro_action.h new file mode 100644 index 0000000..7505e0c --- /dev/null +++ b/include/models/macro_action.h @@ -0,0 +1,27 @@ +#ifndef CORE_MODELS_MACRO_ACTION_H +#define CORE_MODELS_MACRO_ACTION_H + +typedef struct +{ + int macro_id; + int relay_id; + int schedule_id; + uint8_t weekday; +} macro_action_t; + +int +macro_action_insert(macro_action_t *macro_action); + +macro_action_t** +macro_action_get_for_macro(int macro_id); + +void +macro_action_free_list(macro_action_t **macro_actions); + +int* +macro_action_get_macro_ids_with_schedule(int schedule_id); + +int* +macro_action_get_macro_ids_with_relay(int relay_id); + +#endif /* CORE_MODELS_MACRO_ACTION_H */ diff --git a/sql/migration_1.sql b/sql/migration_1.sql index da01bf0..5078763 100644 --- a/sql/migration_1.sql +++ b/sql/migration_1.sql @@ -11,7 +11,7 @@ CREATE TABLE macros name VARCHAR(128) ); -CREATE TABLE junction_macro +CREATE TABLE macro_actions ( macro_id INTEGER NOT NULL diff --git a/src/cache.c b/src/cache.c index cc1d716..5345801 100644 --- a/src/cache.c +++ b/src/cache.c @@ -1,6 +1,7 @@ #include <cache.h> #include <logger.h> #include <sql/cache.h> +#include <models/macro_action.h> #include <models/junction_tag.h> #include <models/junction_relay_schedule.h> @@ -136,13 +137,18 @@ cache_invalidate_schedule(int schedule_id) cache_invalidate(key); int *relay_ids = junction_relay_schedule_get_relay_ids_with_schedule(schedule_id); - for(int i = 0; relay_ids[i] != 0; ++i) { cache_invalidate_relay(relay_ids[i], -1); } - free(relay_ids); + + int *macro_ids = macro_action_get_macro_ids_with_schedule(schedule_id); + for(int i = 0; macro_ids[i] != 0; ++i) + { + cache_invalidate_macro(macro_ids[i]); + } + free(macro_ids); } @@ -181,6 +187,13 @@ cache_invalidate_relay(int relay_id, int status_relay) { cache_invalidate_controller(controller_id); } + + int *macro_ids = macro_action_get_macro_ids_with_relay(relay_id); + for(int i = 0; macro_ids[i] != 0; ++i) + { + cache_invalidate_macro(macro_ids[i]); + } + free(macro_ids); } diff --git a/src/command.c b/src/command.c index ec299ad..9091a53 100644 --- a/src/command.c +++ b/src/command.c @@ -90,13 +90,17 @@ command_schedule_update(schedule_t *schedule) LOGGER_ERR("couldn't find controller for relay %d\n", relays[i]->id); continue; } - controller_free(controller); LOGGER_DEBUG("sending command to controller %s\n", controller->name); + result |= command_send(controller, payload, payload_size); + + controller_free(controller); } relay_free_list(relays); + free(payload); + return result; } diff --git a/src/database.c b/src/database.c index a0f5aeb..7a46488 100644 --- a/src/database.c +++ b/src/database.c @@ -8,7 +8,7 @@ #include <sql/migration_1.h> sqlite3 *global_database; -static int in_transaction; +static database_transaction_lock *transaction_lock; void database_init() @@ -24,7 +24,7 @@ database_init() database_migrate(); sqlite3_exec(global_database, "PRAGMA foreign_keys = ON", 0, 0, 0); - in_transaction = 0; + transaction_lock = NULL; } void @@ -91,33 +91,37 @@ database_migrate() return; } -int -database_transaction_begin() +void +database_transaction_begin(database_transaction_lock *lock) { - if(!in_transaction) + if(transaction_lock == NULL) { LOGGER_DEBUG("beginning transaction\n"); sqlite3_exec(global_database, "BEGIN TRANSACTION;", NULL, NULL, NULL); - in_transaction = 1; - return 1; + transaction_lock = lock; } - return 0; } void -database_transaction_commit() +database_transaction_commit(database_transaction_lock *lock) { - LOGGER_DEBUG("commiting transaction\n"); - sqlite3_exec(global_database, "COMMIT TRANSACTION;", NULL, NULL, NULL); - in_transaction = 0; + if(transaction_lock == lock) + { + LOGGER_DEBUG("commiting transaction\n"); + sqlite3_exec(global_database, "COMMIT TRANSACTION;", NULL, NULL, NULL); + transaction_lock = NULL; + } } void -database_transaction_rollback() +database_transaction_rollback(database_transaction_lock *lock) { - LOGGER_DEBUG("rolling back transaction\n"); - sqlite3_exec(global_database, "ROLLBACK TRANSACTION;", NULL, NULL, NULL); - in_transaction = 0; + if(transaction_lock == lock) + { + LOGGER_DEBUG("rolling back transaction\n"); + sqlite3_exec(global_database, "ROLLBACK TRANSACTION;", NULL, NULL, NULL); + transaction_lock = NULL; + } } int diff --git a/src/endpoint.c b/src/endpoint.c index a56f277..0a6ed54 100644 --- a/src/endpoint.c +++ b/src/endpoint.c @@ -53,7 +53,7 @@ endpoint_response_text(endpoint_response_t *response, int status_code, const cha response->status_code = status_code; response->content_type = "text/plain"; - if(content_length >= 0) + if(content_length) { response->content_length = content_length; response->alloced_content = false; diff --git a/src/endpoints/api_v1_controllers_STR.c b/src/endpoints/api_v1_controllers_STR.c index eb4c24d..f4f47f7 100644 --- a/src/endpoints/api_v1_controllers_STR.c +++ b/src/endpoints/api_v1_controllers_STR.c @@ -193,7 +193,8 @@ api_v1_controllers_STR_DELETE(struct mg_connection *nc, struct http_message *hm, else { LOGGER_DEBUG("deleted controller %s\n", args[0].value.v_str); - endpoint_response_text(response, 200, "", 0); + static const char content[] = "delete controller"; + endpoint_response_text(response, 200, content, STRLEN(content)); } controller_free(controller); return; diff --git a/src/endpoints/api_v1_controllers_STR_relays_INT.c b/src/endpoints/api_v1_controllers_STR_relays_INT.c index 738ad39..de5cf7b 100644 --- a/src/endpoints/api_v1_controllers_STR_relays_INT.c +++ b/src/endpoints/api_v1_controllers_STR_relays_INT.c @@ -36,7 +36,10 @@ api_v1_controllers_STR_relays_INT_GET(struct mg_connection *nc, struct http_mess return; } - relay_t* relay = relay_get_for_controller(controller->id, args[1].value.v_int); + int controller_id = controller->id; + controller_free(controller); + + relay_t* relay = relay_get_for_controller(controller_id, args[1].value.v_int); if(!relay) { @@ -53,7 +56,6 @@ api_v1_controllers_STR_relays_INT_GET(struct mg_connection *nc, struct http_mess endpoint_response_json(response, 200, json); cJSON_Delete(json); relay_free(relay); - controller_free(controller); } void @@ -83,7 +85,11 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess return; } - if(args[1].value.v_int > controller->relay_count) + int controller_id = controller->id; + int controller_relay_count = controller->relay_count; + controller_free(controller); + + if(args[1].value.v_int > controller_relay_count) { LOGGER_DEBUG("relay num %d is too high for %s\n", args[1].value.v_int, args[0].value.v_str); @@ -92,7 +98,7 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess return; } - relay_t* relay = relay_get_for_controller(controller->id, args[1].value.v_int); + relay_t* relay = relay_get_for_controller(controller_id, args[1].value.v_int); if(!relay) { @@ -102,7 +108,7 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess relay->number = args[1].value.v_int; snprintf(relay->name, MAX_NAME_LENGTH, "Relay %d", relay->number); relay->name[MAX_NAME_LENGTH] = '\0'; - relay->controller_id = controller->id; + relay->controller_id = controller_id; uuid_t tmp_uuid; memset(tmp_uuid, 0, sizeof(uuid_t)); @@ -117,7 +123,6 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess relay->active_schedule = relay->schedules[helper_get_weekday(time_struct)]; } - controller_free(controller); LOGGER_DEBUG("overwriting relay %d for controller %s\n", args[1].value.v_int, args[0].value.v_str); cJSON *json = cJSON_ParseWithLength(hm->body.p, hm->body.len); @@ -202,16 +207,14 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess } } - int opened_transaction = database_transaction_begin(); + database_transaction_lock lock; + database_transaction_begin(&lock); if(relay_save(relay)) { LOGGER_ERR("failed to save relay\n"); - if(opened_transaction) - { - database_transaction_rollback(); - } + database_transaction_rollback(&lock); cJSON_Delete(json); @@ -237,10 +240,7 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess { LOGGER_DEBUG("invalid tag in tags\n"); - if(opened_transaction) - { - database_transaction_rollback(); - } + database_transaction_rollback(&lock); relay_free(relay); cJSON_Delete(json); @@ -259,13 +259,12 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess } tag_ids[i++] = tag_id; } + junction_tag_insert_list(tag_ids, relay->id, 0, json_tags_count); + free(tag_ids); } - if(opened_transaction) - { - database_transaction_commit(); - } + database_transaction_commit(&lock); cJSON_Delete(json); json = relay_to_json(relay, 0); diff --git a/src/endpoints/api_v1_controllers_STR_relays_INT_pulse.c b/src/endpoints/api_v1_controllers_STR_relays_INT_pulse.c index 22b158a..97eb9de 100644 --- a/src/endpoints/api_v1_controllers_STR_relays_INT_pulse.c +++ b/src/endpoints/api_v1_controllers_STR_relays_INT_pulse.c @@ -36,7 +36,10 @@ api_v1_controllers_STR_relays_INT_pulse_POST(struct mg_connection *nc, struct ht return; } - relay_t* relay = relay_get_for_controller(controller->id, args[1].value.v_int); + int controller_id = controller->id; + controller_free(controller); + + relay_t* relay = relay_get_for_controller(controller_id, args[1].value.v_int); if(!relay) { @@ -64,7 +67,7 @@ api_v1_controllers_STR_relays_INT_pulse_POST(struct mg_connection *nc, struct ht LOGGER_DEBUG("commanding pulse to relay %d for controller %s\n", args[1].value.v_int, args[0].value.v_str); command_relay_pulse(relay, duration); - endpoint_response_text(response, 200, "", 0); + static const char content[] = "sent pulse"; + endpoint_response_text(response, 200, content, STRLEN(content)); relay_free(relay); - controller_free(controller); } diff --git a/src/endpoints/api_v1_macros.c b/src/endpoints/api_v1_macros.c new file mode 100644 index 0000000..309eec8 --- /dev/null +++ b/src/endpoints/api_v1_macros.c @@ -0,0 +1,257 @@ +#include <cJSON.h> +#include <macros.h> +#include <constants.h> +#include <database.h> +#include <endpoints/api_v1_macros.h> +#include <logger.h> +#include <models/macro.h> +#include <models/macro_action.h> +#include <models/schedule.h> +#include <models/relay.h> +#include <models/controller.h> + +void +api_v1_macros_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response) +{ + (void)args; + (void)hm; + (void)nc; + + macro_t** all_macros = macro_get_all(); + + cJSON *json = cJSON_CreateArray(); + + for(int i = 0; all_macros[i] != NULL; ++i) + { + cJSON_AddItemToArray(json, macro_to_json(all_macros[i])); + free(all_macros[i]); + } + + endpoint_response_json(response, 200, json); + cJSON_Delete(json); + free(all_macros); +} + +void +api_v1_macros_POST(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response) +{ + (void)args; + (void)nc; + + cJSON *json = cJSON_ParseWithLength(hm->body.p, hm->body.len); + + if(json == NULL) + { + static const char content[] = "no valid json was supplied"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + + cJSON *json_name = cJSON_GetObjectItemCaseSensitive(json, "name"); + if(!cJSON_IsString(json_name) || (json_name->valuestring == NULL)) + { + LOGGER_DEBUG("no name for macro provided\n"); + cJSON_Delete(json); + + static const char content[] = "no name for macro provided"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + + cJSON *json_actions = cJSON_GetObjectItemCaseSensitive(json, "actions"); + if(!cJSON_IsArray(json_actions)) + { + LOGGER_DEBUG("no actions for macro provided\n"); + cJSON_Delete(json); + + static const char content[] = "no actions for macro provided"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + + database_transaction_lock lock; + database_transaction_begin(&lock); + + macro_t *new_macro = malloc(sizeof(macro_t)); + + new_macro->id = 0; + uuid_generate(new_macro->uid); + + strncpy(new_macro->name, json_name->valuestring, MAX_NAME_LENGTH); + new_macro->name[MAX_NAME_LENGTH] = '\0'; + + if(macro_save(new_macro)) + { + LOGGER_DEBUG("macro could not be saved\n"); + + database_transaction_rollback(&lock); + + cJSON_Delete(json); + macro_free(new_macro); + + static const char content[] = "macro could not be saved"; + endpoint_response_text(response, 500, content, STRLEN(content)); + return; + } + + cJSON *json_action; + cJSON_ArrayForEach(json_action, json_actions) + { + cJSON *json_action_weekday = cJSON_GetObjectItemCaseSensitive(json_action, "weekday"); + if(!cJSON_IsNumber(json_action_weekday) || (json_action_weekday->valueint < 0) || (json_action_weekday->valueint > 6)) + { + LOGGER_DEBUG("one action is missing a weekday\n"); + cJSON_Delete(json); + macro_free(new_macro); + + static const char content[] = "one action is missing a weekday"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + + cJSON *json_action_schedule = cJSON_GetObjectItemCaseSensitive(json_action, "schedule"); + if(!cJSON_IsObject(json_action_schedule)) + { + LOGGER_DEBUG("action is missing schedule\n"); + cJSON_Delete(json); + macro_free(new_macro); + + static const char content[] = "one action is missing schedule"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + cJSON *json_action_schedule_uid = cJSON_GetObjectItemCaseSensitive(json_action_schedule, "id"); + if(!cJSON_IsString(json_action_schedule_uid) || (json_action_schedule_uid->valuestring == NULL)) + { + LOGGER_DEBUG("action is missing schedule id\n"); + cJSON_Delete(json); + macro_free(new_macro); + + static const char content[] = "one action is missing schedule id"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + uuid_t action_schedule_uid; + if(schedule_uid_parse(json_action_schedule_uid->valuestring, action_schedule_uid)) + { + LOGGER_DEBUG("action schedule has bad uid\n"); + cJSON_Delete(json); + + static const char content[] = "action schedule has bad id"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + + schedule_t *action_schedule = schedule_get_by_uid(action_schedule_uid); + if(action_schedule == NULL) + { + LOGGER_DEBUG("action schedule was not found\n"); + cJSON_Delete(json); + + static const char content[] = "action schedule was not found"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + + int action_schedule_id = action_schedule->id; + schedule_free(action_schedule); + + + cJSON *json_action_relay = cJSON_GetObjectItemCaseSensitive(json_action, "relay"); + if(!cJSON_IsObject(json_action_relay)) + { + LOGGER_DEBUG("action is missing relay\n"); + cJSON_Delete(json); + macro_free(new_macro); + + static const char content[] = "one action is missing relay"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + cJSON *json_action_relay_number = cJSON_GetObjectItemCaseSensitive(json_action_relay, "number"); + if(!cJSON_IsNumber(json_action_relay_number)) + { + LOGGER_DEBUG("action is missing relay number\n"); + cJSON_Delete(json); + macro_free(new_macro); + + static const char content[] = "one action is missing relay number"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + cJSON *json_action_relay_controller_uid = cJSON_GetObjectItemCaseSensitive(json_action_relay, "controller_id"); + if(!cJSON_IsString(json_action_relay_controller_uid) || (json_action_relay_controller_uid->valuestring == NULL)) + { + LOGGER_DEBUG("action is missing relay controller id\n"); + cJSON_Delete(json); + macro_free(new_macro); + + static const char content[] = "one action is missing relay controller id"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + uuid_t action_controller_uid; + if(uuid_parse(json_action_relay_controller_uid->valuestring, action_controller_uid)) + { + LOGGER_DEBUG("action controller has bad uid\n"); + cJSON_Delete(json); + + static const char content[] = "action controller has bad id"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + + controller_t *action_controller = controller_get_by_uid(action_controller_uid); + if(action_controller == NULL) + { + LOGGER_DEBUG("action controller was not found\n"); + cJSON_Delete(json); + + static const char content[] = "action controller was not found"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + + int controller_id = action_controller->id; + int relay_num = json_action_relay_number->valueint; + + controller_free(action_controller); + + relay_t *action_relay = relay_get_for_controller(controller_id, relay_num); + if(action_relay == NULL) + { + LOGGER_DEBUG("action relay was not found\n"); + cJSON_Delete(json); + + static const char content[] = "action relay was not found"; + endpoint_response_text(response, 400, content, STRLEN(content)); + return; + } + + int action_relay_id = action_relay->id; + relay_free(action_relay); + + + macro_action_t *new_action = malloc(sizeof(macro_action_t)); + new_action->macro_id = new_macro->id; + new_action->relay_id = action_relay_id; + new_action->schedule_id = action_schedule_id; + new_action->weekday = json_action_weekday->valueint; + + macro_action_insert(new_action); + free(new_action); + } + + + + database_transaction_commit(&lock); + + cJSON_Delete(json); + json = macro_to_json(new_macro); + + endpoint_response_json(response, 201, json); + + cJSON_Delete(json); + macro_free(new_macro); +} + diff --git a/src/endpoints/api_v1_schedules.c b/src/endpoints/api_v1_schedules.c index 2dad24d..eda0f2e 100644 --- a/src/endpoints/api_v1_schedules.c +++ b/src/endpoints/api_v1_schedules.c @@ -31,6 +31,7 @@ api_v1_schedules_POST(struct mg_connection *nc, struct http_message *hm, endpoin endpoint_response_text(response, 400, content, STRLEN(content)); return; } + cJSON *json_periods = cJSON_GetObjectItemCaseSensitive(json, "periods"); if(!cJSON_IsArray(json_periods)) { diff --git a/src/endpoints/api_v1_schedules_STR.c b/src/endpoints/api_v1_schedules_STR.c index 03613d1..26e8689 100644 --- a/src/endpoints/api_v1_schedules_STR.c +++ b/src/endpoints/api_v1_schedules_STR.c @@ -226,7 +226,8 @@ api_v1_schedules_STR_DELETE(struct mg_connection *nc, struct http_message *hm, e } else { - endpoint_response_text(response, 200, "", 0); + static const char content[] = "deleted schedule"; + endpoint_response_text(response, 200, content, STRLEN(content)); } schedule_free(schedule); return; diff --git a/src/endpoints/api_v1_tags.c b/src/endpoints/api_v1_tags.c index 2bd4afa..26b08b6 100644 --- a/src/endpoints/api_v1_tags.c +++ b/src/endpoints/api_v1_tags.c @@ -91,7 +91,10 @@ api_v1_tags_POST(struct mg_connection *nc, struct http_message *hm, endpoint_arg { LOGGER_DEBUG("new tag saved\n"); - endpoint_response_text(response, 201, json_tag->valuestring, 0); + char *tag = malloc(sizeof(char) * (strlen(json_tag->valuestring) + 1)); + strcpy(tag, json_tag->valuestring); + + endpoint_response_text(response, 201, tag, 0); } cJSON_Delete(json); diff --git a/src/endpoints/api_v1_tags_STR.c b/src/endpoints/api_v1_tags_STR.c index c9f0426..6aca7f0 100644 --- a/src/endpoints/api_v1_tags_STR.c +++ b/src/endpoints/api_v1_tags_STR.c @@ -105,6 +105,7 @@ api_v1_tags_STR_DELETE(struct mg_connection *nc, struct http_message *hm, endpoi } else { - endpoint_response_text(response, 200, "", 0); + static const char content[] = "deleted tag"; + endpoint_response_text(response, 200, content, STRLEN(content)); } } diff --git a/src/models/controller.c b/src/models/controller.c index 807853c..60a2553 100644 --- a/src/models/controller.c +++ b/src/models/controller.c @@ -117,7 +117,8 @@ controller_db_select(sqlite3_stmt *stmt) int controller_save(controller_t *controller) { - int opened_transaction = database_transaction_begin(); + database_transaction_lock lock; + database_transaction_begin(&lock); sqlite3_stmt *stmt; if(controller->id) @@ -142,10 +143,7 @@ controller_save(controller_t *controller) LOGGER_ERR("error updating data: %s\n", sqlite3_errmsg(global_database)); } - if(opened_transaction) - { - database_transaction_rollback(); - } + database_transaction_rollback(&lock); } else { @@ -154,10 +152,7 @@ controller_save(controller_t *controller) controller->id = sqlite3_last_insert_rowid(global_database); } - if(opened_transaction) - { - database_transaction_commit(); - } + database_transaction_commit(&lock); } cache_invalidate_controller(controller->id); diff --git a/src/models/junction_macro.c b/src/models/junction_macro.c deleted file mode 100644 index 6ff7b89..0000000 --- a/src/models/junction_macro.c +++ /dev/null @@ -1,33 +0,0 @@ -#include <stdlib.h> -#include <stdint.h> -#include <stddef.h> - -#include <models/junction_macro.h> -#include <logger.h> -#include <macros.h> -#include <database.h> - -int -junction_macro_insert(int macro_id, int relay_id, int schedule_id, uint8_t weekday) -{ - int rc; - sqlite3_stmt *stmt; - - sqlite3_prepare_v2(global_database, "INSERT INTO junction_macro(macro_id, schedule_id, relay_id, weekday) values (?1, ?2, ?3);", -1, &stmt, NULL); - - sqlite3_bind_int(stmt, 1, macro_id); - sqlite3_bind_int(stmt, 2, relay_id); - sqlite3_bind_int(stmt, 3, schedule_id); - sqlite3_bind_int(stmt, 4, weekday); - - rc = sqlite3_step(stmt); - if (rc != SQLITE_DONE) - { - LOGGER_ERR("error inserting data: %s", sqlite3_errmsg(global_database)); - return 1; - } - - sqlite3_finalize(stmt); - - return 0; -} diff --git a/src/models/junction_relay_schedule.c b/src/models/junction_relay_schedule.c index 9ceed85..63f844c 100644 --- a/src/models/junction_relay_schedule.c +++ b/src/models/junction_relay_schedule.c @@ -62,16 +62,18 @@ junction_relay_schedule_insert_weekdays(int relay_id, int *schedule_ids) sqlite3_bind_int(stmt, i * 3 + 3, relay_id); } + free(query); + rc = sqlite3_step(stmt); if (rc != SQLITE_DONE) { LOGGER_ERR("error inserting data: %s", sqlite3_errmsg(global_database)); - return false; + return 1; } sqlite3_finalize(stmt); - return true; + return 0; } int diff --git a/src/models/junction_tag.c b/src/models/junction_tag.c index a62bed8..e03a195 100644 --- a/src/models/junction_tag.c +++ b/src/models/junction_tag.c @@ -105,6 +105,8 @@ junction_tag_insert_list(int *tag_ids, int relay_id, int schedule_id, int count) } } + free(query); + rc = sqlite3_step(stmt); if (rc != SQLITE_DONE) { diff --git a/src/models/macro.c b/src/models/macro.c index 803cea7..a40ed61 100644 --- a/src/models/macro.c +++ b/src/models/macro.c @@ -7,7 +7,7 @@ #include <logger.h> #include <database.h> #include <models/macro.h> -#include <models/junction_macro.h> +#include <models/macro_action.h> #include <models/schedule.h> #include <models/tag.h> @@ -28,6 +28,7 @@ db_update_insert(macro_t *macro, sqlite3_stmt *stmt) return rc != SQLITE_DONE; } + static macro_t* macro_db_select_mapper(sqlite3_stmt *stmt) { @@ -95,16 +96,17 @@ macro_db_select(sqlite3_stmt *stmt) int macro_save(macro_t *macro) { - int opened_transaction = database_transaction_begin(); + database_transaction_lock lock; + database_transaction_begin(&lock); sqlite3_stmt *stmt; if(macro->id) { - sqlite3_prepare_v2(global_database, "UPDATE macros SET uid = ?2, name = ?3, periods = ?4 WHERE id=?1;", -1, &stmt, NULL); + sqlite3_prepare_v2(global_database, "UPDATE macros SET uid = ?2, name = ?3 WHERE id=?1;", -1, &stmt, NULL); } else { - sqlite3_prepare_v2(global_database, "INSERT INTO macros(uid, name, periods) values (?2, ?3, ?4);", -1, &stmt, NULL); + sqlite3_prepare_v2(global_database, "INSERT INTO macros(uid, name) values (?2, ?3);", -1, &stmt, NULL); } int result = db_update_insert(macro, stmt); @@ -120,10 +122,7 @@ macro_save(macro_t *macro) LOGGER_ERR("error updating data: %s\n", sqlite3_errmsg(global_database)); } - if(opened_transaction) - { - database_transaction_rollback(); - } + database_transaction_rollback(&lock); } else { @@ -132,10 +131,7 @@ macro_save(macro_t *macro) macro->id = sqlite3_last_insert_rowid(global_database); } - if(opened_transaction) - { - database_transaction_commit(); - } + database_transaction_commit(&lock); } cache_invalidate_macro(macro->id); @@ -236,31 +232,42 @@ macro_to_json(macro_t *macro) } cJSON_AddItemToObject(json, "id", json_id); - cJSON *json_tags = cJSON_CreateArray(); - int *tags_ids = NULL; //junction_tag_get_tags_for_macro_id(macro->id); - if(tags_ids != NULL) + cJSON *json_actions = cJSON_CreateArray(); + macro_action_t **macro_actions = macro_action_get_for_macro(macro->id); + for(int i = 0; macro_actions[i] != NULL; ++i) { - for(int i = 0; tags_ids[i] != 0; ++i) - { - char *tag = tag_get_tag(tags_ids[i]); - if(tag == NULL) - { - continue; - } + cJSON *json_action = cJSON_CreateObject(); - cJSON *json_tag = cJSON_CreateString(tag); - if (json_tag == NULL) - { - LOGGER_DEBUG("failed to add tag from string '%s'\n", tag); - free(tag); - continue; - } - cJSON_AddItemToArray(json_tags, json_tag); - free(tag); + cJSON *json_action_weekday = cJSON_CreateNumber(macro_actions[i]->weekday); + if(json_action_weekday == NULL) + { + LOGGER_DEBUG("failed to create weekday from number %d\n", macro_actions[i]->weekday); + continue; } - free(tags_ids); + + relay_t *relay = relay_get_by_id(macro_actions[i]->relay_id); + if(!relay) + { + LOGGER_DEBUG("failed to get relay\n"); + continue; + } + schedule_t *schedule = schedule_get_by_id(macro_actions[i]->schedule_id); + if(!schedule) + { + LOGGER_DEBUG("failed to get schedule\n"); + relay_free(relay); + continue; + } + + cJSON_AddItemToObject(json_action, "weekday", json_action_weekday); + cJSON_AddItemToObject(json_action, "relay", relay_to_json(relay, 0)); + cJSON_AddItemToObject(json_action, "schedule", schedule_to_json(schedule)); + + cJSON_AddItemToArray(json_actions, json_action); } - cJSON_AddItemToObject(json, "tags", json_tags); + cJSON_AddItemToObject(json, "actions", json_actions); + + macro_action_free_list(macro_actions); char *json_str = cJSON_Print(json); cache_put_json_macro(macro->id, json_str); @@ -271,31 +278,6 @@ macro_to_json(macro_t *macro) return json; } -macro_t* -macro_get_by_id_or_off(int id) -{ - sqlite3_stmt *stmt; - - sqlite3_prepare_v2(global_database, "SELECT * FROM macros WHERE id = ?1;", -1, &stmt, NULL); - sqlite3_bind_int(stmt, 1, id); - - macro_t **sql_result = macro_db_select(stmt); - - macro_t *result = sql_result[0]; - free(sql_result); - - if(result) - { - return result; - } - - uuid_t tmp_uuid; - memset(tmp_uuid, 0, sizeof(uuid_t)); - memcpy(tmp_uuid, "off", 3); - - return macro_get_by_uid(tmp_uuid); -} - macro_t* macro_get_by_id(int id) { @@ -313,34 +295,6 @@ macro_get_by_id(int id) return result; } -macro_t* -macro_get_by_uid_or_off(uuid_t uid) -{ - char uuid_str[UUID_STR_LEN]; - uuid_unparse(uid, uuid_str); - LOGGER_DEBUG("getting macro [uid=%s] or off from database\n", uuid_str); - sqlite3_stmt *stmt; - - sqlite3_prepare_v2(global_database, "SELECT * FROM macros WHERE uid = ?1;", -1, &stmt, NULL); - sqlite3_bind_blob(stmt, 1, uid, sizeof(uuid_t), SQLITE_STATIC); - - macro_t **sql_result = macro_db_select(stmt); - - macro_t *result = sql_result[0]; - free(sql_result); - - if(result) - { - return result; - } - - uuid_t tmp_uuid; - memset(tmp_uuid, 0, sizeof(uuid_t)); - memcpy(tmp_uuid, "off", 3); - - return macro_get_by_uid(tmp_uuid); -} - macro_t* macro_get_by_uid(uuid_t uid) { diff --git a/src/models/macro_action.c b/src/models/macro_action.c new file mode 100644 index 0000000..c0333c5 --- /dev/null +++ b/src/models/macro_action.c @@ -0,0 +1,139 @@ +#include <stdlib.h> +#include <stdint.h> +#include <stddef.h> + +#include <models/macro_action.h> +#include <logger.h> +#include <cache.h> +#include <database.h> + +static macro_action_t* +macro_action_db_select_mapper(sqlite3_stmt *stmt) +{ + macro_action_t *new_macro_action = malloc(sizeof(macro_action_t)); + for(int i = 0; i < sqlite3_column_count(stmt); i++) + { + const char *name = sqlite3_column_name(stmt, i); + switch(name[0]) + { + case 'm': // macro_id + new_macro_action->macro_id = sqlite3_column_int(stmt, i); + break; + case 'r': // relay_id + new_macro_action->relay_id = sqlite3_column_int(stmt, i); + break; + case 's': // schedule_id + new_macro_action->schedule_id = sqlite3_column_int(stmt, i); + break; + case 'w': // weekday + new_macro_action->weekday = (uint8_t)sqlite3_column_int(stmt, i); + break; + default: // ignore columns not implemented + break; + } + } + return new_macro_action; +} + +static macro_action_t** +macro_action_db_select(sqlite3_stmt *stmt) +{ + macro_action_t **all_macro_actions = malloc(sizeof(macro_action_t*)); + + int row = 0; + + for(;;) + { + int s; + + s = sqlite3_step(stmt); + if (s == SQLITE_ROW) + { + macro_action_t *new_macro_action = macro_action_db_select_mapper(stmt); + row++; + + all_macro_actions = (macro_action_t**)realloc(all_macro_actions, sizeof(macro_action_t*) * (row + 1)); + all_macro_actions[row - 1] = new_macro_action; + } + else + { + if(s == SQLITE_DONE) + { + break; + } + else + { + LOGGER_ERR("error selecting macro_actions from database: %s\n", sqlite3_errstr(s)); + break; + } + } + } + sqlite3_finalize(stmt); + all_macro_actions[row] = NULL; + return all_macro_actions; +} + +int +macro_action_insert(macro_action_t *macro_action) +{ + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "INSERT INTO macro_actions(macro_id, relay_id, schedule_id, weekday) values (?1, ?2, ?3, ?4);", -1, &stmt, NULL); + + sqlite3_bind_int(stmt, 1, macro_action->macro_id); + sqlite3_bind_int(stmt, 2, macro_action->relay_id); + sqlite3_bind_int(stmt, 3, macro_action->schedule_id); + sqlite3_bind_int(stmt, 4, macro_action->weekday); + + int rc = sqlite3_step(stmt); + + sqlite3_finalize(stmt); + + cache_invalidate_macro(macro_action->macro_id); + + return rc != SQLITE_DONE; +} + +macro_action_t** +macro_action_get_for_macro(int macro_id) +{ + LOGGER_DEBUG("getting macro_actions [macro_id=%d] from database\n", macro_id); + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "SELECT * FROM macro_actions WHERE macro_id=?", -1, &stmt, NULL); + sqlite3_bind_int(stmt, 1, macro_id); + + return macro_action_db_select(stmt); +} + +void +macro_action_free_list(macro_action_t **macro_actions) +{ + for(int i = 0; macro_actions[i] != NULL; ++i) + { + free(macro_actions[i]); + } + free(macro_actions); +} + +int* +macro_action_get_macro_ids_with_schedule(int schedule_id) +{ + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "SELECT macro_id FROM macro_actions WHERE schedule_id=?1;", -1, &stmt, NULL); + sqlite3_bind_int(stmt, 1, schedule_id); + + return database_helper_get_ids(stmt); +} + +int* +macro_action_get_macro_ids_with_relay(int relay_id) +{ + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "SELECT macro_id FROM macro_actions WHERE relay_id=?1;", -1, &stmt, NULL); + sqlite3_bind_int(stmt, 1, relay_id); + + return database_helper_get_ids(stmt); +} diff --git a/src/models/relay.c b/src/models/relay.c index df196f0..4efe837 100644 --- a/src/models/relay.c +++ b/src/models/relay.c @@ -115,7 +115,8 @@ relay_db_select(sqlite3_stmt *stmt) int relay_save(relay_t *relay) { - int opened_transaction = database_transaction_begin(); + database_transaction_lock lock; + database_transaction_begin(&lock); sqlite3_stmt *stmt; if(relay->id) @@ -140,10 +141,7 @@ relay_save(relay_t *relay) LOGGER_ERR("error updating data: %s\n", sqlite3_errmsg(global_database)); } - if(opened_transaction) - { - database_transaction_rollback(); - } + database_transaction_rollback(&lock); } else { @@ -163,10 +161,7 @@ relay_save(relay_t *relay) } junction_relay_schedule_insert_weekdays(relay->id, schedule_ids); - if(opened_transaction) - { - database_transaction_commit(); - } + database_transaction_commit(&lock); } cache_invalidate_relay(relay->id, -1); diff --git a/src/models/schedule.c b/src/models/schedule.c index 9225007..3fc89e8 100644 --- a/src/models/schedule.c +++ b/src/models/schedule.c @@ -112,7 +112,8 @@ schedule_db_select(sqlite3_stmt *stmt) int schedule_save(schedule_t *schedule) { - int opened_transaction = database_transaction_begin(); + database_transaction_lock lock; + database_transaction_begin(&lock); sqlite3_stmt *stmt; if(schedule->id) @@ -137,10 +138,7 @@ schedule_save(schedule_t *schedule) LOGGER_ERR("error updating data: %s\n", sqlite3_errmsg(global_database)); } - if(opened_transaction) - { - database_transaction_rollback(); - } + database_transaction_rollback(&lock); } else { @@ -149,10 +147,7 @@ schedule_save(schedule_t *schedule) schedule->id = sqlite3_last_insert_rowid(global_database); } - if(opened_transaction) - { - database_transaction_commit(); - } + database_transaction_commit(&lock); } cache_invalidate_schedule(schedule->id); diff --git a/src/router.c b/src/router.c index 6c74428..b4b0387 100644 --- a/src/router.c +++ b/src/router.c @@ -10,6 +10,7 @@ #include <endpoints/api_v1_controllers.h> #include <endpoints/api_v1_relays.h> #include <endpoints/api_v1_tags.h> +#include <endpoints/api_v1_macros.h> #include <endpoints/api_v1_ws.h> static endpoint_t endpoints[ROUTER_ENDPOINTS_MAX_COUNT]; @@ -90,6 +91,11 @@ router_init() router_register_endpoint("/api/v1/tags/{str}", HTTP_METHOD_GET, api_v1_tags_STR_GET); router_register_endpoint("/api/v1/tags/{str}", HTTP_METHOD_DELETE, api_v1_tags_STR_DELETE); + router_register_endpoint("/api/v1/macros/", HTTP_METHOD_GET, api_v1_macros_GET); + router_register_endpoint("/api/v1/macros/", HTTP_METHOD_POST, api_v1_macros_POST); + //router_register_endpoint("/api/v1/macros/{str}", HTTP_METHOD_GET, api_v1_macros_STR_GET); + //router_register_endpoint("/api/v1/macros/{str}", HTTP_METHOD_DELETE, api_v1_macros_STR_DELETE); + router_register_endpoint("/api/v1/ws/relays", HTTP_METHOD_WEBSOCKET, api_v1_ws_relays); } diff --git a/tests/run_tests.sh b/tests/run_tests.sh index ec36b70..476b3ba 100755 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -4,7 +4,7 @@ source_dir=$PWD working_dir=$PWD/testing_latest working_bak=$PWD/testing_bak -alias valgrind_emgauwa="valgrind $2 --log-file=$working_dir/valgrind.log" +alias valgrind_emgauwa="valgrind -s $2 --log-file=$working_dir/valgrind.log" rm -rf $working_bak From 01ffb1d58d11801f96a6c4a36e260a0fd37972c0 Mon Sep 17 00:00:00 2001 From: Tobias Reisinger <tobias@msrg.cc> Date: Sat, 5 Sep 2020 13:29:46 +0200 Subject: [PATCH 7/9] add: response macros add: preparation for more macro endpoints --- include/endpoints/api_v1_macros.h | 11 +- include/logger.h | 3 + include/macros.h | 20 +- include/models/macro_action.h | 3 + src/endpoint.c | 5 +- src/endpoints/api_v1_controllers_STR.c | 97 +++--- src/endpoints/api_v1_controllers_STR_relays.c | 10 +- .../api_v1_controllers_STR_relays_INT.c | 57 +--- .../api_v1_controllers_STR_relays_INT_pulse.c | 18 +- src/endpoints/api_v1_controllers_discover.c | 16 +- src/endpoints/api_v1_macros.c | 79 ++--- src/endpoints/api_v1_macros_STR.c | 281 ++++++++++++++++++ src/endpoints/api_v1_relays_tag_STR.c | 8 +- src/endpoints/api_v1_schedules.c | 33 +- src/endpoints/api_v1_schedules_STR.c | 50 +--- src/endpoints/api_v1_schedules_list.c | 34 +-- src/endpoints/api_v1_schedules_tag_STR.c | 8 +- src/endpoints/api_v1_tags.c | 34 +-- src/endpoints/api_v1_tags_STR.c | 24 +- src/handlers/http.c | 4 +- src/logger.c | 2 +- src/models/junction_relay_schedule.c | 6 +- src/models/junction_tag.c | 6 +- src/models/macro.c | 4 +- src/models/macro_action.c | 17 ++ src/router.c | 5 +- 26 files changed, 482 insertions(+), 353 deletions(-) create mode 100644 src/endpoints/api_v1_macros_STR.c diff --git a/include/endpoints/api_v1_macros.h b/include/endpoints/api_v1_macros.h index 6a15961..2809c69 100644 --- a/include/endpoints/api_v1_macros.h +++ b/include/endpoints/api_v1_macros.h @@ -9,10 +9,13 @@ api_v1_macros_GET(struct mg_connection *nc, struct http_message *hm, endpoint_ar void api_v1_macros_POST(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response); -//void -//api_v1_tags_STR_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response); +void +api_v1_macros_STR_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response); -//void -//api_v1_tags_STR_DELETE(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response); +void +api_v1_macros_STR_PUT(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response); + +void +api_v1_macros_STR_DELETE(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response); #endif /* CORE_ENDPOINTS_API_V1_MACROS_H */ diff --git a/include/logger.h b/include/logger.h index fc207f5..20c30e0 100644 --- a/include/logger.h +++ b/include/logger.h @@ -8,9 +8,12 @@ #include <colors.h> #include <config.h> +#define LOG_NONE INT_MAX + void logger_log(int level, const char *filename, int line, const char *func, const char *msg, ...); +#define LOGGER_NONE(...) logger_log(LOG_NONE , __FILE__, __LINE__, __func__, ##__VA_ARGS__) #define LOGGER_DEBUG(...) logger_log(LOG_DEBUG , __FILE__, __LINE__, __func__, ##__VA_ARGS__) #define LOGGER_INFO(...) logger_log(LOG_INFO , __FILE__, __LINE__, __func__, ##__VA_ARGS__) #define LOGGER_NOTICE(...) logger_log(LOG_NOTICE , __FILE__, __LINE__, __func__, ##__VA_ARGS__) diff --git a/include/macros.h b/include/macros.h index 4242abe..062081a 100644 --- a/include/macros.h +++ b/include/macros.h @@ -1,6 +1,24 @@ #ifndef CORE_MACROS_H #define CORE_MACROS_H -#define STRLEN(s) ((sizeof(s)/sizeof(s[0])) - sizeof(s[0])) +#include <logger.h> + +#define M_STRLEN(s) ((sizeof(s)/sizeof(s[0])) - sizeof(s[0])) + +#define M_RESPONSE_TEXT_STATIC(logger_func, response, code, content) do { logger_func("%s\n", content); endpoint_response_text(response, code, content, M_STRLEN(content)); } while(0) +#define M_RESPONSE_400_NO_VALID_JSON(response) M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request is not valid json") +#define M_RESPONSE_400_NO_VALID_ID(response) M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request does not contain valid id (uuid)") +#define M_RESPONSE_400_NO_NAME(response) M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request does not contain a name") + +#define M_RESPONSE_403_PROTECTED_SCHEDULE(response) M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 403, "the target schedule is protected") + +#define M_RESPONSE_404_NO_CONTROLLER_FOUND_FOR_ID(response) M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 404, "no controller was found for the requested id") +#define M_RESPONSE_404_NO_SCHEDULE_FOUND_FOR_ID(response) M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 404, "no schedule was found for the requested id") +#define M_RESPONSE_404_NO_MACRO_FOUND_FOR_ID(response) M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 404, "no schedule was found for the requested id") +#define M_RESPONSE_404_NO_TAG_FOUND(response) M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 404, "the requested tag was not found") + +#define M_RESPONSE_500_FAILED_TO_SAVE_TO_DATABASE(response) M_RESPONSE_TEXT_STATIC(LOGGER_ERR, response, 500, "the server failed to save to the database") +#define M_RESPONSE_500_FAILED_TO_READ_FROM_DATABASE(response) M_RESPONSE_TEXT_STATIC(LOGGER_ERR, response, 500, "the server failed to read from the database") +#define M_RESPONSE_500_FAILED_TO_DELETE_FROM_DATABASE(response) M_RESPONSE_TEXT_STATIC(LOGGER_ERR, response, 500, "the server failed to delete from the database") #endif /* CORE_MACROS_H */ diff --git a/include/models/macro_action.h b/include/models/macro_action.h index 7505e0c..22ddd63 100644 --- a/include/models/macro_action.h +++ b/include/models/macro_action.h @@ -12,6 +12,9 @@ typedef struct int macro_action_insert(macro_action_t *macro_action); +int +macro_action_delete_for_macro(int macro_id); + macro_action_t** macro_action_get_for_macro(int macro_id); diff --git a/src/endpoint.c b/src/endpoint.c index 0a6ed54..5173538 100644 --- a/src/endpoint.c +++ b/src/endpoint.c @@ -84,8 +84,5 @@ endpoint_response_json(endpoint_response_t *response, int status_code, const cJS } } - LOGGER_ERR("failed to print schedule json\n"); - - static const char content[] = "failed to print json"; - endpoint_response_text(response, status_code, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_ERR, response, 500, "failed to print json"); } diff --git a/src/endpoints/api_v1_controllers_STR.c b/src/endpoints/api_v1_controllers_STR.c index f4f47f7..0a6c0ba 100644 --- a/src/endpoints/api_v1_controllers_STR.c +++ b/src/endpoints/api_v1_controllers_STR.c @@ -18,10 +18,7 @@ api_v1_controllers_STR_GET(struct mg_connection *nc, struct http_message *hm, en uuid_t target_uid; if(uuid_parse(args[0].value.v_str, target_uid)) { - LOGGER_DEBUG("failed to unparse uid\n"); - - static const char content[] = "given id was invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_ID(response); return; } @@ -29,10 +26,7 @@ api_v1_controllers_STR_GET(struct mg_connection *nc, struct http_message *hm, en if(!controller) { - LOGGER_DEBUG("could not find a controller for uid '%s'\n", args[0].value.v_str); - - static const char content[] = "no controller for id found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 404, "no controller found for id"); return; } LOGGER_DEBUG("returning controller for uid '%s'\n", args[0].value.v_str); @@ -53,10 +47,7 @@ api_v1_controllers_STR_PUT(struct mg_connection *nc, struct http_message *hm, en uuid_t target_uid; if(uuid_parse(args[0].value.v_str, target_uid)) { - LOGGER_DEBUG("failed to unparse uid\n"); - - static const char content[] = "given id was invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_ID(response); return; } @@ -64,10 +55,7 @@ api_v1_controllers_STR_PUT(struct mg_connection *nc, struct http_message *hm, en if(!controller) { - LOGGER_DEBUG("could not find a controller for uid '%s'\n", args[0].value.v_str); - - static const char content[] = "no controller for id found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_404_NO_CONTROLLER_FOUND_FOR_ID(response); return; } LOGGER_DEBUG("starting overwrite for controller %s\n", args[0].value.v_str); @@ -76,70 +64,64 @@ api_v1_controllers_STR_PUT(struct mg_connection *nc, struct http_message *hm, en if(json == NULL) { - static const char content[] = "no valid json was supplied"; - endpoint_response_text(response, 400, content, STRLEN(content)); controller_free(controller); + + M_RESPONSE_400_NO_VALID_JSON(response); return; } cJSON *json_name = cJSON_GetObjectItemCaseSensitive(json, "name"); if(json_name) { - if(cJSON_IsString(json_name) && json_name->valuestring) + if(!cJSON_IsString(json_name) || json_name->valuestring == NULL) { - strncpy(controller->name, json_name->valuestring, MAX_NAME_LENGTH); - controller->name[MAX_NAME_LENGTH] = '\0'; - LOGGER_DEBUG("new controller name: %s\n", controller->name); - } - else - { - static const char content[] = "the given name is no valid string"; - endpoint_response_text(response, 400, content, STRLEN(content)); cJSON_Delete(json); controller_free(controller); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the given name is invalid"); return; } + + strncpy(controller->name, json_name->valuestring, MAX_NAME_LENGTH); + controller->name[MAX_NAME_LENGTH] = '\0'; + LOGGER_DEBUG("new controller name: %s\n", controller->name); } cJSON *json_ip = cJSON_GetObjectItemCaseSensitive(json, "ip"); if(json_ip) { - if(cJSON_IsString(json_ip) && json_ip->valuestring) + if(!cJSON_IsString(json_ip) || json_ip->valuestring == NULL) { - unsigned char buf[sizeof(struct in_addr)]; - if(inet_pton(AF_INET, json_ip->valuestring, buf)) - { - strncpy(controller->ip, json_ip->valuestring, IP_LENGTH); - controller->ip[IP_LENGTH] = '\0'; - LOGGER_DEBUG("new controller ip: %s\n", controller->ip); - } - else - { - static const char content[] = "the given ip address is no valid IPv4 address"; - endpoint_response_text(response, 400, content, STRLEN(content)); - cJSON_Delete(json); - controller_free(controller); - return; - } + cJSON_Delete(json); + controller_free(controller); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "no ip address given"); + return; + } + + unsigned char buf[sizeof(struct in_addr)]; + if(inet_pton(AF_INET, json_ip->valuestring, buf)) + { + strncpy(controller->ip, json_ip->valuestring, IP_LENGTH); + controller->ip[IP_LENGTH] = '\0'; + LOGGER_DEBUG("new controller ip: %s\n", controller->ip); } else { - static const char content[] = "the given ip address is no valid string"; - endpoint_response_text(response, 400, content, STRLEN(content)); cJSON_Delete(json); controller_free(controller); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the given ip address is not valid"); return; } } if(controller_save(controller)) { - LOGGER_ERR("failed to save controller\n"); controller_free(controller); cJSON_Delete(json); - static const char content[] = "failed to save controller to database"; - endpoint_response_text(response, 500, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_ERR, response, 500, "failed to save controller to database"); return; } LOGGER_DEBUG("saved controller %s\n", args[0].value.v_str); @@ -165,10 +147,7 @@ api_v1_controllers_STR_DELETE(struct mg_connection *nc, struct http_message *hm, uuid_t target_uid; if(uuid_parse(target_uid_str, target_uid)) { - LOGGER_DEBUG("failed to unparse uid\n"); - - static const char content[] = "given id was invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_ID(response); return; } @@ -176,25 +155,17 @@ api_v1_controllers_STR_DELETE(struct mg_connection *nc, struct http_message *hm, if(!controller) { - LOGGER_DEBUG("could not find a controller for uid '%s'\n", args[0].value.v_str); - - static const char content[] = "no controller for id found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_404_NO_CONTROLLER_FOUND_FOR_ID(response); return; } if(controller_remove(controller)) { - LOGGER_ERR("failed to remove controller from database\n"); - - static const char content[] = "failed to remove controller from database"; - endpoint_response_text(response, 500, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_ERR, response, 500, "failed to remove controller from database"); } else { - LOGGER_DEBUG("deleted controller %s\n", args[0].value.v_str); - static const char content[] = "delete controller"; - endpoint_response_text(response, 200, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 200, "deleted controller"); } controller_free(controller); return; diff --git a/src/endpoints/api_v1_controllers_STR_relays.c b/src/endpoints/api_v1_controllers_STR_relays.c index 6accc90..ad8a83e 100644 --- a/src/endpoints/api_v1_controllers_STR_relays.c +++ b/src/endpoints/api_v1_controllers_STR_relays.c @@ -15,10 +15,7 @@ api_v1_controllers_STR_relays_GET(struct mg_connection *nc, struct http_message uuid_t target_uid; if(uuid_parse(args[0].value.v_str, target_uid)) { - LOGGER_DEBUG("failed to unparse uid\n"); - - static const char content[] = "given id was invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_ID(response); return; } @@ -26,10 +23,7 @@ api_v1_controllers_STR_relays_GET(struct mg_connection *nc, struct http_message if(!controller) { - LOGGER_DEBUG("could not find a controller for uid '%s'\n", args[0].value.v_str); - - static const char content[] = "no controller for id found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_404_NO_CONTROLLER_FOUND_FOR_ID(response); return; } diff --git a/src/endpoints/api_v1_controllers_STR_relays_INT.c b/src/endpoints/api_v1_controllers_STR_relays_INT.c index de5cf7b..d6ec00d 100644 --- a/src/endpoints/api_v1_controllers_STR_relays_INT.c +++ b/src/endpoints/api_v1_controllers_STR_relays_INT.c @@ -18,10 +18,7 @@ api_v1_controllers_STR_relays_INT_GET(struct mg_connection *nc, struct http_mess uuid_t target_uid; if(uuid_parse(args[0].value.v_str, target_uid)) { - LOGGER_DEBUG("failed to unparse uid\n"); - - static const char content[] = "given id was invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_ID(response); return; } @@ -29,10 +26,7 @@ api_v1_controllers_STR_relays_INT_GET(struct mg_connection *nc, struct http_mess if(!controller) { - LOGGER_DEBUG("could not find a controller for uid '%s'\n", args[0].value.v_str); - - static const char content[] = "no controller for id found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_404_NO_CONTROLLER_FOUND_FOR_ID(response); return; } @@ -43,10 +37,7 @@ api_v1_controllers_STR_relays_INT_GET(struct mg_connection *nc, struct http_mess if(!relay) { - LOGGER_DEBUG("could not find a relay with num %d for controller '%s'\n", args[1].value.v_int, args[0].value.v_str); - - static const char content[] = "no relay for this controller found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 404, "no relay for this controller found"); return; } @@ -67,10 +58,7 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess uuid_t target_uid; if(uuid_parse(args[0].value.v_str, target_uid)) { - LOGGER_DEBUG("failed to unparse uid\n"); - - static const char content[] = "given id was invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_ID(response); return; } @@ -78,10 +66,7 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess if(!controller) { - LOGGER_DEBUG("could not find a controller for uid '%s'\n", args[0].value.v_str); - - static const char content[] = "no controller for id found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_404_NO_CONTROLLER_FOUND_FOR_ID(response); return; } @@ -91,10 +76,7 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess if(args[1].value.v_int > controller_relay_count) { - LOGGER_DEBUG("relay num %d is too high for %s\n", args[1].value.v_int, args[0].value.v_str); - - static const char content[] = "relay number is too high for this controller"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "relay number is too high for this controller"); return; } @@ -129,8 +111,7 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess if(json == NULL) { - static const char content[] = "no valid json was supplied"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_JSON(response); return; } @@ -154,21 +135,17 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess cJSON *json_schedule_uid = cJSON_GetObjectItemCaseSensitive(json_schedule, "id"); if(!cJSON_IsString(json_schedule_uid) || (json_schedule_uid->valuestring == NULL)) { - LOGGER_DEBUG("schedules[%d] is missing uid\n", schedule_position); cJSON_Delete(json); - static const char content[] = "at least one schedule is missing an id"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "at least one schedule is missing an id"); return; } uuid_t target_uid; if(schedule_uid_parse(json_schedule_uid->valuestring, target_uid)) { - LOGGER_DEBUG("schedules[%d] has bad uid\n", schedule_position); cJSON_Delete(json); - static const char content[] = "at least one schedule has a bad id"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 404, "at least one schedule has a bad id"); return; } @@ -195,11 +172,9 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess uuid_t target_uid; if(schedule_uid_parse(json_active_schedule_uid->valuestring, target_uid)) { - LOGGER_DEBUG("active_schedule has bad uid\n"); cJSON_Delete(json); - static const char content[] = "active_schedule has a bad id"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "active schedule has a bad uid"); return; } relay->schedules[day_of_week] = schedule_get_by_uid_or_off(target_uid); @@ -212,14 +187,10 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess if(relay_save(relay)) { - LOGGER_ERR("failed to save relay\n"); - database_transaction_rollback(&lock); - cJSON_Delete(json); - static const char content[] = "failed to save relay to database"; - endpoint_response_text(response, 500, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_ERR, response, 500, "failed to save relay to database"); return; } @@ -238,16 +209,12 @@ api_v1_controllers_STR_relays_INT_PUT(struct mg_connection *nc, struct http_mess { if(!cJSON_IsString(json_tag) || (json_tag->valuestring == NULL)) { - LOGGER_DEBUG("invalid tag in tags\n"); - database_transaction_rollback(&lock); - relay_free(relay); cJSON_Delete(json); free(tag_ids); - static const char content[] = "invalid tag in tags"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "invalid tag in tags"); return; } const char *tag = json_tag->valuestring; diff --git a/src/endpoints/api_v1_controllers_STR_relays_INT_pulse.c b/src/endpoints/api_v1_controllers_STR_relays_INT_pulse.c index 97eb9de..f72812a 100644 --- a/src/endpoints/api_v1_controllers_STR_relays_INT_pulse.c +++ b/src/endpoints/api_v1_controllers_STR_relays_INT_pulse.c @@ -18,10 +18,7 @@ api_v1_controllers_STR_relays_INT_pulse_POST(struct mg_connection *nc, struct ht uuid_t target_uid; if(uuid_parse(args[0].value.v_str, target_uid)) { - LOGGER_DEBUG("failed to unparse uid\n"); - - static const char content[] = "given id was invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_ID(response); return; } @@ -29,10 +26,7 @@ api_v1_controllers_STR_relays_INT_pulse_POST(struct mg_connection *nc, struct ht if(!controller) { - LOGGER_DEBUG("could not find a controller for uid '%s'\n", args[0].value.v_str); - - static const char content[] = "no controller for id found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_404_NO_CONTROLLER_FOUND_FOR_ID(response); return; } @@ -43,10 +37,7 @@ api_v1_controllers_STR_relays_INT_pulse_POST(struct mg_connection *nc, struct ht if(!relay) { - LOGGER_DEBUG("could not find a relay with num %d for controller '%s'\n", args[1].value.v_int, args[0].value.v_str); - - static const char content[] = "no relay for this controller found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 404, "no relay found"); return; } @@ -67,7 +58,6 @@ api_v1_controllers_STR_relays_INT_pulse_POST(struct mg_connection *nc, struct ht LOGGER_DEBUG("commanding pulse to relay %d for controller %s\n", args[1].value.v_int, args[0].value.v_str); command_relay_pulse(relay, duration); - static const char content[] = "sent pulse"; - endpoint_response_text(response, 200, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 200, "sent pulse"); relay_free(relay); } diff --git a/src/endpoints/api_v1_controllers_discover.c b/src/endpoints/api_v1_controllers_discover.c index d2e00d7..c6d7648 100644 --- a/src/endpoints/api_v1_controllers_discover.c +++ b/src/endpoints/api_v1_controllers_discover.c @@ -114,13 +114,7 @@ api_v1_controllers_discover_POST(struct mg_connection *nc, struct http_message * if(discover_server_port == -1) { - LOGGER_ERR("failed to get server port for discovery\n"); - static const char content[] = ""; - response->status_code = 500; - response->content_type = "text/plain"; - response->content_length = STRLEN(content);; - response->content = content; - response->alloced_content = false; + M_RESPONSE_TEXT_STATIC(LOGGER_ERR, response, 500, "the server failed to prepare discovery"); return; } @@ -130,13 +124,7 @@ api_v1_controllers_discover_POST(struct mg_connection *nc, struct http_message * LOGGER_DEBUG("sending udp broadcast\n"); if(send_udp_broadcast("255.255.255.255", global_config.discovery_port, payload, sizeof(payload)) < 0) { - LOGGER_ERR("failed to send UDP broadcast\n"); - static const char content[] = ""; - response->status_code = 500; - response->content_type = "text/plain"; - response->content_length = STRLEN(content);; - response->content = content; - response->alloced_content = false; + M_RESPONSE_TEXT_STATIC(LOGGER_ERR, response, 500, "the server failed to send discovery broadcast"); return; } diff --git a/src/endpoints/api_v1_macros.c b/src/endpoints/api_v1_macros.c index 309eec8..e78b14f 100644 --- a/src/endpoints/api_v1_macros.c +++ b/src/endpoints/api_v1_macros.c @@ -42,30 +42,23 @@ api_v1_macros_POST(struct mg_connection *nc, struct http_message *hm, endpoint_a if(json == NULL) { - static const char content[] = "no valid json was supplied"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_JSON(response); return; } cJSON *json_name = cJSON_GetObjectItemCaseSensitive(json, "name"); if(!cJSON_IsString(json_name) || (json_name->valuestring == NULL)) { - LOGGER_DEBUG("no name for macro provided\n"); - cJSON_Delete(json); - - static const char content[] = "no name for macro provided"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_NAME(response); return; } cJSON *json_actions = cJSON_GetObjectItemCaseSensitive(json, "actions"); if(!cJSON_IsArray(json_actions)) { - LOGGER_DEBUG("no actions for macro provided\n"); cJSON_Delete(json); - static const char content[] = "no actions for macro provided"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request does not contains actions for the macro"); return; } @@ -82,15 +75,11 @@ api_v1_macros_POST(struct mg_connection *nc, struct http_message *hm, endpoint_a if(macro_save(new_macro)) { - LOGGER_DEBUG("macro could not be saved\n"); - database_transaction_rollback(&lock); - cJSON_Delete(json); macro_free(new_macro); - static const char content[] = "macro could not be saved"; - endpoint_response_text(response, 500, content, STRLEN(content)); + M_RESPONSE_500_FAILED_TO_SAVE_TO_DATABASE(response); return; } @@ -100,56 +89,53 @@ api_v1_macros_POST(struct mg_connection *nc, struct http_message *hm, endpoint_a cJSON *json_action_weekday = cJSON_GetObjectItemCaseSensitive(json_action, "weekday"); if(!cJSON_IsNumber(json_action_weekday) || (json_action_weekday->valueint < 0) || (json_action_weekday->valueint > 6)) { - LOGGER_DEBUG("one action is missing a weekday\n"); + database_transaction_rollback(&lock); cJSON_Delete(json); macro_free(new_macro); - static const char content[] = "one action is missing a weekday"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains an action without weekday"); return; } cJSON *json_action_schedule = cJSON_GetObjectItemCaseSensitive(json_action, "schedule"); if(!cJSON_IsObject(json_action_schedule)) { - LOGGER_DEBUG("action is missing schedule\n"); + database_transaction_rollback(&lock); cJSON_Delete(json); macro_free(new_macro); - static const char content[] = "one action is missing schedule"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains an action without schedule"); return; } cJSON *json_action_schedule_uid = cJSON_GetObjectItemCaseSensitive(json_action_schedule, "id"); if(!cJSON_IsString(json_action_schedule_uid) || (json_action_schedule_uid->valuestring == NULL)) { - LOGGER_DEBUG("action is missing schedule id\n"); + database_transaction_rollback(&lock); cJSON_Delete(json); macro_free(new_macro); - static const char content[] = "one action is missing schedule id"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains an action without schedule id"); return; } uuid_t action_schedule_uid; if(schedule_uid_parse(json_action_schedule_uid->valuestring, action_schedule_uid)) { - LOGGER_DEBUG("action schedule has bad uid\n"); + database_transaction_rollback(&lock); cJSON_Delete(json); + macro_free(new_macro); - static const char content[] = "action schedule has bad id"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains an action with an invalid schedule id"); return; } schedule_t *action_schedule = schedule_get_by_uid(action_schedule_uid); if(action_schedule == NULL) { - LOGGER_DEBUG("action schedule was not found\n"); + database_transaction_rollback(&lock); cJSON_Delete(json); + macro_free(new_macro); - static const char content[] = "action schedule was not found"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 404, "the schedule for at least one action was not found"); return; } @@ -160,55 +146,52 @@ api_v1_macros_POST(struct mg_connection *nc, struct http_message *hm, endpoint_a cJSON *json_action_relay = cJSON_GetObjectItemCaseSensitive(json_action, "relay"); if(!cJSON_IsObject(json_action_relay)) { - LOGGER_DEBUG("action is missing relay\n"); + database_transaction_rollback(&lock); cJSON_Delete(json); macro_free(new_macro); - static const char content[] = "one action is missing relay"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains an action without relay"); return; } cJSON *json_action_relay_number = cJSON_GetObjectItemCaseSensitive(json_action_relay, "number"); if(!cJSON_IsNumber(json_action_relay_number)) { - LOGGER_DEBUG("action is missing relay number\n"); + database_transaction_rollback(&lock); cJSON_Delete(json); macro_free(new_macro); - static const char content[] = "one action is missing relay number"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains an action without relay number"); return; } cJSON *json_action_relay_controller_uid = cJSON_GetObjectItemCaseSensitive(json_action_relay, "controller_id"); if(!cJSON_IsString(json_action_relay_controller_uid) || (json_action_relay_controller_uid->valuestring == NULL)) { - LOGGER_DEBUG("action is missing relay controller id\n"); + database_transaction_rollback(&lock); cJSON_Delete(json); macro_free(new_macro); - static const char content[] = "one action is missing relay controller id"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains an action without relay controller id"); return; } uuid_t action_controller_uid; if(uuid_parse(json_action_relay_controller_uid->valuestring, action_controller_uid)) { - LOGGER_DEBUG("action controller has bad uid\n"); + database_transaction_rollback(&lock); cJSON_Delete(json); + macro_free(new_macro); - static const char content[] = "action controller has bad id"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains an action with an invalid relay controller id"); return; } controller_t *action_controller = controller_get_by_uid(action_controller_uid); if(action_controller == NULL) { - LOGGER_DEBUG("action controller was not found\n"); + database_transaction_rollback(&lock); cJSON_Delete(json); + macro_free(new_macro); - static const char content[] = "action controller was not found"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 404, "the controller for at least one action relay was not found"); return; } @@ -220,11 +203,11 @@ api_v1_macros_POST(struct mg_connection *nc, struct http_message *hm, endpoint_a relay_t *action_relay = relay_get_for_controller(controller_id, relay_num); if(action_relay == NULL) { - LOGGER_DEBUG("action relay was not found\n"); + database_transaction_rollback(&lock); cJSON_Delete(json); + macro_free(new_macro); - static const char content[] = "action relay was not found"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 404, "the relay for at least one action was not found"); return; } diff --git a/src/endpoints/api_v1_macros_STR.c b/src/endpoints/api_v1_macros_STR.c new file mode 100644 index 0000000..e2d228f --- /dev/null +++ b/src/endpoints/api_v1_macros_STR.c @@ -0,0 +1,281 @@ +#include <cJSON.h> +#include <macros.h> +#include <constants.h> +#include <endpoints/api_v1_macros.h> +#include <logger.h> +#include <command.h> +#include <models/macro_action.h> +#include <models/macro.h> +#include <models/relay.h> +#include <models/tag.h> + +void +api_v1_macros_STR_GET(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response) +{ + (void)hm; + (void)nc; + + uuid_t target_uid; + if(uuid_parse(args[0].value.v_str, target_uid)) + { + M_RESPONSE_400_NO_VALID_ID(response); + return; + } + + macro_t* macro = macro_get_by_uid(target_uid); + + if(!macro) + { + M_RESPONSE_404_NO_MACRO_FOUND_FOR_ID(response); + return; + } + + cJSON *json = macro_to_json(macro); + + endpoint_response_json(response, 200, json); + cJSON_Delete(json); + macro_free(macro); +} + +void +api_v1_macros_STR_PUT(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response) +{ + (void)hm; + (void)nc; + + uuid_t target_uid; + if(uuid_parse(args[0].value.v_str, target_uid)) + { + M_RESPONSE_400_NO_VALID_ID(response); + return; + } + + macro_t* macro = macro_get_by_uid(target_uid); + + if(!macro) + { + M_RESPONSE_404_NO_MACRO_FOUND_FOR_ID(response); + return; + } + + cJSON *json = cJSON_ParseWithLength(hm->body.p, hm->body.len); + + if(json == NULL) + { + M_RESPONSE_400_NO_VALID_JSON(response); + return; + } + + database_transaction_lock lock; + database_transaction_begin(&lock); + + cJSON *json_name = cJSON_GetObjectItemCaseSensitive(json, "name"); + if(cJSON_IsString(json_name) && (json_name->valuestring != NULL)) + { + strncpy(macro->name, json_name->valuestring, MAX_NAME_LENGTH); + macro->name[MAX_NAME_LENGTH] = '\0'; + + if(macro_save(macro)) + { + database_transaction_rollback(&lock); + cJSON_Delete(json); + macro_free(macro); + + M_RESPONSE_TEXT_STATIC(LOGGER_ERR, response, 500, "macro could not be saved"); + return; + } + } + + cJSON *json_actions = cJSON_GetObjectItemCaseSensitive(json, "actions"); + if(cJSON_IsArray(json_actions)) + { + macro_action_delete_for_macro(macro->id); + + cJSON *json_action; + cJSON_ArrayForEach(json_action, json_actions) + { + cJSON *json_action_weekday = cJSON_GetObjectItemCaseSensitive(json_action, "weekday"); + if(!cJSON_IsNumber(json_action_weekday) || (json_action_weekday->valueint < 0) || (json_action_weekday->valueint > 6)) + { + database_transaction_rollback(&lock); + cJSON_Delete(json); + macro_free(macro); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "at least one action is missing a weekday"); + return; + } + + cJSON *json_action_schedule = cJSON_GetObjectItemCaseSensitive(json_action, "schedule"); + if(!cJSON_IsObject(json_action_schedule)) + { + database_transaction_rollback(&lock); + cJSON_Delete(json); + macro_free(macro); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "at least one action is missing a schedule"); + return; + } + cJSON *json_action_schedule_uid = cJSON_GetObjectItemCaseSensitive(json_action_schedule, "id"); + if(!cJSON_IsString(json_action_schedule_uid) || (json_action_schedule_uid->valuestring == NULL)) + { + database_transaction_rollback(&lock); + cJSON_Delete(json); + macro_free(macro); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "at least one action is missing a schedule id"); + return; + } + uuid_t action_schedule_uid; + if(schedule_uid_parse(json_action_schedule_uid->valuestring, action_schedule_uid)) + { + database_transaction_rollback(&lock); + cJSON_Delete(json); + macro_free(macro); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "at least one action has a bad schedule id"); + return; + } + + schedule_t *action_schedule = schedule_get_by_uid(action_schedule_uid); + if(action_schedule == NULL) + { + database_transaction_rollback(&lock); + cJSON_Delete(json); + macro_free(macro); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "at least one action schedule was not found"); + return; + } + + int action_schedule_id = action_schedule->id; + schedule_free(action_schedule); + + + cJSON *json_action_relay = cJSON_GetObjectItemCaseSensitive(json_action, "relay"); + if(!cJSON_IsObject(json_action_relay)) + { + database_transaction_rollback(&lock); + cJSON_Delete(json); + macro_free(macro); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "at least one action is missing a relay"); + return; + } + cJSON *json_action_relay_number = cJSON_GetObjectItemCaseSensitive(json_action_relay, "number"); + if(!cJSON_IsNumber(json_action_relay_number)) + { + database_transaction_rollback(&lock); + cJSON_Delete(json); + macro_free(macro); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "at least one action is missing a relay number"); + return; + } + cJSON *json_action_relay_controller_uid = cJSON_GetObjectItemCaseSensitive(json_action_relay, "controller_id"); + if(!cJSON_IsString(json_action_relay_controller_uid) || (json_action_relay_controller_uid->valuestring == NULL)) + { + database_transaction_rollback(&lock); + cJSON_Delete(json); + macro_free(macro); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "at least one action is missing a relay controller id"); + return; + } + uuid_t action_controller_uid; + if(uuid_parse(json_action_relay_controller_uid->valuestring, action_controller_uid)) + { + database_transaction_rollback(&lock); + cJSON_Delete(json); + macro_free(macro); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "at least one action has a bad relay controller id"); + return; + } + + controller_t *action_controller = controller_get_by_uid(action_controller_uid); + if(action_controller == NULL) + { + database_transaction_rollback(&lock); + cJSON_Delete(json); + macro_free(macro); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "at least one action relay controller was not found"); + return; + } + + int controller_id = action_controller->id; + int relay_num = json_action_relay_number->valueint; + + controller_free(action_controller); + + relay_t *action_relay = relay_get_for_controller(controller_id, relay_num); + if(action_relay == NULL) + { + database_transaction_rollback(&lock); + cJSON_Delete(json); + macro_free(macro); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "action relay was not found"); + return; + } + + int action_relay_id = action_relay->id; + relay_free(action_relay); + + + macro_action_t *action = malloc(sizeof(macro_action_t)); + action->macro_id = macro->id; + action->relay_id = action_relay_id; + action->schedule_id = action_schedule_id; + action->weekday = json_action_weekday->valueint; + + macro_action_insert(action); + free(action); + } + } + + database_transaction_commit(&lock); + + cJSON_Delete(json); + json = macro_to_json(macro); + + endpoint_response_json(response, 201, json); + + cJSON_Delete(json); + macro_free(macro); +} + +void +api_v1_macros_STR_DELETE(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response) +{ + (void)hm; + (void)nc; + + const char *target_uid_str = args[0].value.v_str; + + uuid_t target_uid; + if(uuid_parse(target_uid_str, target_uid)) + { + M_RESPONSE_400_NO_VALID_ID(response); + return; + } + + macro_t* macro = macro_get_by_uid(target_uid); + + if(!macro) + { + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 404, "no macro with id found"); + return; + } + + if(macro_remove(macro)) + { + M_RESPONSE_TEXT_STATIC(LOGGER_ERR, response, 500, "failed to remove macro from database"); + } + else + { + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 200, "deleted macro"); + } + macro_free(macro); + return; +} diff --git a/src/endpoints/api_v1_relays_tag_STR.c b/src/endpoints/api_v1_relays_tag_STR.c index 06a6adc..ffce429 100644 --- a/src/endpoints/api_v1_relays_tag_STR.c +++ b/src/endpoints/api_v1_relays_tag_STR.c @@ -16,17 +16,13 @@ api_v1_relays_tag_STR_GET(struct mg_connection *nc, struct http_message *hm, end int tag_id = tag_get_id(args[0].value.v_str); if(tag_id == 0) { - static const char content[] = "tag was not found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_404_NO_TAG_FOUND(response); return; } int *relays_ids = junction_tag_get_relays_for_tag_id(tag_id); if(relays_ids == NULL) { - LOGGER_ERR("failed to load relays for tag from database\n"); - - static const char content[] = "failed to load relays for tag from database"; - endpoint_response_text(response, 500, content, STRLEN(content)); + M_RESPONSE_500_FAILED_TO_READ_FROM_DATABASE(response); return; } diff --git a/src/endpoints/api_v1_schedules.c b/src/endpoints/api_v1_schedules.c index eda0f2e..7a9ad6e 100644 --- a/src/endpoints/api_v1_schedules.c +++ b/src/endpoints/api_v1_schedules.c @@ -16,30 +16,23 @@ api_v1_schedules_POST(struct mg_connection *nc, struct http_message *hm, endpoin if(json == NULL) { - static const char content[] = "no valid json was supplied"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_JSON(response); return; } cJSON *json_name = cJSON_GetObjectItemCaseSensitive(json, "name"); if(!cJSON_IsString(json_name) || (json_name->valuestring == NULL)) { - LOGGER_DEBUG("no name for schedule provided\n"); - cJSON_Delete(json); - - static const char content[] = "no name for schedule provided"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_NAME(response); return; } cJSON *json_periods = cJSON_GetObjectItemCaseSensitive(json, "periods"); if(!cJSON_IsArray(json_periods)) { - LOGGER_DEBUG("no periods for schedule provided\n"); cJSON_Delete(json); - static const char content[] = "no periods for schedule provided"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request does not contain periods"); return; } @@ -49,11 +42,9 @@ api_v1_schedules_POST(struct mg_connection *nc, struct http_message *hm, endpoin { if(!cJSON_IsString(json_tag) || (json_tag->valuestring == NULL)) { - LOGGER_DEBUG("invalid tag in tags\n"); cJSON_Delete(json); - static const char content[] = "invalid tag in tags"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains at least one invalid tag"); return; } } @@ -79,22 +70,18 @@ api_v1_schedules_POST(struct mg_connection *nc, struct http_message *hm, endpoin if(!cJSON_IsString(json_period_start) || (json_period_start->valuestring == NULL)) { - LOGGER_DEBUG("period is missing start\n"); cJSON_Delete(json); schedule_free(new_schedule); - static const char content[] = "one period is missing a start"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains at least one period without a start"); return; } if(!cJSON_IsString(json_period_end) || (json_period_end->valuestring == NULL)) { - LOGGER_DEBUG("period is missing end\n"); cJSON_Delete(json); schedule_free(new_schedule); - static const char content[] = "one period is missing an end"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains at least one period without an end"); return; } @@ -102,22 +89,18 @@ api_v1_schedules_POST(struct mg_connection *nc, struct http_message *hm, endpoin uint16_t end; if(period_helper_parse_hhmm(json_period_start->valuestring, &start)) { - LOGGER_DEBUG("couldn't parse start '%s'\n", json_period_start->valuestring); cJSON_Delete(json); schedule_free(new_schedule); - static const char content[] = "the start for one period is invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains at least one period with an invalid start"); return; } if(period_helper_parse_hhmm(json_period_end->valuestring, &end)) { - LOGGER_DEBUG("couldn't parse end '%s'\n", json_period_end->valuestring); cJSON_Delete(json); schedule_free(new_schedule); - static const char content[] = "the end for one period is invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains at least one period with an invalid end"); return; } diff --git a/src/endpoints/api_v1_schedules_STR.c b/src/endpoints/api_v1_schedules_STR.c index 26e8689..3abc0c8 100644 --- a/src/endpoints/api_v1_schedules_STR.c +++ b/src/endpoints/api_v1_schedules_STR.c @@ -19,10 +19,7 @@ api_v1_schedules_STR_GET(struct mg_connection *nc, struct http_message *hm, endp uuid_t target_uid; if(schedule_uid_parse(args[0].value.v_str, target_uid)) { - LOGGER_DEBUG("failed to unparse uid\n"); - - static const char content[] = "given id was invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_ID(response); return; } @@ -30,10 +27,7 @@ api_v1_schedules_STR_GET(struct mg_connection *nc, struct http_message *hm, endp if(!schedule) { - LOGGER_DEBUG("could not find a schedule for uid '%s'\n", args[0].value.v_str); - - static const char content[] = "no schedule for id found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_404_NO_SCHEDULE_FOUND_FOR_ID(response); return; } @@ -53,10 +47,7 @@ api_v1_schedules_STR_PUT(struct mg_connection *nc, struct http_message *hm, endp uuid_t target_uid; if(schedule_uid_parse(args[0].value.v_str, target_uid)) { - LOGGER_DEBUG("failed to unparse uid\n"); - - static const char content[] = "given id was invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_ID(response); return; } @@ -64,10 +55,7 @@ api_v1_schedules_STR_PUT(struct mg_connection *nc, struct http_message *hm, endp if(!schedule) { - LOGGER_DEBUG("could not find a schedule for uid '%s'\n", args[0].value.v_str); - - static const char content[] = "no schedule for id found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_404_NO_SCHEDULE_FOUND_FOR_ID(response); return; } @@ -75,8 +63,7 @@ api_v1_schedules_STR_PUT(struct mg_connection *nc, struct http_message *hm, endp if(json == NULL) { - static const char content[] = "no valid json was supplied"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_JSON(response); return; } @@ -137,12 +124,10 @@ api_v1_schedules_STR_PUT(struct mg_connection *nc, struct http_message *hm, endp if(schedule_save(schedule)) { - LOGGER_ERR("failed to save schedule\n"); free(schedule); cJSON_Delete(json); - static const char content[] = "failed to save schedule to database"; - endpoint_response_text(response, 500, content, STRLEN(content)); + M_RESPONSE_500_FAILED_TO_SAVE_TO_DATABASE(response); return; } @@ -190,10 +175,7 @@ api_v1_schedules_STR_DELETE(struct mg_connection *nc, struct http_message *hm, e uuid_t target_uid; if(schedule_uid_parse(target_uid_str, target_uid)) { - LOGGER_DEBUG("failed to unparse uid\n"); - - static const char content[] = "given id was invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_ID(response); return; } @@ -201,33 +183,25 @@ api_v1_schedules_STR_DELETE(struct mg_connection *nc, struct http_message *hm, e if(!schedule) { - LOGGER_DEBUG("could not find a schedule for uid '%s'\n", args[0].value.v_str); - - static const char content[] = "no schedule for id found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_404_NO_SCHEDULE_FOUND_FOR_ID(response); return; } if(schedule_is_protected(schedule)) { - static const char content[] = "target schedule is protected"; - endpoint_response_text(response, 403, content, STRLEN(content)); - schedule_free(schedule); + + M_RESPONSE_403_PROTECTED_SCHEDULE(response); return; } if(schedule_remove(schedule)) { - LOGGER_ERR("failed to remove schedule from database\n"); - - static const char content[] = "failed to remove schedule from database"; - endpoint_response_text(response, 500, content, STRLEN(content)); + M_RESPONSE_500_FAILED_TO_DELETE_FROM_DATABASE(response); } else { - static const char content[] = "deleted schedule"; - endpoint_response_text(response, 200, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 200, "the target schedule got deleted"); } schedule_free(schedule); return; diff --git a/src/endpoints/api_v1_schedules_list.c b/src/endpoints/api_v1_schedules_list.c index ede980b..46d2b8a 100644 --- a/src/endpoints/api_v1_schedules_list.c +++ b/src/endpoints/api_v1_schedules_list.c @@ -20,29 +20,23 @@ api_v1_schedules_list_POST(struct mg_connection *nc, struct http_message *hm, en { if(json == NULL) { - static const char content[] = "no valid json was supplied"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_JSON(response); return; } cJSON *json_name = cJSON_GetObjectItemCaseSensitive(json, "name"); if(!cJSON_IsString(json_name) || (json_name->valuestring == NULL)) { - LOGGER_DEBUG("no name for schedule provided\n"); - cJSON_Delete(json_list); - - static const char content[] = "no name for schedule provided"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request does not contain a name for at least one schedule"); return; } + cJSON *json_periods = cJSON_GetObjectItemCaseSensitive(json, "periods"); if(!cJSON_IsArray(json_periods)) { - LOGGER_DEBUG("no periods for schedule provided\n"); cJSON_Delete(json_list); - static const char content[] = "no periods for schedule provided"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request does not contain periods for at least one schedule"); return; } @@ -52,11 +46,9 @@ api_v1_schedules_list_POST(struct mg_connection *nc, struct http_message *hm, en { if(!cJSON_IsString(json_tag) || (json_tag->valuestring == NULL)) { - LOGGER_DEBUG("invalid tag in tags\n"); cJSON_Delete(json_list); - static const char content[] = "invalid tag in tags"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains at least one invalid tag"); return; } } @@ -82,22 +74,18 @@ api_v1_schedules_list_POST(struct mg_connection *nc, struct http_message *hm, en if(!cJSON_IsString(json_period_start) || (json_period_start->valuestring == NULL)) { - LOGGER_DEBUG("period is missing start\n"); cJSON_Delete(json_list); schedule_free(new_schedule); - static const char content[] = "one period is missing a start"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains at least one period without a start"); return; } if(!cJSON_IsString(json_period_end) || (json_period_end->valuestring == NULL)) { - LOGGER_DEBUG("period is missing end\n"); cJSON_Delete(json_list); schedule_free(new_schedule); - static const char content[] = "one period is missing an end"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains at least one period without an end"); return; } @@ -105,22 +93,18 @@ api_v1_schedules_list_POST(struct mg_connection *nc, struct http_message *hm, en uint16_t end; if(period_helper_parse_hhmm(json_period_start->valuestring, &start)) { - LOGGER_DEBUG("couldn't parse start '%s'\n", json_period_start->valuestring); cJSON_Delete(json_list); schedule_free(new_schedule); - static const char content[] = "the start for one period is invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains at least one period with an invalid start"); return; } if(period_helper_parse_hhmm(json_period_end->valuestring, &end)) { - LOGGER_DEBUG("couldn't parse end '%s'\n", json_period_end->valuestring); cJSON_Delete(json_list); schedule_free(new_schedule); - static const char content[] = "the end for one period is invalid"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains at least one period with an invalid end"); return; } diff --git a/src/endpoints/api_v1_schedules_tag_STR.c b/src/endpoints/api_v1_schedules_tag_STR.c index b0d22ec..08723dc 100644 --- a/src/endpoints/api_v1_schedules_tag_STR.c +++ b/src/endpoints/api_v1_schedules_tag_STR.c @@ -16,17 +16,13 @@ api_v1_schedules_tag_STR_GET(struct mg_connection *nc, struct http_message *hm, int tag_id = tag_get_id(args[0].value.v_str); if(tag_id == 0) { - static const char content[] = "tag was not found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_404_NO_TAG_FOUND(response); return; } int *schedules_ids = junction_tag_get_schedules_for_tag_id(tag_id); if(schedules_ids == NULL) { - LOGGER_ERR("failed to load schedules for tag from database\n"); - - static const char content[] = "failed to load schedules for tag from database"; - endpoint_response_text(response, 500, content, STRLEN(content)); + M_RESPONSE_500_FAILED_TO_READ_FROM_DATABASE(response); return; } diff --git a/src/endpoints/api_v1_tags.c b/src/endpoints/api_v1_tags.c index 26b08b6..928ec17 100644 --- a/src/endpoints/api_v1_tags.c +++ b/src/endpoints/api_v1_tags.c @@ -44,48 +44,38 @@ api_v1_tags_POST(struct mg_connection *nc, struct http_message *hm, endpoint_arg if(json == NULL) { - static const char content[] = "no valid json was supplied"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_400_NO_VALID_JSON(response); return; } cJSON *json_tag = cJSON_GetObjectItemCaseSensitive(json, "tag"); if(!cJSON_IsString(json_tag) || (json_tag->valuestring == NULL)) { - LOGGER_DEBUG("no tag provided\n"); cJSON_Delete(json); - static const char content[] = "no tag provided"; - endpoint_response_text(response, 400, content, STRLEN(content)); - return; - } - - if(tag_get_id(json_tag->valuestring)) - { - LOGGER_DEBUG("tag existed already\n"); - cJSON_Delete(json); - - static const char content[] = "tag existed already"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request does not contain a tag"); return; } if(strlen(json_tag->valuestring) == 0) { - LOGGER_DEBUG("tag is empty\n"); cJSON_Delete(json); - static const char content[] = "tag is empty"; - endpoint_response_text(response, 400, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the request contains an empty tag"); + return; + } + + if(tag_get_id(json_tag->valuestring)) + { + cJSON_Delete(json); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 400, "the tag does already exist"); return; } if(tag_save(0, json_tag->valuestring)) { - LOGGER_DEBUG("tag could not be saved\n"); - - static const char content[] = "tag could not be saved"; - endpoint_response_text(response, 500, content, STRLEN(content)); + M_RESPONSE_500_FAILED_TO_SAVE_TO_DATABASE(response); } else { diff --git a/src/endpoints/api_v1_tags_STR.c b/src/endpoints/api_v1_tags_STR.c index 6aca7f0..e0e7c55 100644 --- a/src/endpoints/api_v1_tags_STR.c +++ b/src/endpoints/api_v1_tags_STR.c @@ -16,26 +16,19 @@ api_v1_tags_STR_GET(struct mg_connection *nc, struct http_message *hm, endpoint_ int tag_id = tag_get_id(args[0].value.v_str); if(tag_id == 0) { - static const char content[] = "tag was not found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_404_NO_TAG_FOUND(response); return; } int *relays_ids = junction_tag_get_relays_for_tag_id(tag_id); if(relays_ids == NULL) { - LOGGER_ERR("failed to load relays for tag from database\n"); - - static const char content[] = "failed to load relays for tag from database"; - endpoint_response_text(response, 500, content, STRLEN(content)); + M_RESPONSE_500_FAILED_TO_READ_FROM_DATABASE(response); return; } int *schedules_ids = junction_tag_get_schedules_for_tag_id(tag_id); if(schedules_ids == NULL) { - LOGGER_ERR("failed to load schedules for tag from database\n"); - - static const char content[] = "failed to load schedules for tag from database"; - endpoint_response_text(response, 500, content, STRLEN(content)); + M_RESPONSE_500_FAILED_TO_READ_FROM_DATABASE(response); return; } @@ -91,21 +84,16 @@ api_v1_tags_STR_DELETE(struct mg_connection *nc, struct http_message *hm, endpoi int tag_id = tag_get_id(args[0].value.v_str); if(tag_id == 0) { - static const char content[] = "tag was not found"; - endpoint_response_text(response, 404, content, STRLEN(content)); + M_RESPONSE_404_NO_TAG_FOUND(response); return; } if(tag_remove(tag_id)) { - LOGGER_ERR("failed to remove tag from database\n"); - - static const char content[] = "failed to remove tag from database"; - endpoint_response_text(response, 500, content, STRLEN(content)); + M_RESPONSE_500_FAILED_TO_DELETE_FROM_DATABASE(response); } else { - static const char content[] = "deleted tag"; - endpoint_response_text(response, 200, content, STRLEN(content)); + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 200, "the tag got deleted"); } } diff --git a/src/handlers/http.c b/src/handlers/http.c index 87d2908..84c4a36 100644 --- a/src/handlers/http.c +++ b/src/handlers/http.c @@ -82,8 +82,8 @@ handle_http_request(struct mg_connection *nc, struct http_message *hm) endpoint_t *endpoint = router_find_endpoint(hm->uri.p, hm->uri.len, &hm->method); endpoint_response_t response; - static const char content[] = "the server did not create a response"; - endpoint_response_text(&response, 500, content, STRLEN(content)); + + M_RESPONSE_TEXT_STATIC(LOGGER_NONE, &response, 500, "server did not create a response"); if(!endpoint) { diff --git a/src/logger.c b/src/logger.c index 2869668..1839d38 100644 --- a/src/logger.c +++ b/src/logger.c @@ -17,7 +17,7 @@ const char *COLOR_EMERG = COLOR_MAGENTA; void logger_log(int level, const char *filename, int line, const char *func, const char *msg, ...) { - if(global_config.log_level < level) + if(global_config.log_level < level || level == LOG_NONE ) { return; } diff --git a/src/models/junction_relay_schedule.c b/src/models/junction_relay_schedule.c index 63f844c..f0854bf 100644 --- a/src/models/junction_relay_schedule.c +++ b/src/models/junction_relay_schedule.c @@ -40,14 +40,14 @@ junction_relay_schedule_insert_weekdays(int relay_id, int *schedule_ids) static const char query_base[] = "INSERT INTO junction_relay_schedule (weekday, schedule_id, relay_id) VALUES"; static const char query_extender[] = " (?, ?, ?)"; - size_t query_len = STRLEN(query_base) + (7 * (STRLEN(query_extender) + 1)) + 1; + size_t query_len = M_STRLEN(query_base) + (7 * (M_STRLEN(query_extender) + 1)) + 1; char *query = malloc(sizeof(char) * query_len + 1); strncpy(query, query_base, query_len); - query_len -= STRLEN(query_base); + query_len -= M_STRLEN(query_base); for(int i = 0; i < 7; ++i) { strncat(query, query_extender, query_len); - query_len -= STRLEN(query_extender); + query_len -= M_STRLEN(query_extender); char *query_divider = (i < 7 - 1) ? "," : ";"; strncat(query, query_divider, query_len); query_len -= 1; diff --git a/src/models/junction_tag.c b/src/models/junction_tag.c index e03a195..7d84af5 100644 --- a/src/models/junction_tag.c +++ b/src/models/junction_tag.c @@ -67,14 +67,14 @@ junction_tag_insert_list(int *tag_ids, int relay_id, int schedule_id, int count) static const char query_base[] = "INSERT INTO junction_tag(tag_id, schedule_id, relay_id) VALUES"; static const char query_extender[] = " (?, ?, ?)"; - size_t query_len = STRLEN(query_base) + (count * (STRLEN(query_extender) + 1)) + 1; + size_t query_len = M_STRLEN(query_base) + (count * (M_STRLEN(query_extender) + 1)) + 1; char *query = malloc(sizeof(char) * query_len + 1); strncpy(query, query_base, query_len); - query_len -= STRLEN(query_base); + query_len -= M_STRLEN(query_base); for(int i = 0; i < count; ++i) { strncat(query, query_extender, query_len); - query_len -= STRLEN(query_extender); + query_len -= M_STRLEN(query_extender); char *query_divider = (i < count - 1) ? "," : ";"; strncat(query, query_divider, query_len); query_len -= 1; diff --git a/src/models/macro.c b/src/models/macro.c index a40ed61..5bffdb3 100644 --- a/src/models/macro.c +++ b/src/models/macro.c @@ -143,7 +143,7 @@ int macro_remove(macro_t *macro) { sqlite3_stmt *stmt; - if(!macro->id) + if(macro->id == 0) { return 0; } @@ -155,6 +155,8 @@ macro_remove(macro_t *macro) sqlite3_finalize(stmt); + cache_invalidate_macro(macro->id); + return rc != SQLITE_DONE; } diff --git a/src/models/macro_action.c b/src/models/macro_action.c index c0333c5..eb07116 100644 --- a/src/models/macro_action.c +++ b/src/models/macro_action.c @@ -94,6 +94,23 @@ macro_action_insert(macro_action_t *macro_action) return rc != SQLITE_DONE; } +int +macro_action_delete_for_macro(int macro_id) +{ + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "DELETE FROM macro_actions WHERE macro_id=?1;", -1, &stmt, NULL); + sqlite3_bind_int(stmt, 1, macro_id); + + int rc = sqlite3_step(stmt); + + sqlite3_finalize(stmt); + + cache_invalidate_macro(macro_id); + + return rc != SQLITE_DONE; +} + macro_action_t** macro_action_get_for_macro(int macro_id) { diff --git a/src/router.c b/src/router.c index b4b0387..23ef95d 100644 --- a/src/router.c +++ b/src/router.c @@ -93,8 +93,9 @@ router_init() router_register_endpoint("/api/v1/macros/", HTTP_METHOD_GET, api_v1_macros_GET); router_register_endpoint("/api/v1/macros/", HTTP_METHOD_POST, api_v1_macros_POST); - //router_register_endpoint("/api/v1/macros/{str}", HTTP_METHOD_GET, api_v1_macros_STR_GET); - //router_register_endpoint("/api/v1/macros/{str}", HTTP_METHOD_DELETE, api_v1_macros_STR_DELETE); + router_register_endpoint("/api/v1/macros/{str}", HTTP_METHOD_GET, api_v1_macros_STR_GET); + router_register_endpoint("/api/v1/macros/{str}", HTTP_METHOD_PUT, api_v1_macros_STR_PUT); + router_register_endpoint("/api/v1/macros/{str}", HTTP_METHOD_DELETE, api_v1_macros_STR_DELETE); router_register_endpoint("/api/v1/ws/relays", HTTP_METHOD_WEBSOCKET, api_v1_ws_relays); } From d3fd48b35a4587ce4382c4a824ff3bd018f38ac2 Mon Sep 17 00:00:00 2001 From: Tobias Reisinger <tobias@msrg.cc> Date: Sun, 6 Sep 2020 13:12:33 +0200 Subject: [PATCH 8/9] add: macro endpoint for execution --- include/endpoints/api_v1_macros.h | 3 ++ include/models/macro.h | 4 +- include/models/macro_action.h | 3 ++ src/endpoints/api_v1_macros_STR.c | 4 +- src/endpoints/api_v1_macros_STR_execute.c | 64 +++++++++++++++++++++++ src/models/junction_relay_schedule.c | 2 +- src/models/macro.c | 33 ++++-------- src/models/macro_action.c | 22 ++++++++ src/router.c | 1 + 9 files changed, 110 insertions(+), 26 deletions(-) create mode 100644 src/endpoints/api_v1_macros_STR_execute.c diff --git a/include/endpoints/api_v1_macros.h b/include/endpoints/api_v1_macros.h index 2809c69..9a79271 100644 --- a/include/endpoints/api_v1_macros.h +++ b/include/endpoints/api_v1_macros.h @@ -18,4 +18,7 @@ api_v1_macros_STR_PUT(struct mg_connection *nc, struct http_message *hm, endpoin void api_v1_macros_STR_DELETE(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response); +void +api_v1_macros_STR_execute_PUT(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response); + #endif /* CORE_ENDPOINTS_API_V1_MACROS_H */ diff --git a/include/models/macro.h b/include/models/macro.h index 0ceb1ca..d532902 100644 --- a/include/models/macro.h +++ b/include/models/macro.h @@ -6,7 +6,6 @@ #include <cJSON.h> #include <constants.h> -#include <models/period.h> #include <models/macro_action.h> typedef struct @@ -43,4 +42,7 @@ macro_get_by_uid(uuid_t uid); macro_t** macro_get_all(); +int* +macro_get_target_relay_ids(int macro_id); + #endif /* CORE_MACRO_H */ diff --git a/include/models/macro_action.h b/include/models/macro_action.h index 22ddd63..bd61d09 100644 --- a/include/models/macro_action.h +++ b/include/models/macro_action.h @@ -18,6 +18,9 @@ macro_action_delete_for_macro(int macro_id); macro_action_t** macro_action_get_for_macro(int macro_id); +int +macro_action_execute(macro_action_t *macro_action); + void macro_action_free_list(macro_action_t **macro_actions); diff --git a/src/endpoints/api_v1_macros_STR.c b/src/endpoints/api_v1_macros_STR.c index e2d228f..44a5e18 100644 --- a/src/endpoints/api_v1_macros_STR.c +++ b/src/endpoints/api_v1_macros_STR.c @@ -86,11 +86,11 @@ api_v1_macros_STR_PUT(struct mg_connection *nc, struct http_message *hm, endpoin } } + macro_action_delete_for_macro(macro->id); + cJSON *json_actions = cJSON_GetObjectItemCaseSensitive(json, "actions"); if(cJSON_IsArray(json_actions)) { - macro_action_delete_for_macro(macro->id); - cJSON *json_action; cJSON_ArrayForEach(json_action, json_actions) { diff --git a/src/endpoints/api_v1_macros_STR_execute.c b/src/endpoints/api_v1_macros_STR_execute.c new file mode 100644 index 0000000..33f3952 --- /dev/null +++ b/src/endpoints/api_v1_macros_STR_execute.c @@ -0,0 +1,64 @@ +#include <cJSON.h> +#include <macros.h> +#include <constants.h> +#include <endpoints/api_v1_macros.h> +#include <logger.h> +#include <command.h> +#include <models/macro_action.h> +#include <models/macro.h> +#include <models/relay.h> +#include <models/tag.h> + +void +api_v1_macros_STR_execute_PUT(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response) +{ + (void)hm; + (void)nc; + + uuid_t target_uid; + if(uuid_parse(args[0].value.v_str, target_uid)) + { + M_RESPONSE_400_NO_VALID_ID(response); + return; + } + + macro_t* macro = macro_get_by_uid(target_uid); + + if(!macro) + { + M_RESPONSE_404_NO_MACRO_FOUND_FOR_ID(response); + return; + } + + macro_action_t** macro_actions = macro_action_get_for_macro(macro->id); + + database_transaction_lock lock; + database_transaction_begin(&lock); + + for(int i = 0; macro_actions[i] != NULL; ++i) + { + macro_action_execute(macro_actions[i]); + } + + database_transaction_commit(&lock); + + int *target_relay_ids = macro_get_target_relay_ids(macro->id); + for(int i = 0; target_relay_ids[i] != 0; ++i) + { + relay_t *target_relay = relay_get_by_id(target_relay_ids[i]); + if(!target_relay) + { + LOGGER_ERR("failed to load target relay from database\n"); + continue; + } + command_relay_schedules_set(target_relay); + + relay_free(target_relay); + } + + free(target_relay_ids); + macro_action_free_list(macro_actions); + macro_free(macro); + + M_RESPONSE_TEXT_STATIC(LOGGER_DEBUG, response, 200, "macro got executed"); +} diff --git a/src/models/junction_relay_schedule.c b/src/models/junction_relay_schedule.c index f0854bf..50bedb7 100644 --- a/src/models/junction_relay_schedule.c +++ b/src/models/junction_relay_schedule.c @@ -95,7 +95,7 @@ junction_relay_schedule_get_relay_ids_with_schedule(int schedule_id) { sqlite3_stmt *stmt; - sqlite3_prepare_v2(global_database, "SELECT relay_id FROM junction_relay_schedule WHERE schedule_id=?1;", -1, &stmt, NULL); + sqlite3_prepare_v2(global_database, "SELECT DISTINCT relay_id FROM junction_relay_schedule WHERE schedule_id=?1;", -1, &stmt, NULL); sqlite3_bind_int(stmt, 1, schedule_id); return database_helper_get_ids(stmt); diff --git a/src/models/macro.c b/src/models/macro.c index 5bffdb3..0d19075 100644 --- a/src/models/macro.c +++ b/src/models/macro.c @@ -160,28 +160,6 @@ macro_remove(macro_t *macro) return rc != SQLITE_DONE; } -int -macro_is_protected(macro_t *macro) -{ - uuid_t tmp_uuid; - - memset(tmp_uuid, 0, sizeof(uuid_t)); - memcpy(tmp_uuid, "off", 3); - if(uuid_compare(macro->uid, tmp_uuid) == 0) - { - return 1; - } - - memset(tmp_uuid, 0, sizeof(uuid_t)); - memcpy(tmp_uuid, "on", 2); - if(uuid_compare(macro->uid, tmp_uuid) == 0) - { - return 1; - } - - return 0; -} - void macro_free(macro_t *macro) { @@ -339,3 +317,14 @@ macro_get_all() return macro_db_select(stmt); } + +int* +macro_get_target_relay_ids(int macro_id) +{ + sqlite3_stmt *stmt; + + sqlite3_prepare_v2(global_database, "SELECT DISTINCT relay_id FROM macro_actions WHERE macro_id=?1;", -1, &stmt, NULL); + sqlite3_bind_int(stmt, 1, macro_id); + + return database_helper_get_ids(stmt); +} diff --git a/src/models/macro_action.c b/src/models/macro_action.c index eb07116..97cbfc6 100644 --- a/src/models/macro_action.c +++ b/src/models/macro_action.c @@ -123,6 +123,28 @@ macro_action_get_for_macro(int macro_id) return macro_action_db_select(stmt); } +int +macro_action_execute(macro_action_t *macro_action) +{ + schedule_t *schedule = schedule_get_by_id(macro_action->schedule_id); + if(!schedule) + { + return 1; + } + + relay_t *relay = relay_get_by_id(macro_action->relay_id); + if(!relay) + { + free(schedule); + return 1; + } + + schedule_free(relay->schedules[macro_action->weekday]); + relay->schedules[macro_action->weekday] = schedule; + + return relay_save(relay); +} + void macro_action_free_list(macro_action_t **macro_actions) { diff --git a/src/router.c b/src/router.c index 23ef95d..13b8299 100644 --- a/src/router.c +++ b/src/router.c @@ -96,6 +96,7 @@ router_init() router_register_endpoint("/api/v1/macros/{str}", HTTP_METHOD_GET, api_v1_macros_STR_GET); router_register_endpoint("/api/v1/macros/{str}", HTTP_METHOD_PUT, api_v1_macros_STR_PUT); router_register_endpoint("/api/v1/macros/{str}", HTTP_METHOD_DELETE, api_v1_macros_STR_DELETE); + router_register_endpoint("/api/v1/macros/{str}/execute", HTTP_METHOD_PUT, api_v1_macros_STR_execute_PUT); router_register_endpoint("/api/v1/ws/relays", HTTP_METHOD_WEBSOCKET, api_v1_ws_relays); } From 4b39631765a5320982132f3fd720a248a84f5464 Mon Sep 17 00:00:00 2001 From: Tobias Reisinger <tobias@msrg.cc> Date: Sun, 6 Sep 2020 13:14:06 +0200 Subject: [PATCH 9/9] add: bump version --- .drone.yml | 6 ------ CMakeLists.txt | 2 +- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/.drone.yml b/.drone.yml index 3394189..e0ed31a 100644 --- a/.drone.yml +++ b/.drone.yml @@ -47,12 +47,6 @@ steps: - cmake .. - make test -- name: show-log-valgrind - image: bash - pull: always - commands: - - cat tests/testing_latest/valgrind.log - - name: gitea_release image: plugins/gitea-release settings: diff --git a/CMakeLists.txt b/CMakeLists.txt index 532a906..8a34ecd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required (VERSION 3.7) project(core - VERSION 0.3.4 + VERSION 0.3.5 LANGUAGES C) add_executable(core src/main.c)