Add some subscription (a.k.a. "follow") functionality
[blerg.git] / http / http_blerg.c
index 025fbb0..a6d3a5f 100644 (file)
@@ -28,6 +28,12 @@ struct put_state {
        int data_size;
 };
 
+struct subscribe_state {
+       struct MHD_PostProcessor *pp;
+       char username[33];
+       char to[33];
+};
+
 struct get_state {
        struct blerg *b;
        yajl_gen g;
@@ -209,6 +215,22 @@ int POST_put_iterator(void *cls, enum MHD_ValueKind kind, const char *key, const
        return MHD_YES;
 }
 
+int POST_subscribe_iterator(void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) {
+       struct subscribe_state *ss = cls;
+
+       if (strncmp(key, "username", 9) == 0) {
+               if (size > 32) size = 32;
+               memcpy(ss->username, data, size);
+               ss->username[size] = 0;
+       } else if (strncmp(key, "to", 3) == 0) {
+               if (size > 32) size = 32;
+               memcpy(ss->to, data, size);
+               ss->to[size] = 0;
+       }
+
+       return MHD_YES;
+}
+
 struct MHD_Response *create_response_for_range(struct blerg *b, uint64_t from, uint64_t to) {
        struct MHD_Response *response;
        struct get_state *gs = malloc(sizeof(struct get_state));
@@ -535,6 +557,33 @@ ahc_derp (void *cls, struct MHD_Connection *connection, const char *url, const c
                } else {
                        return respond_JSON_Failure(connection);
                }
+       } else if (strncmp(url, "/subscribe", 11) == 0) {
+               struct subscribe_state *ss = (struct subscribe_state *) *ptr;
+
+               if (ss == NULL) {
+                       if (strcmp(method, MHD_HTTP_METHOD_POST) != 0)
+                               return respond_405(connection);
+
+                       struct subscribe_state *ss = malloc(sizeof(struct subscribe_state));
+                       ss->username[0] = ss->to[0] = 0;
+                       ss->pp = MHD_create_post_processor(connection, 1024, &POST_subscribe_iterator, ss);
+                       *ptr = ss;
+                       return MHD_YES;
+               }
+
+               if (*upload_data_size) {
+                       MHD_post_process(ss->pp, upload_data, *upload_data_size);
+                       *upload_data_size = 0;
+                       return MHD_YES;
+               }
+
+               const char *given_token = MHD_lookup_connection_value(connection, MHD_COOKIE_KIND, "auth");
+               if (auth_check_token(ss->username, given_token)) {
+                       subscription_add(ss->username, ss->to);
+                       return respond_JSON_Success(connection);
+               } else {
+                       return respond_JSON_Failure(connection);
+               }
        } else {
                return respond_404(connection);
        }