sad

simple audio daemon
git clone git@git.2f30.org/sad.git
Log | Files | Refs | LICENSE

notify.c (1853B)


      1 #include <sys/select.h>
      2 
      3 #include <err.h>
      4 #include <limits.h>
      5 #include <stdio.h>
      6 #include <stdlib.h>
      7 #include <string.h>
      8 
      9 #include "queue.h"
     10 #include "sad.h"
     11 
     12 Eventdesc Eventmap[] = {
     13 	{ EVSONGFINISHED, "songfinished" },
     14 };
     15 
     16 struct subscriber {
     17 	int clifd;
     18 	int event;
     19 	TAILQ_ENTRY(subscriber) entry;
     20 };
     21 
     22 static TAILQ_HEAD(subscribers, subscriber) subscribers;
     23 
     24 int
     25 initnotifier(void)
     26 {
     27 	TAILQ_INIT(&subscribers);
     28 	return 0;
     29 }
     30 
     31 int
     32 addsubscriber(int clifd, int event)
     33 {
     34 	struct subscriber *s;
     35 	size_t i;
     36 
     37 	for (i = 0; i < LEN(Eventmap); i++)
     38 		if (Eventmap[i].event == event)
     39 			break;
     40 	if (i == LEN(Eventmap))
     41 		return -1;
     42 
     43 	TAILQ_FOREACH(s, &subscribers, entry)
     44 		if (s->clifd == clifd &&
     45 		    s->event == event)
     46 			return 0; /* do not queue events */
     47 
     48 	s = malloc(sizeof(*s));
     49 	if (!s)
     50 		err(1, "malloc");
     51 
     52 	s->clifd = clifd;
     53 	s->event = event;
     54 	TAILQ_INSERT_TAIL(&subscribers, s, entry);
     55 
     56 	return 0;
     57 }
     58 
     59 int
     60 addsubscribername(int clifd, const char *name)
     61 {
     62 	size_t i;
     63 
     64 	for (i = 0; i < LEN(Eventmap); i++)
     65 		if (!strcmp(Eventmap[i].name, name))
     66 			return addsubscriber(clifd, Eventmap[i].event);
     67 	return -1;
     68 }
     69 
     70 int
     71 notify(int event)
     72 {
     73 	struct subscriber *s, *tmp;
     74 	size_t i;
     75 
     76 	for (i = 0; i < LEN(Eventmap); i++)
     77 		if (Eventmap[i].event == event)
     78 			break;
     79 	if (i == LEN(Eventmap))
     80 		return -1;
     81 
     82 	TAILQ_FOREACH_SAFE(s, &subscribers, entry, tmp) {
     83 		if (s->event != event)
     84 			continue;
     85 		for (i = 0; i < LEN(Eventmap); i++) {
     86 			if (Eventmap[i].event == s->event) {
     87 				dprintf(s->clifd, "event: %s\n", Eventmap[i].name);
     88 				dprintf(s->clifd, "OK\n");
     89 				TAILQ_REMOVE(&subscribers, s, entry);
     90 				free(s);
     91 				break;
     92 			}
     93 		}
     94 	}
     95 	return 0;
     96 }
     97 
     98 void
     99 removesubscriber(int clifd)
    100 {
    101 	struct subscriber *s, *tmp;
    102 
    103 	TAILQ_FOREACH_SAFE(s, &subscribers, entry, tmp) {
    104 		if (s->clifd == clifd) {
    105 			TAILQ_REMOVE(&subscribers, s, entry);
    106 			free(s);
    107 		}
    108 	}
    109 }