Statistics
| Branch: | Tag: | Revision:

root / templates / poller.js @ 049a5a10

History | View | Annotate | Download (4.9 kB)

1
// Copyright 2009 FriendFeed
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License"); you may
4
// not use this file except in compliance with the License. You may obtain
5
// a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
// License for the specific language governing permissions and limitations
13
// under the License.
14

    
15
$(document).ready(function() {
16
    if (!window.console) window.console = {};
17
    if (!window.console.log) window.console.log = function() {};
18

    
19
    $("#messageform").live("submit", function() {
20
        newMessage($(this));
21
        return false;
22
    });
23
    $("#messageform").live("keypress", function(e) {
24
        if (e.keyCode == 13) {
25
            newMessage($(this));
26
            return false;
27
        }
28
    });
29
    $("#message").select();
30
    updater.start();
31
    updater.poll();
32
});
33

    
34
function newMessage(form) {
35
    var message = form.formToDict();
36
    var disabled = form.find("input[type=submit]");
37
    disabled.disable();
38
    $.postJSON("{% url fetch-new %}", message, function(response) {
39
        updater.showMessage(response);
40
        if (message.id) {
41
            form.parent().remove();
42
        } else {
43
            form.find("input[type=text]").val("").select();
44
            disabled.enable();
45
        }
46
    });
47
}
48

    
49
function getCookie(name) {
50
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
51
    return r ? r[1] : undefined;
52
}
53

    
54
jQuery.postJSON = function(url, args, callback) {
55
    args._xsrf = getCookie("_xsrf");
56
    $.ajax({url: url, data: $.param(args), dataType: "text", type: "POST",
57
            success: function(response) {
58
        if (callback) callback(eval("(" + response + ")"));
59
    }, error: function(response) {
60
        console.log("ERROR:", response)
61
    }});
62
};
63

    
64
jQuery.fn.formToDict = function() {
65
    var fields = this.serializeArray();
66
    var json = {}
67
    for (var i = 0; i < fields.length; i++) {
68
        json[fields[i].name] = fields[i].value;
69
    }
70
    if (json.next) delete json.next;
71
    return json;
72
};
73

    
74
jQuery.fn.disable = function() {
75
    this.enable(false);
76
    return this;
77
};
78

    
79
jQuery.fn.enable = function(opt_enable) {
80
    if (arguments.length && !opt_enable) {
81
        this.attr("disabled", "disabled");
82
    } else {
83
        this.removeAttr("disabled");
84
    }
85
    return this;
86
};
87

    
88
var updater = {
89
    errorSleepTime: 500,
90
    cursor: null,
91
    
92
    start: function() {
93
            var args = {"_xsrf": getCookie("_xsrf")};
94
            if (updater.cursor) args.cursor = updater.cursor;
95
            $.ajax({url: "{% url fetch-existing %}", type: "POST", dataType: "text",
96
                    data: $.param(args), success: updater.onFetchExisting,
97
                    error: updater.onError});
98
        },
99
    
100
    poll: function() {
101
        var args = {"_xsrf": getCookie("_xsrf")};
102
        if (updater.cursor) args.cursor = updater.cursor;
103
        $.ajax({url: "{% url fetch-updates %}", type: "POST", dataType: "text",
104
                data: $.param(args), success: updater.onSuccess,
105
                error: updater.onError});
106
    },
107

    
108
    onSuccess: function(response) {
109
        try {
110
            updater.newMessages(eval("(" + response + ")"));
111
        } catch (e) {
112
            updater.onError();
113
            return;
114
        }
115
        updater.errorSleepTime = 500;
116
        window.setTimeout(updater.poll, 0);
117
    },
118

    
119
    onFetchExisting: function(response) {
120
            try {
121
                updater.existingMessages(eval("(" + response + ")"));
122
            } catch (e) {
123
//                updater.onError();
124
                return;
125
            }
126
        },
127
     
128
    onError: function(response) {
129
        updater.errorSleepTime *= 2;
130
        console.log("Poll error; sleeping for", updater.errorSleepTime, "ms");
131
        window.setTimeout(updater.poll, updater.errorSleepTime);
132
    },
133

    
134
    newMessages: function(response) {
135
        if (!response.messages) return;
136
        updater.cursor = response.cursor;
137
        var messages = response.messages;
138
        updater.cursor = messages[messages.length - 1].id;
139
//        console.log(messages.length, "new messages, cursor:", updater.cursor);
140
        
141
        for (var i = 0; i < messages.length; i++) {
142
            updater.showMessage(messages[i]);
143
        }
144
        $("#hid_mid").val('UPDATED');
145
        if (($('#console').dialog('isOpen')) == false){
146
                blink("#consolebutton");
147
                window.setTimeout('location.reload()', 3000);
148
        }
149
    },
150

    
151
    existingMessages: function(response) {
152
            if (!response.messages) return;
153
            updater.cursor = response.cursor;
154
            var messages = response.messages;
155
            updater.cursor = messages[messages.length - 1].id;
156
            for (var i = 0; i < messages.length; i++) {
157
                updater.showMessage(messages[i]);
158
            }
159
        },
160
   
161
    showMessage: function(message) {
162
        var existing = $("#m" + message.id);
163
        if (existing.length > 0) return;
164
        var node = $(message.html);
165
        node.hide();
166
//         $('#inbox').val($('#inbox').val()+message.text); 
167
        $("#inbox").append(node);
168
        node.slideDown();
169
    }
170
};
171

    
172
function blink(selector){
173
        $(selector).animate({ color: "red" }, 500, function(){
174
        $(this).animate({ color: "#555555" }, 500, function(){
175
        blink(this);
176
        });
177
        });
178
}
179