summaryrefslogtreecommitdiffstats
path: root/assets
diff options
context:
space:
mode:
Diffstat (limited to 'assets')
-rw-r--r--assets/js/subscribe_widget.js78
1 files changed, 78 insertions, 0 deletions
diff --git a/assets/js/subscribe_widget.js b/assets/js/subscribe_widget.js
new file mode 100644
index 00000000..64e3e55f
--- /dev/null
+++ b/assets/js/subscribe_widget.js
@@ -0,0 +1,78 @@
+var subscribe_button = document.getElementById('subscribe');
+subscribe_button.parentNode['action'] = 'javascript:void(0)';
+
+if (subscribe_button.getAttribute('data-type') === 'subscribe') {
+ subscribe_button.onclick = subscribe;
+} else {
+ subscribe_button.onclick = unsubscribe;
+}
+
+function subscribe(timeouts = 0) {
+ if (timeouts > 10) {
+ console.log('Failed to subscribe.');
+ return;
+ }
+
+ var url = '/subscription_ajax?action_create_subscription_to_channel=1&redirect=false' +
+ '&c=' + subscribe_data.ucid +
+ '&referer=' + location.pathname + location.search;
+ var xhr = new XMLHttpRequest();
+ xhr.responseType = 'json';
+ xhr.timeout = 20000;
+ xhr.open('POST', url, true);
+ xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+ xhr.send('csrf_token=' + subscribe_data.csrf_token);
+
+ var fallback = subscribe_button.innerHTML;
+ subscribe_button.onclick = unsubscribe;
+ subscribe_button.innerHTML = '<b>' + subscribe_data.unsubscribe_text + ' | ' + subscribe_data.sub_count_text + '</b>';
+
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState == 4) {
+ if (xhr.status != 200) {
+ subscribe_button.onclick = subscribe;
+ subscribe_button.innerHTML = fallback;
+ }
+ }
+ }
+
+ xhr.ontimeout = function () {
+ console.log('Subscribing timed out.');
+ subscribe(timeouts + 1);
+ };
+}
+
+function unsubscribe(timeouts = 0) {
+ if (timeouts > 10) {
+ console.log('Failed to subscribe');
+ return;
+ }
+
+ var url = '/subscription_ajax?action_remove_subscriptions=1&redirect=false' +
+ '&c=' + subscribe_data.ucid +
+ '&referer=' + location.pathname + location.search;
+ var xhr = new XMLHttpRequest();
+ xhr.responseType = 'json';
+ xhr.timeout = 20000;
+ xhr.open('POST', url, true);
+ xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
+ xhr.send('csrf_token=' + subscribe_data.csrf_token);
+
+ var fallback = subscribe_button.innerHTML;
+ subscribe_button.onclick = subscribe;
+ subscribe_button.innerHTML = '<b>' + subscribe_data.subscribe_text + ' | ' + subscribe_data.sub_count_text + '</b>';
+
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState == 4) {
+ if (xhr.status != 200) {
+ subscribe_button.onclick = unsubscribe;
+ subscribe_button.innerHTML = fallback;
+ }
+ }
+ }
+
+ xhr.ontimeout = function () {
+ console.log('Unsubscribing timed out.');
+ unsubscribe(timeouts + 1);
+ };
+}