HTTP API Examples

From Open-Xchange

Code examples on how to access the Open-Xchange HTTP API

Accessing EMails

This example accesses the HTTP API to list mails in the users inbox. It must run in the same domain as the Open-Xchange server.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Mail Example</title>
<style type="text/css">
body {
    padding: 10px;
}
.inbox {
    width: 400px;
    overflow: visible;
}
.mail {
    position: relative;
    border-bottom: 1px solid #ccc;
    white-space: nowrap;
    font-size: 10pt;
    line-height: 1.3333em;
    height: 6.5em;
}
.mail > div {
    position: absolute;
    top: 0.75em;
    right: 1em;
    bottom: 0.75em;
    left: 1em;
}
.mail:hover {
    background-color: #f5f5f5;
}
.ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
}
.from {
    position: absolute;
    top: 0;
    width: 60%;
    font-size: 12pt;
}
.date {
    position: absolute;
    top: 0;
    left: 60%;
    width: 40%;
    text-align: right;
    color: #06c;
    font-size: 9pt;
}
.subject {
    position: absolute;
    top: 1.6em;
    width: 100%;
    font-size: 9pt;
}
.teaser {
    position: absolute;
    top: 3em;
    height: 2em;
    line-height: 1em;
    color: #555;
    font-weight: normal;
    white-space: normal;
}
.teaser > span {
    font-size: 9pt;
}
.unread {
    font-weight: bold;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script>

$(document).ready(function () {

    var ajaxRoot = "/ajax", // should always be this one
        client = "com.openexchange.ox.gui.dhtml", // must match UI (affects cookie handling)
        session = ""; // we get this with first autologin request
        
    // set default content type - we speak JSON all the time
    $.ajaxSetup({ dataType: "json" });

    // helper to convert arrays into key-value objects
    function makeObjects(list, columns) {
        var i = 0, $i = list.length, tmp = [], arr, obj, j, $j;
        for (; i < $i; i++) {
            arr = list[i];
            obj = {};
            for (j = 0, $j = arr.length; j < $j; j++) {
                obj[columns[j]] = arr[j];
            }
            tmp.push(obj);
        }
        return tmp;
    }
    
    function drawLoginButton() {
        $("#inbox").hide();
        $("#form").show();
    }

    function getTeaser(folder, id, node) {
        // get mail text (plain/text)
        $.ajax({
            url: ajaxRoot + "/mail?" + $.param({
                action: "get", folder: folder, id: id, unseen: "true", view: "text",
                session: session
            })
        })
        .done(function (r) {
            try {
                // show first lines...
                var text = $("<span/>").html(r.data.attachments[0].content).get(0);
                node.text((text.innerText || text.textContent).substr(0, 200));
            } catch (e) {
            }
        });
    }

    function drawInbox(list) {

        var node = $("<div/>").addClass("inbox"),
            getDate = function (d) {
                d = new Date();
                return d.getDate() + "." + (d.getMonth() + 1) + "." + d.getFullYear();
            };
        
        // loop over mails
        $.each(list, function (i, mail) {

            var unread = (mail.flags & 32) === 0,
                teaser;
            
            node.append(
                $("<div/>")
                .addClass(
                    "mail" + (i % 2 ? " odd" : "")
                    + (unread ? " unread" : "")
                )
                .append(
                    $("<div/>")
                    .append(
                        $("<div/>")
                        .addClass("from ellipsis")
                        .append(
                            $("<span/>")
                            .text((mail.from[0][0] || mail.from[0][1]).replace(/"|'/g, ""))
                        )
                    )
                    .append(
                        $("<div/>")
                        .addClass("date ellipsis")
                        .text(getDate(mail.received_date))
                    )
                    .append(
                        $("<div/>")
                        .addClass("subject ellipsis")
                        .text(mail.subject)
                    )
                    .append(
                        $("<div/>").append(teaser = $("<span/>"))
                        .addClass("teaser ellipsis")
                    )
                )
            )
            
            // get teaser text
            getTeaser(mail.folder, mail.id, teaser);
        });
        
        $("#form").hide();
        $("#inbox").empty().append(node)
            .append(
                $("<input/>", { type: "button", value: "Logout" })
                .css("margin", "1em")
                .click(logout)
            )
            .show();
    }
    
    function getInbox() {

        // continuation
        function getMailHeaders(list) {
            // get first mails
            // for columns see http://oxpedia.org/index.php?title=HTTP_API#Module_.22mail.22
            var count = 7;
            $.ajax({
                type: "PUT",
                url: ajaxRoot + "/mail?" + $.param({
                    action: "list", columns: "600,601,603,607,610,611,655",
                    session: session
                }),
                data: JSON.stringify(list.slice(0, count))
            })
            .done(function (response) {
                if (response.error) {
                    drawLoginButton();
                } else {
                    drawInbox(makeObjects(response.data, ["id", "folder", "from", "subject", "received_date", "flags", "attachments"]));
                }
            });
        }
        
        $.ajax({
            // get all mails in INBOX (id & folder_id only; do not fetch mail headers -> slow!)
            // folder is "default0/INBOX". assumption: IMAP path prefix is "/"
            url: ajaxRoot + "/mail?" + $.param({
                action: "all", columns: "600,601",
                folder: "default0/INBOX", session: session,
                sort: "610", order: "desc" // order by received_date
            })
        })
        .done(function (response) {
            // API error, e.g. session not found?
            if (response.error) {
                drawLoginButton();
            } else {
                // continue
                // response.data contains array of id/folder_id pairs.
                // we convert this to key/value objects because it's easier to write and
                // debug code that way (obj.folder_id instead of obj[1]).
                getMailHeaders(makeObjects(response.data, ["id", "folder"]));
            }
        })
        .error(drawLoginButton); // general network error
    }
    
    function autoLogin() {
        // auto login to get session id -- must be activated on server!
        $.ajax({
            url: ajaxRoot + "/login?" + $.param({
                action: "autologin", client: client
            })
        })
        .done(function (response) {
            if (response.error) {
                drawLoginButton();
            } else {
                // remember session id
                session = response.session;
                // get inbox
                getInbox();
            }
        });
    }

    function login() {
        // Two steps:
        // Step #1: Login with username & password
        // Step #2: Pull special persistence cookie that allows auto-login
        $.ajax({
            type: "POST",
            url: ajaxRoot + "/login?" + $.param({
                action: "login",
                client: client
            }),
            data: $.param({
                password: $("#password").val(),
                name: $("#name").val()
            }),
        })
        .done(function (response) {
            if (response.session) {
                // store cookie for future autologin requests
                $.ajax({
                    type: "GET",
                    url: ajaxRoot + "/login?" + $.param({
                        action: "store",
                        session: (session = response.session)
                    })
                })
                .done(getInbox)
            }
        });
        return false;
    }

    function logout() {
        $.ajax({
            type: "GET",
            url: ajaxRoot + "/login?" + $.param({
                action: "logout",
                client: client,
                session: session
            })
        })
        .done(function () {
            session = "";
            drawLoginButton();
        });
        return false;
    }
    
    $("#form").submit(login);

    autoLogin();
});

</script>
</head>
<body>

<div id="form" style="display: none">
    <form action="" name="OX6.UI">
        <input type="text" id="name" name="name" value=""/><br/>
        <input type="password" id="password" name="password" value=""/><br/>
        <input type="submit" value="Login"/>
    </form>
</div>

<div id="inbox"></div>

</body>
</html>