Skip to content
This repository was archived by the owner on Mar 18, 2025. It is now read-only.

Commit e1529e8

Browse files
committed
JSON message generation slightly less ugly.
1 parent 9a20f5b commit e1529e8

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

libsignald.c

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,16 @@ signald_read_cb(gpointer data, gint source, PurpleInputCondition cond)
179179
}
180180
}
181181

182+
gchar *
183+
append_newline(gchar *str)
184+
{
185+
int desired_length = strlen(str)+2;
186+
char *strn = g_malloc0(desired_length);
187+
strcpy(strn, str);
188+
strn[desired_length-2] = '\n';
189+
return strn;
190+
}
191+
182192
void
183193
signald_login(PurpleAccount *account)
184194
{
@@ -224,11 +234,16 @@ signald_login(PurpleAccount *account)
224234
sa->watcher = purple_input_add(fd, PURPLE_INPUT_READ, signald_read_cb, sa);
225235

226236
// subscribe to the configured number
227-
char subscribe_msg[128];
228-
// TODO: build json properly
229-
sprintf(subscribe_msg, "{\"type\": \"subscribe\", \"username\": \"%s\"}\n", purple_account_get_username(account));
230-
int l = strlen(subscribe_msg);
231-
int w = write(fd, subscribe_msg, l);
237+
JsonObject *data = json_object_new();
238+
json_object_set_string_member(data, "type", "subscribe");
239+
json_object_set_string_member(data, "username", purple_account_get_username(account));
240+
// TODO: create a "write json" helper function
241+
char *json = json_object_to_string(data);
242+
char *jsonn = append_newline(json);
243+
g_free(json);
244+
int l = strlen(jsonn);
245+
int w = write(fd, jsonn, l);
246+
g_free(jsonn);
232247
if (w != l) {
233248
purple_connection_set_state(pc, PURPLE_DISCONNECTED);
234249
purple_debug_info("signald", "wrote %d, wanted %d, error is %s\n",w,l,strerror(errno));
@@ -285,17 +300,13 @@ signald_send_im(PurpleConnection *pc,
285300
json_object_set_string_member(data, "recipientNumber", who);
286301
json_object_set_string_member(data, "messageBody", message);
287302
char *json = json_object_to_string(data);
288-
// append a newline
289-
int l = strlen(json)+2;
290-
char *jsonn = malloc(l);
291-
strcpy(jsonn, json);
292-
jsonn[l-2] = '\n';
293-
jsonn[l-1] = 0;
303+
char *jsonn = append_newline(json);
304+
g_free(json);
294305
//purple_debug_info("signald", "Sending:%s", jsonn);
295306
// send json message
307+
int l = strlen(jsonn);
296308
int w = write(sa->fd, jsonn, l);
297-
free(jsonn);
298-
g_free(json);
309+
g_free(jsonn);
299310
json_object_unref(data);
300311
if (w != l) {
301312
purple_debug_info("signald", "wrote %d, wanted %d, error is %s\n",w,l,strerror(errno));

0 commit comments

Comments
 (0)