summaryrefslogtreecommitdiff
path: root/search.c
blob: b1a36a0dc0af8058c9a411a108e6fe9255515a06 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#ifdef DEBUG
#ifdef __ANDROID__
#include <android/log.h>
#else
#include <stdio.h>
#endif
#endif
#include <stdlib.h>
#include <string.h>
#include "request.h"
#include "rtclient.h"
#include "rtclient/ticket.h"
#include "rtclient/search.h"

static void handle_search(rtclient_response *response)
{
	char data[response->numBytes];
	strcpy(data, response->data);
	char lines[response->numBytes];
	strcpy(lines, response->data);

	char *line = strtok(data, "\n");
	if (strstr(line, "200 Ok")) {
		line = strtok(NULL, "\n");
		size_t length = 0;
		do {
			length++;
			if (!strcmp(line, "No matching results."))
				return;
		} while ((line = strtok(NULL, "\n")));

		struct rtclient_ticket **list
			= malloc(sizeof(struct rtclient_ticket) * (length + 1));

		char *linesaveptr = NULL;
		line = strtok_r(lines, "\n", &linesaveptr);
		line = strtok_r(NULL, "\n", &linesaveptr);
		for (size_t i = 0; i < length; i++) {
			list[i] = malloc(sizeof(struct rtclient_ticket));
			struct rtclient_ticket *ticket = list[i];

			char *tokensaveptr = NULL;
			char *token = strtok_r(line, ":", &tokensaveptr);
			ticket->id = atoi(token);

			token = strtok_r(NULL, ":", &tokensaveptr);
			ticket->subject = malloc(strlen(token));
			strcpy(ticket->subject, ++token);

			line = strtok_r(NULL, "\n", &linesaveptr);
		}
		list[length] = NULL;
		((void (*)(struct rtclient_ticket **))response->userData)(list);
	} else {
#ifdef DEBUG
#ifdef __ANDROID__
		__android_log_print(ANDROID_LOG_INFO, "librtclient",
				"%s response status:\n%s", __func__, line);
#else
		printf("%s response status:\n%s\n", __func__, line);
#endif
#endif
	}
	rtclient_free_response(response);
}

void rtclient_search_ticket(const char *query,
		void (*callback)(struct rtclient_ticket **))
{
	request(handle_search, (void (*)(void *))callback, NULL,
			"%s%s", "REST/1.0/search/ticket?query=", query);
}