]> git.armaanb.net Git - chorizo.git/blob - we_adblock.c
we_adblock: No need for static here, either
[chorizo.git] / we_adblock.c
1 #include <stdio.h>
2
3 #include <glib.h>
4 #include <webkit2/webkit-web-extension.h>
5
6
7 GSList *adblock_patterns = NULL;
8
9
10 void
11 adblock_load(void)
12 {
13     GRegex *re = NULL;
14     GError *err = NULL;
15     GIOChannel *channel = NULL;
16     gchar *path = NULL, *buf = NULL;
17
18     path = g_build_filename(g_get_user_config_dir(), __NAME__, "adblock.black",
19                             NULL);
20     channel = g_io_channel_new_file(path, "r", &err);
21     if (channel != NULL)
22     {
23         while (g_io_channel_read_line(channel, &buf, NULL, NULL, NULL)
24                == G_IO_STATUS_NORMAL)
25         {
26             g_strstrip(buf);
27             if (buf[0] != '#')
28             {
29                 re = g_regex_new(buf,
30                                  G_REGEX_CASELESS | G_REGEX_OPTIMIZE,
31                                  G_REGEX_MATCH_PARTIAL, &err);
32                 if (err != NULL)
33                 {
34                     fprintf(stderr, __NAME__": Could not compile regex: %s\n", buf);
35                     g_error_free(err);
36                     err = NULL;
37                 }
38                 else
39                     adblock_patterns = g_slist_append(adblock_patterns, re);
40             }
41             g_free(buf);
42         }
43         g_io_channel_shutdown(channel, FALSE, NULL);
44     }
45     g_free(path);
46 }
47
48 gboolean
49 web_page_send_request(WebKitWebPage *web_page, WebKitURIRequest *request,
50                       WebKitURIResponse *redirected_response, gpointer user_data)
51 {
52     GSList *it = adblock_patterns;
53     const gchar *uri;
54
55     uri = webkit_uri_request_get_uri(request);
56
57     while (it)
58     {
59         if (g_regex_match((GRegex *)(it->data), uri, 0, NULL))
60             return TRUE;
61         it = g_slist_next(it);
62     }
63
64     return FALSE;
65 }
66
67 void
68 web_page_created_callback(WebKitWebExtension *extension, WebKitWebPage *web_page,
69                           gpointer user_data)
70 {
71     g_signal_connect_object(web_page, "send-request",
72                             G_CALLBACK(web_page_send_request), NULL, 0);
73 }
74
75 G_MODULE_EXPORT void
76 webkit_web_extension_initialize(WebKitWebExtension *extension)
77 {
78     adblock_load();
79     g_signal_connect(extension, "page-created",
80                      G_CALLBACK(web_page_created_callback), NULL);
81 }