<commit_before>/*global $, require, module*/
var wysiwyg = require('wysiwyg-js');
require('./wysiwyg-editor');
var uuid = require('uuid/v4');
var popups = require('./wysiwyg-editor.customPopups');
require('../css/wysiwyg-editor.css');

var makeWysisyg = function($wysiwyg) {
    var nextNode = function(node) {
        if (node.hasChildNodes()) {
            return node.firstChild;
        } else {
            while (node && !node.nextSibling) {
                node = node.parentNode;
            }
            if (!node) {
                return null;
            }
            return node.nextSibling;
        }
    };

    var getRangeSelectedNodes = function(range) {
        var node = range.startContainer;
        var endNode = range.endContainer;

        // Special case for a range that is contained within a single node
        if (node == endNode) {
            return [node];
        }

        // Iterate nodes until we hit the end container
        var rangeNodes = [];
        while (node && node != endNode) {
            rangeNodes.push( node = nextNode(node) );
        }

        // Add partially selected nodes at the start of the range
        node = range.startContainer;
        while (node && node != range.commonAncestorContainer) {
            rangeNodes.unshift(node);
            node = node.parentNode;
        }

        return rangeNodes;
    };

    var getSelectedNodes = function() {
        if (window.getSelection) {
            var sel = window.getSelection();
            if (!sel.isCollapsed) {
                return getRangeSelectedNodes(sel.getRangeAt(0));
            }
        }
        return [];
    };

    var wysiwygBold = function($wysiwyg) {
        $wysiwyg.wysiwyg('shell').bold();
        wysiwygReplaceTag($wysiwyg, "b", "strong");
        window.edited = true;
    };

    var wysiwygItalic = function($wysiwyg) {
        $wysiwyg.wysiwyg('shell').italic();
        wysiwygReplaceTag($wysiwyg, "i", "em");
        window.edited = true;
    };

    var wysiwygUnlink = function($wysiwyg) {
        document.execCommand('unlink', false, false);
        $wysiwyg.wysiwyg('shell').sync();
        window.edited = true;
    };

    var wysiwygReplaceTag = function($wysiwyg, oldSelector, newTag, processFunc) {
        $wysiwyg
            .wysiwyg('container')
            .find(oldSelector)
            .replaceWith(function() {
                //console.log($(this));
                var $result = $("<" + newTag + " />", {
                    html: $(this).html()
                });
                if (processFunc) {
                    processFunc.apply(this, [$result]);
                }
                return $result;
            });
        window.edited = true;
    };

    // http://stackoverflow.com/a/6691294
    var placeHtmlAtCaret = function(html, selectPastedContent) {
        var sel, range;
        if (window.getSelection) {
            // IE9 and non-IE
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();

                // Range.createContextualFragment() would be useful here but is
                // only relatively recently standardized and is not supported in
                // some browsers (IE9, for one)
                var el = document.createElement("div");
                el.innerHTML = html;
                var frag = document.createDocumentFragment(), node, lastNode;
                while ( (node = el.firstChild) ) {
                    lastNode = frag.appendChild(node);
                }
                var firstNode = frag.firstChild;
                range.insertNode(frag);

                // Preserve the selection
                if (lastNode) {
                    range = range.cloneRange();
                    range.setStartAfter(lastNode);
                    if (selectPastedContent) {
                        range.setStartBefore(firstNode);
                    } else {
                        range.collapse(true);
                    }
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        } else if ( (sel = document.selection) && sel.type != "Control") {
            // IE < 9
            var originalRange = sel.createRange();
            originalRange.collapse(true);
            sel.createRange().pasteHTML(html);
            if (selectPastedContent) {
                range = sel.createRange();
                range.setEndPoint("StartToStart", originalRange);
                range.select();
            }
        }
    };

    $wysiwyg.wysiwyg({
        toolbar: "top-selection",
        buttons: {
            bold: {
                title: 'Полужирный (Ctrl+B)',
                image: '\uf032',
                click: function($button) {
                    wysiwygBold($wysiwyg);
                },
                showstatic: true,
                showselection: true
            },
            italic: {
                title: 'Курсив (Ctrl+I)',
                image: '\uf033',
                click: function($button) {
                    wysiwygItalic($wysiwyg);
                },
                showstatic: true,
                showselection: true
            },
            forecolor: {
                title: 'Цвет текста',
                image: '\uf1fc',
                popup: function($popup, $button) {
                    $popup.append(popups.openColorPalette(function(color) {
                        $wysiwyg.wysiwyg('shell').forecolor(color).closePopup().collapseSelection();
                        wysiwygReplaceTag($wysiwyg, "font[color]", "span", function($result) {
                            $result.css('color', color);
                        });
                    }));
                },
                showstatic: true,
                showselection: true
            },
            insertlink: {
                title: 'Преобразовать в ссылку',
                image: '\uf0c1',
                popup: function($popup, $button) {
                    var selectedNodes = getSelectedNodes();

                    var $selectedNodes = [];
                    $.each(selectedNodes, function(idx, node) {
                        $selectedNodes[$selectedNodes.length] = $(node);
                    });
                    $selectedNodes = $($selectedNodes).map(function() {
                        return this.toArray();
                    });

                    var $oldLink = $selectedNodes.closest("a");
                    var oldHref, oldTarget;
                    if ($oldLink.length) {
                        oldHref = $oldLink.attr('href');
                        oldTarget = $oldLink.attr('target');
                    } else {
                        console.log($selectedNodes);
                        var $oldImg = $selectedNodes.find("img");
                        if ($oldImg.length) {
                            oldHref = $oldImg.attr('src');
                            oldTarget = "_blank";
                        }
                    }

                    if (typeof oldHref === typeof undefined) {
                        oldHref = "";
                    }

                    if (typeof oldTarget === typeof undefined) {
                        oldTarget = "";
                    }

                    $popup.append(popups.openLinkConverter(function(href, target) {
                        var dummyHref;
                        do {
                            dummyHref = uuid();
                        } while ($wysiwyg.wysiwyg('container').find("a[href='" + dummyHref + "']").length);

                        $wysiwyg.wysiwyg('shell').insertLink(dummyHref).closePopup();
                        var $link = $wysiwyg
                            .wysiwyg('container')
                            .find("a[href='" + dummyHref + "']");
                        $link.attr('href', href);
                        if (target != "") {
                            $link.attr('target', target);
                        }
                        window.edited = true;
                    }, function() {
                        $wysiwyg.wysiwyg('shell').closePopup();
                    }, oldHref, oldTarget));
                },
                showstatic: false,
                showselection: true
            },
            unlink: {
                title: 'Удалить ссылку',
                image: '\uf127',
                click: function($button) {
                    wysiwygUnlink($wysiwyg);
                },
                showstatic: false,
                showselection: true
            },
            insertimage: {
                title: 'Вставить картинку',
                image: '\uf030',
                popup: function($popup, $button) {
                    $popup.append(popups.openImageInserter(function(src) {
                        var dummySrc;
                        do {
                            dummySrc = uuid();
                        } while ($wysiwyg.wysiwyg('container').find("img[src='" + dummySrc + "']").length);

                        $wysiwyg.wysiwyg('shell').insertImage(dummySrc).closePopup();

                        var $image = $wysiwyg
                            .wysiwyg('container')
                            .find("img[src='" + dummySrc + "']");

                        $image.attr('src', src);

                        window.edited = true;
                    }, function() {
                        $wysiwyg.wysiwyg('shell').closePopup();
                    }));
                },
                showstatic: true,
                showselection: false
            },
            insertfile: {
                title: 'Сделать ссылкой на файл',
                image: '\uf15b',
                popup: function($popup, $button) {
                    $popup.append(popups.openFileLinkMaker(function(href, target) {
                        var dummyHref;
                        do {
                            dummyHref = uuid();
                        } while ($wysiwyg.wysiwyg('container').find("a[href='" + dummyHref + "']").length);

                        $wysiwyg.wysiwyg('shell').insertLink(dummyHref).closePopup();
                        var $link = $wysiwyg
                            .wysiwyg('container')
                            .find("a[href='" + dummyHref + "']");
                        $link.attr('href', href);
                        if (target != "") {
                            $link.attr('target', target);
                        }
                        window.edited = true;
                    }, function() {
                        $wysiwyg.wysiwyg('shell').closePopup();
                    }));
                },
                showstatic: false,
                showselection: true
            },
            removeformat: {
                title: 'Сбросить форматирование',
                image: '\uf12d',
                showstatic: false,
                showselection: true
            }
        },
        submit: {
            title: 'OK',
            image: '\uf00c'
        },
        onKeyPress: function(key, character, shiftKey, altKey, ctrlKey, metaKey) {
            if (typeof $wysiwyg.data('keyPressUserFunc') !== typeof undefined) {
                $wysiwyg.data('keyPressUserFunc').apply(this, [key, character, shiftKey, altKey, ctrlKey, metaKey]);
            }

            window.edited = true;

            console.log({
                key: key,
                character: character,
                shiftKey: shiftKey,
                altKey: altKey,
                ctrlKey: ctrlKey,
                metaKey: metaKey
            });

            if ((character == "b") && (ctrlKey) && (!altKey) && (!shiftKey) && (!metaKey)) {
                wysiwygBold($wysiwyg);
                return false;
            } else if ((character == "i") && (ctrlKey) && (!altKey) && (!shiftKey) && (!metaKey)) {
                wysiwygItalic($wysiwyg);
                return false;
            } else if ((key == 13) && (!ctrlKey) && (!altKey) && (shiftKey) && (!metaKey)) {
                placeHtmlAtCaret("
", false);
                return false;
            } else {
                return true;
            }
        },
        placeholderUrl: '',
        selectImage: 'Перетащите сюда изображение или щелкните здесь',
        //maxImageSize: [600, 200],
        forceImageUpload: true,    // upload images even if File-API is present
        onImageUpload: function(insert_image) {
            // A bit tricky, because we can't easily upload a file via
            // '$.ajax()' on a legacy browser without XMLHttpRequest2.
            // You have to submit the form into an '' element.
            // Call 'insert_image(url)' as soon as the file is online
            // and the URL is available.
            var iframe_name = 'legacy-uploader-' + uuid();
            $('')
                .attr('name', iframe_name)
                .load(function() {
                    //  is ready - we will find the URL in the iframe-body
                    var iframe = this;
                    var iframedoc = iframe.contentDocument ? iframe.contentDocument :
                        (iframe.contentWindow ? iframe.contentWindow.document : iframe.document);
                    var iframebody = iframedoc.getElementsByTagName('body')[0];
                    var image_url = iframebody.innerHTML;
                    insert_image(image_url);
                    $(iframe).remove();
                })
                .appendTo(document.body);
            var $input = $(this);
            $input
                .attr('name', 'upload-filename')
                .parents('form')
                .attr('action', "/uploadImage")// TODO: image uploader
                .attr('method', 'POST')
                .attr('enctype', 'multipart/form-data')
                .attr('target', iframe_name)
                .submit();
        },
    });

    $wysiwyg.on('paste.clearFormat', function(e) {
        var pastedData;
        console.log(e.originalEvent.clipboardData);
        pastedData = e.originalEvent.clipboardData.getData('text/plain');
        console.log(pastedData);
        // Parse pasted data to paragraphs
        var paragraphs = pastedData.split('\n');
        var html = '';
        paragraphs.forEach(function(p, idx) {
            if (idx > 0) {
                html += '
';
            }
            html += p + '
';
        });
        // http://stackoverflow.com/a/2925633
        // https://stackoverflow.com/a/3599599/2175025
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();
                // the selection is cleared
                // so we might be inside a
 with 0-length range
                // find
 outside
                var rangeParentNode = range.startContainer.parentElement;
                if (
                    rangeParentNode
                    && rangeParentNode.nodeType === Node.ELEMENT_NODE
                    && rangeParentNode.tagName === 'P'
                ) {
                    // yes, we're inside

                    // keep the leading offset
                    var offsetBeforePaste = range.startOffset;
                    // keep the trailing to form the last paragraph
                    var trailing = rangeParentNode.innerHTML.substring(range.startOffset);
                    // remember the length of the first pasted paragraph
                    var firstPastedParagraphLength = paragraphs[0].length;
                    // append the first pasted paragraph to the end of this one
                    // and cut off the trailing
                    rangeParentNode.innerHTML = rangeParentNode.innerHTML.substring(0, range.startOffset) + paragraphs.shift();
                    // add rest new paragraphs with the stored trailing
                    if (paragraphs.length) {
                        var lastPastedParagraphLength;
                        var $lastInsertedParagraph = $(rangeParentNode);
                        paragraphs.forEach(function (str, idx) {
                            var content = str;
                            if (idx === paragraphs.length - 1) {
                                // remember the length
                                lastPastedParagraphLength = content.length;
                                // restore the trailing
                                content += trailing;
                            }
                            var $p = $('
' + content + '
');
                            $p.insertAfter($lastInsertedParagraph);
                            $lastInsertedParagraph = $p;
                        });
                        lastP = $lastInsertedParagraph.get(0);

                        if (lastP.childNodes.length) {
                            range.setStart(lastP.childNodes[0], lastPastedParagraphLength);
                            range.setEnd(lastP.childNodes[0], lastPastedParagraphLength);
                        } else {
                            // last
 is empty
                            range.setStart(lastP, 0);
                            range.setEnd(lastP, 0);
                        }
                    } else {
                        // there is no paragraphs to paste left
                        // so restore the trailing to the current one
                        rangeParentNode.innerHTML += trailing;
                        lastP = rangeParentNode;
                        range.setStart(lastP.childNodes[0], offsetBeforePaste + firstPastedParagraphLength);
                        range.setEnd(lastP.childNodes[0], offsetBeforePaste + firstPastedParagraphLength);
                    }

                    sel.removeAllRanges();
                    sel.addRange(range);
                } else {
                    // we're somewhere in the ass
                    // use an algorithm from StackOverflow
                    var tmp = document.createElement('div');
                    tmp.innerHTML = html;
                    var frag = document.createDocumentFragment();
                    var p, lastP;
                    while ((p = tmp.firstChild)) {
                        lastP = frag.appendChild(p);
                    }
                    range.insertNode(frag);
                    range.setStartAfter(lastP);
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        } else if (document.selection && document.selection.createRange) {
            document.selection.createRange().pasteHTML(html);
        }

        window.edited = true;
        e.preventDefault();
    });
};

module.exports = makeWysisyg;
<commit_msg>Callback when edited instead of littering global window props<commit_after>/*global $, require, module*/
var wysiwyg = require('wysiwyg-js');
require('./wysiwyg-editor');
var uuid = require('uuid/v4');
var popups = require('./wysiwyg-editor.customPopups');
require('../css/wysiwyg-editor.css');

var makeWysisyg = function($wysiwyg, callbackWhenEdited) {
    var nextNode = function(node) {
        if (node.hasChildNodes()) {
            return node.firstChild;
        } else {
            while (node && !node.nextSibling) {
                node = node.parentNode;
            }
            if (!node) {
                return null;
            }
            return node.nextSibling;
        }
    };

    var getRangeSelectedNodes = function(range) {
        var node = range.startContainer;
        var endNode = range.endContainer;

        // Special case for a range that is contained within a single node
        if (node == endNode) {
            return [node];
        }

        // Iterate nodes until we hit the end container
        var rangeNodes = [];
        while (node && node != endNode) {
            rangeNodes.push( node = nextNode(node) );
        }

        // Add partially selected nodes at the start of the range
        node = range.startContainer;
        while (node && node != range.commonAncestorContainer) {
            rangeNodes.unshift(node);
            node = node.parentNode;
        }

        return rangeNodes;
    };

    var getSelectedNodes = function() {
        if (window.getSelection) {
            var sel = window.getSelection();
            if (!sel.isCollapsed) {
                return getRangeSelectedNodes(sel.getRangeAt(0));
            }
        }
        return [];
    };

    var wysiwygBold = function($wysiwyg) {
        $wysiwyg.wysiwyg('shell').bold();
        wysiwygReplaceTag($wysiwyg, "b", "strong");
        callbackWhenEdited();
    };

    var wysiwygItalic = function($wysiwyg) {
        $wysiwyg.wysiwyg('shell').italic();
        wysiwygReplaceTag($wysiwyg, "i", "em");
        callbackWhenEdited();
    };

    var wysiwygUnlink = function($wysiwyg) {
        document.execCommand('unlink', false, false);
        $wysiwyg.wysiwyg('shell').sync();
        callbackWhenEdited();
    };

    var wysiwygReplaceTag = function($wysiwyg, oldSelector, newTag, processFunc) {
        $wysiwyg
            .wysiwyg('container')
            .find(oldSelector)
            .replaceWith(function() {
                //console.log($(this));
                var $result = $("<" + newTag + " />", {
                    html: $(this).html()
                });
                if (processFunc) {
                    processFunc.apply(this, [$result]);
                }
                return $result;
            });
        callbackWhenEdited();
    };

    // http://stackoverflow.com/a/6691294
    var placeHtmlAtCaret = function(html, selectPastedContent) {
        var sel, range;
        if (window.getSelection) {
            // IE9 and non-IE
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();

                // Range.createContextualFragment() would be useful here but is
                // only relatively recently standardized and is not supported in
                // some browsers (IE9, for one)
                var el = document.createElement("div");
                el.innerHTML = html;
                var frag = document.createDocumentFragment(), node, lastNode;
                while ( (node = el.firstChild) ) {
                    lastNode = frag.appendChild(node);
                }
                var firstNode = frag.firstChild;
                range.insertNode(frag);

                // Preserve the selection
                if (lastNode) {
                    range = range.cloneRange();
                    range.setStartAfter(lastNode);
                    if (selectPastedContent) {
                        range.setStartBefore(firstNode);
                    } else {
                        range.collapse(true);
                    }
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        } else if ( (sel = document.selection) && sel.type != "Control") {
            // IE < 9
            var originalRange = sel.createRange();
            originalRange.collapse(true);
            sel.createRange().pasteHTML(html);
            if (selectPastedContent) {
                range = sel.createRange();
                range.setEndPoint("StartToStart", originalRange);
                range.select();
            }
        }
    };

    $wysiwyg.wysiwyg({
        toolbar: "top-selection",
        buttons: {
            bold: {
                title: 'Полужирный (Ctrl+B)',
                image: '\uf032',
                click: function($button) {
                    wysiwygBold($wysiwyg);
                },
                showstatic: true,
                showselection: true
            },
            italic: {
                title: 'Курсив (Ctrl+I)',
                image: '\uf033',
                click: function($button) {
                    wysiwygItalic($wysiwyg);
                },
                showstatic: true,
                showselection: true
            },
            forecolor: {
                title: 'Цвет текста',
                image: '\uf1fc',
                popup: function($popup, $button) {
                    $popup.append(popups.openColorPalette(function(color) {
                        $wysiwyg.wysiwyg('shell').forecolor(color).closePopup().collapseSelection();
                        wysiwygReplaceTag($wysiwyg, "font[color]", "span", function($result) {
                            $result.css('color', color);
                        });
                    }));
                },
                showstatic: true,
                showselection: true
            },
            insertlink: {
                title: 'Преобразовать в ссылку',
                image: '\uf0c1',
                popup: function($popup, $button) {
                    var selectedNodes = getSelectedNodes();

                    var $selectedNodes = [];
                    $.each(selectedNodes, function(idx, node) {
                        $selectedNodes[$selectedNodes.length] = $(node);
                    });
                    $selectedNodes = $($selectedNodes).map(function() {
                        return this.toArray();
                    });

                    var $oldLink = $selectedNodes.closest("a");
                    var oldHref, oldTarget;
                    if ($oldLink.length) {
                        oldHref = $oldLink.attr('href');
                        oldTarget = $oldLink.attr('target');
                    } else {
                        console.log($selectedNodes);
                        var $oldImg = $selectedNodes.find("img");
                        if ($oldImg.length) {
                            oldHref = $oldImg.attr('src');
                            oldTarget = "_blank";
                        }
                    }

                    if (typeof oldHref === typeof undefined) {
                        oldHref = "";
                    }

                    if (typeof oldTarget === typeof undefined) {
                        oldTarget = "";
                    }

                    $popup.append(popups.openLinkConverter(function(href, target) {
                        var dummyHref;
                        do {
                            dummyHref = uuid();
                        } while ($wysiwyg.wysiwyg('container').find("a[href='" + dummyHref + "']").length);

                        $wysiwyg.wysiwyg('shell').insertLink(dummyHref).closePopup();
                        var $link = $wysiwyg
                            .wysiwyg('container')
                            .find("a[href='" + dummyHref + "']");
                        $link.attr('href', href);
                        if (target != "") {
                            $link.attr('target', target);
                        }
                        callbackWhenEdited();
                    }, function() {
                        $wysiwyg.wysiwyg('shell').closePopup();
                    }, oldHref, oldTarget));
                },
                showstatic: false,
                showselection: true
            },
            unlink: {
                title: 'Удалить ссылку',
                image: '\uf127',
                click: function($button) {
                    wysiwygUnlink($wysiwyg);
                },
                showstatic: false,
                showselection: true
            },
            insertimage: {
                title: 'Вставить картинку',
                image: '\uf030',
                popup: function($popup, $button) {
                    $popup.append(popups.openImageInserter(function(src) {
                        var dummySrc;
                        do {
                            dummySrc = uuid();
                        } while ($wysiwyg.wysiwyg('container').find("img[src='" + dummySrc + "']").length);

                        $wysiwyg.wysiwyg('shell').insertImage(dummySrc).closePopup();

                        var $image = $wysiwyg
                            .wysiwyg('container')
                            .find("img[src='" + dummySrc + "']");

                        $image.attr('src', src);

                        callbackWhenEdited();
                    }, function() {
                        $wysiwyg.wysiwyg('shell').closePopup();
                    }));
                },
                showstatic: true,
                showselection: false
            },
            insertfile: {
                title: 'Сделать ссылкой на файл',
                image: '\uf15b',
                popup: function($popup, $button) {
                    $popup.append(popups.openFileLinkMaker(function(href, target) {
                        var dummyHref;
                        do {
                            dummyHref = uuid();
                        } while ($wysiwyg.wysiwyg('container').find("a[href='" + dummyHref + "']").length);

                        $wysiwyg.wysiwyg('shell').insertLink(dummyHref).closePopup();
                        var $link = $wysiwyg
                            .wysiwyg('container')
                            .find("a[href='" + dummyHref + "']");
                        $link.attr('href', href);
                        if (target != "") {
                            $link.attr('target', target);
                        }
                        callbackWhenEdited();
                    }, function() {
                        $wysiwyg.wysiwyg('shell').closePopup();
                    }));
                },
                showstatic: false,
                showselection: true
            },
            removeformat: {
                title: 'Сбросить форматирование',
                image: '\uf12d',
                showstatic: false,
                showselection: true
            }
        },
        submit: {
            title: 'OK',
            image: '\uf00c'
        },
        onKeyPress: function(key, character, shiftKey, altKey, ctrlKey, metaKey) {
            if (typeof $wysiwyg.data('keyPressUserFunc') !== typeof undefined) {
                $wysiwyg.data('keyPressUserFunc').apply(this, [key, character, shiftKey, altKey, ctrlKey, metaKey]);
            }

            callbackWhenEdited();

            console.log({
                key: key,
                character: character,
                shiftKey: shiftKey,
                altKey: altKey,
                ctrlKey: ctrlKey,
                metaKey: metaKey
            });

            if ((character == "b") && (ctrlKey) && (!altKey) && (!shiftKey) && (!metaKey)) {
                wysiwygBold($wysiwyg);
                return false;
            } else if ((character == "i") && (ctrlKey) && (!altKey) && (!shiftKey) && (!metaKey)) {
                wysiwygItalic($wysiwyg);
                return false;
            } else if ((key == 13) && (!ctrlKey) && (!altKey) && (shiftKey) && (!metaKey)) {
                placeHtmlAtCaret("
", false);
                return false;
            } else {
                return true;
            }
        },
        placeholderUrl: '',
        selectImage: 'Перетащите сюда изображение или щелкните здесь',
        //maxImageSize: [600, 200],
        forceImageUpload: true,    // upload images even if File-API is present
        onImageUpload: function(insert_image) {
            // A bit tricky, because we can't easily upload a file via
            // '$.ajax()' on a legacy browser without XMLHttpRequest2.
            // You have to submit the form into an '' element.
            // Call 'insert_image(url)' as soon as the file is online
            // and the URL is available.
            var iframe_name = 'legacy-uploader-' + uuid();
            $('')
                .attr('name', iframe_name)
                .load(function() {
                    //  is ready - we will find the URL in the iframe-body
                    var iframe = this;
                    var iframedoc = iframe.contentDocument ? iframe.contentDocument :
                        (iframe.contentWindow ? iframe.contentWindow.document : iframe.document);
                    var iframebody = iframedoc.getElementsByTagName('body')[0];
                    var image_url = iframebody.innerHTML;
                    insert_image(image_url);
                    $(iframe).remove();
                })
                .appendTo(document.body);
            var $input = $(this);
            $input
                .attr('name', 'upload-filename')
                .parents('form')
                .attr('action', "/uploadImage")// TODO: image uploader
                .attr('method', 'POST')
                .attr('enctype', 'multipart/form-data')
                .attr('target', iframe_name)
                .submit();
        },
    });

    $wysiwyg.on('paste.clearFormat', function(e) {
        var pastedData;
        console.log(e.originalEvent.clipboardData);
        pastedData = e.originalEvent.clipboardData.getData('text/plain');
        console.log(pastedData);
        // Parse pasted data to paragraphs
        var paragraphs = pastedData.split('\n');
        var html = '';
        paragraphs.forEach(function(p, idx) {
            if (idx > 0) {
                html += '
';
            }
            html += p + '
';
        });
        // http://stackoverflow.com/a/2925633
        // https://stackoverflow.com/a/3599599/2175025
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();
                // the selection is cleared
                // so we might be inside a
 with 0-length range
                // find
 outside
                var rangeParentNode = range.startContainer.parentElement;
                if (
                    rangeParentNode
                    && rangeParentNode.nodeType === Node.ELEMENT_NODE
                    && rangeParentNode.tagName === 'P'
                ) {
                    // yes, we're inside

                    // keep the leading offset
                    var offsetBeforePaste = range.startOffset;
                    // keep the trailing to form the last paragraph
                    var trailing = rangeParentNode.innerHTML.substring(range.startOffset);
                    // remember the length of the first pasted paragraph
                    var firstPastedParagraphLength = paragraphs[0].length;
                    // append the first pasted paragraph to the end of this one
                    // and cut off the trailing
                    rangeParentNode.innerHTML = rangeParentNode.innerHTML.substring(0, range.startOffset) + paragraphs.shift();
                    // add rest new paragraphs with the stored trailing
                    if (paragraphs.length) {
                        var lastPastedParagraphLength;
                        var $lastInsertedParagraph = $(rangeParentNode);
                        paragraphs.forEach(function (str, idx) {
                            var content = str;
                            if (idx === paragraphs.length - 1) {
                                // remember the length
                                lastPastedParagraphLength = content.length;
                                // restore the trailing
                                content += trailing;
                            }
                            var $p = $('
' + content + '
');
                            $p.insertAfter($lastInsertedParagraph);
                            $lastInsertedParagraph = $p;
                        });
                        lastP = $lastInsertedParagraph.get(0);

                        if (lastP.childNodes.length) {
                            range.setStart(lastP.childNodes[0], lastPastedParagraphLength);
                            range.setEnd(lastP.childNodes[0], lastPastedParagraphLength);
                        } else {
                            // last
 is empty
                            range.setStart(lastP, 0);
                            range.setEnd(lastP, 0);
                        }
                    } else {
                        // there is no paragraphs to paste left
                        // so restore the trailing to the current one
                        rangeParentNode.innerHTML += trailing;
                        lastP = rangeParentNode;
                        range.setStart(lastP.childNodes[0], offsetBeforePaste + firstPastedParagraphLength);
                        range.setEnd(lastP.childNodes[0], offsetBeforePaste + firstPastedParagraphLength);
                    }

                    sel.removeAllRanges();
                    sel.addRange(range);
                } else {
                    // we're somewhere in the ass
                    // use an algorithm from StackOverflow
                    var tmp = document.createElement('div');
                    tmp.innerHTML = html;
                    var frag = document.createDocumentFragment();
                    var p, lastP;
                    while ((p = tmp.firstChild)) {
                        lastP = frag.appendChild(p);
                    }
                    range.insertNode(frag);
                    range.setStartAfter(lastP);
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        } else if (document.selection && document.selection.createRange) {
            document.selection.createRange().pasteHTML(html);
        }

        callbackWhenEdited();
        e.preventDefault();
    });
};

module.exports = makeWysisyg;
<|endoftext|>


<commit_before>var WebSocketServer = require("ws").Server
var http = require("http")
var express = require("express")
var app = express()
var port = process.env.PORT || 5000

app.use(express.static(process.cwd() + "/client"))

var server = http.createServer(app)
server.listen(port)

console.log("http server listening on %d", port)

var wss = new WebSocketServer({server: server})
console.log("websocket server created")

wss.on("connection", function(ws) {
    ws.on('message', function(message) {
        console.log('received: %s', message);
        wss.broadcast(message);
    });
})<commit_msg>broadcst<commit_after>var WebSocketServer = require("ws").Server
var http = require("http")
var express = require("express")
var app = express()
var port = process.env.PORT || 5000

app.use(express.static(process.cwd() + "/client"))

var server = http.createServer(app)
server.listen(port)

console.log("http server listening on %d", port)

var wss = new WebSocketServer({server: server})

wss.broadcast = function(data) {
    for(var i in this.clients) {
        this.clients[i].send(data);
    }
};

wss.on("connection", function(ws) {
    ws.on('message', function(message) {
        console.log('received: %s', message);
        wss.broadcast(message);
    });
})<|endoftext|>


<commit_before>apos.widgetPlayers.facebook = function($el) {

  // N.B. Even though this is a player, it's not getting refreshed
  // once it's been created. Hrmmm.

  var data = apos.getWidgetData($el),
      pageUrl = data.pageUrl;

  $.getJSON(
    // Note the trailing ? is significant. It tells jQuery to automatically
    // create a JSONP callback function and obtain the result via a cross-domain
    // script tag so we can talk to twitter in older browsers without a
    // security error
    '/apos-facebook/feed',
    {
      limit: (data.limit || 5),
      pageUrl: pageUrl,
    },
    function(posts) {

      //Define our posts object as well as the template and loader.
      var $posts = $el.find('[data-apos-facebook-posts]'),
          $postTemplate = $posts.find('[data-apos-facebook-post].apos-template'),
          $loader = $posts.find('[data-apos-facebook-loader]');

      if (!posts.length) {
        $el.trigger('aposFacebookNull');
        return;
      }

      function init(){
        removePlaceholder();
        generatePostMarkup(posts);
      }

      function removePlaceholder(){
        $posts.find('[data-apos-facebook-placeholder]').remove();
      }

      function removeTemplate(){
        $postTemplate.remove();
      };

      function buildTemplate($template){
        $template.$title = $template.find('[data-apos-facebook-title]');
        $template.$link = $template.find('[data-apos-facebook-link]');
        $template.$date = $template.find('[data-apos-facebook-date]');
        $template.$photo = $template.find('[data-apos-facebook-photo]');
        $template.$body = $template.find('[data-apos-facebook-body]');
        return $template;
      }

      function cloneTemplate($obj){
        $clone = $obj.clone();
        $clone.removeClass('apos-template');
        clone = buildTemplate($clone);
        return clone;
      }

      function getImageUrl(postId, callback){
        var id = postId;
        $.getJSON(
          '/apos-facebook/photo',
          { id: id},
          function(response) {
            return callback(response);
          }
        );
      }

      function getFacebookDate(date){
        var postDate = new Date(date),
            postMonth = postDate.getMonth() + 1,
            postDay = postDate.getDate(),
            postYear = postDate.getFullYear(),
            thisYear = new Date().getFullYear();

        return ((postYear != thisYear ) ? postMonth +"/"+postDay+"/"+postYear: postMonth +"/"+postDay);
      }

      function generatePostMarkup(posts){
        _.each(posts, function(post){
          //Clone our Template
          var $post = cloneTemplate($postTemplate);
          //console.log("The post should be:", $post);
          //Add Title
          if(post.name){
            $post.$title.text(post.name);
          } else {
            $post.$title.remove();
          }

          //Add Link href
          if(post.link){
            $post.$link.attr('href', post.link);
          }

          //Add Date
          if(post.date){
            var postDate = getFacebookDate(post.date);
            $post.$date.text(postDate || '');
          } else {
            $post.$date.remove();
          }

          //Add Photo based on type
          if (post.type === "photo"){
            getImageUrl(post.object_id, function(result){
              $post.$photo.find('img').attr('src', result);
            });
          } else if(post.photo){
            $post.$photo.find('img').attr('src', post.photo);
          }

          //Add Body
          if(post.body){
            $post.$body.html(post.body);
          } else {
            $post.$body.remove();
          }

          //Add Type --> Arguably, this could add a class as well.
          $post.attr('data-post-type', post.type || '');

          //If there's still a loader, kill it.
          $loader.remove();

          //Add That to the List

          $posts.append($post);
        });
        removeTemplate();
      };

      init();
    }
  );
}
<commit_msg>Updated to new afterLoader style<commit_after>apos.widgetPlayers.facebook = function($el) {
  // N.B. Even though this is a player, it's not getting refreshed
  // once it's been created. Hrmmm.

  var data = apos.getWidgetData($el),
      pageUrl = data.pageUrl;

  $.getJSON(
    '/apos-facebook/feed',
    {
      limit: (data.limit || 5),
      pageUrl: pageUrl,
    },
    function(posts) {

      //Define our posts object as well as the template and loader.
      var $posts = $el.find('[data-apos-facebook-posts]'),
          $postTemplate = $posts.find('[data-apos-facebook-post].apos-template'),
          $loader = $posts.find('[data-apos-facebook-loader]');

      if (!posts.length) {
        $el.trigger('aposFacebookNull');
        return;
      }

      function init(){
        removePlaceholder();
        generatePostMarkup(posts);
      }

      function removePlaceholder(){
        $posts.find('[data-apos-facebook-placeholder]').remove();
      }

      function removeTemplate(){
        $postTemplate.remove();
      };

      function buildTemplate($template){
        $template.$title = $template.find('[data-apos-facebook-title]');
        $template.$link = $template.find('[data-apos-facebook-link]');
        $template.$date = $template.find('[data-apos-facebook-date]');
        $template.$photo = $template.find('[data-apos-facebook-photo]');
        $template.$body = $template.find('[data-apos-facebook-body]');
        return $template;
      }

      function cloneTemplate($obj){
        $clone = $obj.clone();
        $clone.removeClass('apos-template');
        clone = buildTemplate($clone);
        return clone;
      }

      function getImageUrl(postId, callback){
        var id = postId;
        $.getJSON(
          '/apos-facebook/photo',
          { id: id},
          function(response) {
            return callback(response);
          }
        );
      }

      function getFacebookDate(date){
        var postDate = new Date(date),
            postMonth = postDate.getMonth() + 1,
            postDay = postDate.getDate(),
            postYear = postDate.getFullYear(),
            thisYear = new Date().getFullYear();

        return ((postYear != thisYear ) ? postMonth +"/"+postDay+"/"+postYear: postMonth +"/"+postDay);
      }

      function generatePostMarkup(posts){
        _.each(posts, function(post){
          //Clone our Template
          var $post = cloneTemplate($postTemplate);
          //console.log("The post should be:", $post);
          //Add Title
          if(post.name){
            $post.$title.text(post.name);
          } else {
            $post.$title.remove();
          }

          //Add Link href
          if(post.link){
            $post.$link.attr('href', post.link);
          }

          //Add Date
          if(post.date){
            var postDate = getFacebookDate(post.date);
            $post.$date.text(postDate || '');
          } else {
            $post.$date.remove();
          }

          //Add Photo based on type
          if (post.type === "photo"){
            getImageUrl(post.object_id, function(result){
              $post.$photo.find('img').attr('src', result);
            });
          } else if(post.photo){
            $post.$photo.find('img').attr('src', post.photo);
          }

          //Add Body
          if(post.body){
            $post.$body.html(post.body);
          } else {
            $post.$body.remove();
          }

          //Add Type --> Arguably, this could add a class as well.
          $post.attr('data-post-type', post.type || '');

          //If there's still a loader, kill it.
          $loader.remove();

          //Add That to the List

          $posts.append($post);
        });
        removeTemplate();
        apos.widgetPlayers.facebook.afterLoad($el, posts);
      };

      init();
    }
  );
}

apos.widgetPlayers.facebook.afterLoad = function($el, posts){
  //You can do whatever you want here.
}
<|endoftext|>


<commit_before>/*!
 * Basic postMessage Support
 *
 * Copyright (c) 2013-2016 Dave Olsen, http://dmolsen.com
 * Licensed under the MIT license
 *
 * Handles the postMessage stuff in the pattern, view-all, and style guide templates.
 *
 */

// alert the iframe parent that the pattern has loaded assuming this view was loaded in an iframe
if (self != top) {

  // handle the options that could be sent to the parent window
  //   - all get path
  //   - pattern & view all get a pattern partial, styleguide gets all
  //   - pattern shares lineage
  var path = window.location.toString();
  var parts = path.split("?");
  var options = { "event": "patternLab.pageLoad", "path": parts[0] };

  patternData = document.getElementById('sg-pattern-data-footer').innerHTML;
  patternData = JSON.parse(patternData);
  options.patternpartial = (patternData.patternPartial !== undefined) ? patternData.patternPartial : "all";
  if (patternData.lineage !== "") {
    options.lineage = patternData.lineage;
  }

  var targetOrigin = (window.location.protocol == "file:") ? "*" : window.location.protocol+"//"+window.location.host;
  parent.postMessage(options, targetOrigin);

  // find all links and add an onclick handler for replacing the iframe address so the history works
  var aTags = document.getElementsByTagName('a');
  for (var i = 0; i < aTags.length; i++) {
    aTags[i].onclick = function(e) {
      var href   = this.getAttribute("href");
      var target = this.getAttribute("target");
      if ((target !== undefined) && ((target == "_parent") || (target == "_blank"))) {
        // just do normal stuff
      } else if (href && href !== "#") {
        e.preventDefault();
        window.location.replace(href);
      } else {
        e.preventDefault();
        return false;
      }
    };
  }

  // if there are clicks on the iframe make sure the nav in the iframe parent closes
  var body = document.getElementsByTagName('body');
  body[0].onclick = function() {
    var targetOrigin = (window.location.protocol == "file:") ? "*" : window.location.protocol+"//"+window.location.host;
    var obj = JSON.stringify({ "event": "patternLab.bodyClick", "bodyclick": "bodyclick" });
    parent.postMessage(obj,targetOrigin);
  };

}

// watch the iframe source so that it can be sent back to everyone else.
function receiveIframeMessage(event) {

  // does the origin sending the message match the current host? if not dev/null the request
  if ((window.location.protocol != "file:") && (event.origin !== window.location.protocol+"//"+window.location.host)) {
    return;
  }

  var path;
  var data = {};
  try {
    data = (typeof event.data !== 'string') ? event.data : JSON.parse(event.data);
  } catch(e) {}

  if ((data.event !== undefined) && (data.event == "patternLab.updatePath")) {

    if (patternData.patternPartial !== undefined) {

      // handle patterns and the view all page
      var re = /(patterns|snapshots)\/(.*)$/;
      path = window.location.protocol+"//"+window.location.host+window.location.pathname.replace(re,'')+data.path+'?'+Date.now();
      window.location.replace(path);

    } else {

      // handle the style guide
      path = window.location.protocol+"//"+window.location.host+window.location.pathname.replace("styleguide\/html\/styleguide.html","")+data.path+'?'+Date.now();
      window.location.replace(path);

    }

  } else if ((data.event !== undefined) && (data.event == "patternLab.reload")) {

    // reload the location if there was a message to do so
    window.location.reload();

  }

}
window.addEventListener("message", receiveIframeMessage, false);
<commit_msg>cleaning up spacing<commit_after>/*!
 * Basic postMessage Support
 *
 * Copyright (c) 2013-2016 Dave Olsen, http://dmolsen.com
 * Licensed under the MIT license
 *
 * Handles the postMessage stuff in the pattern, view-all, and style guide templates.
 *
 */

// alert the iframe parent that the pattern has loaded assuming this view was loaded in an iframe
if (self != top) {

  // handle the options that could be sent to the parent window
  //   - all get path
  //   - pattern & view all get a pattern partial, styleguide gets all
  //   - pattern shares lineage
  var path = window.location.toString();
  var parts = path.split("?");
  var options = { "event": "patternLab.pageLoad", "path": parts[0] };

  patternData = document.getElementById('sg-pattern-data-footer').innerHTML;
  patternData = JSON.parse(patternData);
  options.patternpartial = (patternData.patternPartial !== undefined) ? patternData.patternPartial : "all";
  if (patternData.lineage !== "") {
    options.lineage = patternData.lineage;
  }

  var targetOrigin = (window.location.protocol == "file:") ? "*" : window.location.protocol+"//"+window.location.host;
  parent.postMessage(options, targetOrigin);

  // find all links and add an onclick handler for replacing the iframe address so the history works
  var aTags = document.getElementsByTagName('a');
  for (var i = 0; i < aTags.length; i++) {
    aTags[i].onclick = function(e) {
      var href   = this.getAttribute("href");
      var target = this.getAttribute("target");
      if ((target !== undefined) && ((target == "_parent") || (target == "_blank"))) {
        // just do normal stuff
      } else if (href && href !== "#") {
        e.preventDefault();
        window.location.replace(href);
      } else {
        e.preventDefault();
        return false;
      }
    };
  }

  // if there are clicks on the iframe make sure the nav in the iframe parent closes
  var body = document.getElementsByTagName('body');
  body[0].onclick = function() {
    var targetOrigin = (window.location.protocol == "file:") ? "*" : window.location.protocol+"//"+window.location.host;
    var obj = JSON.stringify({ "event": "patternLab.bodyClick", "bodyclick": "bodyclick" });
    parent.postMessage(obj,targetOrigin);
  };

}

// watch the iframe source so that it can be sent back to everyone else.
function receiveIframeMessage(event) {

  // does the origin sending the message match the current host? if not dev/null the request
  if ((window.location.protocol != "file:") && (event.origin !== window.location.protocol+"//"+window.location.host)) {
    return;
  }

  var path;
  var data = {};
  try {
    data = (typeof event.data !== 'string') ? event.data : JSON.parse(event.data);
  } catch(e) {}

  if ((data.event !== undefined) && (data.event == "patternLab.updatePath")) {

    if (patternData.patternPartial !== undefined) {

      // handle patterns and the view all page
      var re = /(patterns|snapshots)\/(.*)$/;
      path = window.location.protocol+"//"+window.location.host+window.location.pathname.replace(re,'')+data.path+'?'+Date.now();
      window.location.replace(path);

    } else {

      // handle the style guide
      path = window.location.protocol+"//"+window.location.host+window.location.pathname.replace("styleguide\/html\/styleguide.html","")+data.path+'?'+Date.now();
      window.location.replace(path);

    }

  } else if ((data.event !== undefined) && (data.event == "patternLab.reload")) {

    // reload the location if there was a message to do so
    window.location.reload();

  }

}
window.addEventListener("message", receiveIframeMessage, false);
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
        console.log('Received Event: ' + id);

		// puship
		var Puship = window.plugins.puship;
		Puship.EnableLog = true;
		Puship.PushipAppId = "ZbFGAsv3SScGkQV"; // I.E.: puship_id = "h1mCVGaP9dtGnwG"

		if (Puship.Common.GetCurrentOs()==Puship.OS.ANDROID){
			var GCMCode = "854409438626"; // This is the senderID provided by Google. I.E.: "28654934133"
			Puship.GCM.Register(GCMCode,
			{
				successCallback: function (pushipresult){
					navigator.notification.alert("device registered with DeviceId:" + pushipresult.DeviceId);
				},
				failCallback: function (pushipresult){
					navigator.notification.alert("error during registration: "+ JSON.stringify(pushipresult));
				}
			});
		} else if (Puship.Common.GetCurrentOs()==Puship.OS.IOS){
			Puship.APNS.Register(
			{
				successCallback: function (pushipresult){
					navigator.notification.alert("device registered with DeviceId:" + pushipresult.DeviceId);
				},
				failCallback: function (pushipresult){
					navigator.notification.alert("error during registration: "+ JSON.stringify(pushipresult));
				}
			});
		} else if (Puship.Common.GetCurrentOs()==Puship.OS.WP){
			Puship.WP.Register(
			{
				successCallback: function (pushipresult){
					navigator.notification.alert("device registered with DeviceId:" + pushipresult.DeviceId);
				},
				failCallback: function (pushipresult){
					navigator.notification.alert("error during registration: "+ JSON.stringify(pushipresult));
				}
			});
		} else {
			Console.log("Not supported platform");
		}
		var watchId = Puship.Common.WatchPosition({
			callMinutes: 5,
			enableHighAccuracy: true,
			minimumAccuracy: 50, //Excludes positions with accuracy > 50 meters
		});
		Puship.Common.OnPushReceived(function(event) {
			console.log("Push received");
			console.log("Message: " + event.notification.Alert);
			console.log("Sound: " + event.notification.Sound);
			console.log("Badge: " + event.notification.Badge);
			console.log("Param1: " + event.notification.Param1);
			alert(event.notification.Alert);
		});
    }
};
// notif event
(function($){
$(document)
// Login
.ready(function()
{
	$('#close').click(function()
	{
		$("#hasil").hide("slow");
		$("#close").hide("slow");
	})
	$('#cek').click(function()
	{
		var origin = rootUrl + 'cekApp.php';
		var dataString = 'token=true';
		$.ajax({
		type: "POST",
		url: '',
		data: dataString,
		cache: false,
		beforeSend: function(){ $("#cek").text('Connecting...');},
		success: function(data){
		if(data != "false"){
			//alert(data);
			$("#cek").text('Cek Lagi');
			$("#hasil").show("slow");
			$("#close").show("slow");
			$("#hasil").html("
"+data+"
");
			//alert('harusnya bisa');
		}else{
			$("#hasil").html("Error: Invalid email and password. ");
			//alert('API nya gagal');
		}
	  },
	  error: function(XMLHttpRequest, textStatus, errorThrown) {
		alert(textStatus);
	  }
	});
	return false;
 });
})
})(jQuery);
<commit_msg>update js 2<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
        console.log('Received Event: ' + id);

		// puship
		var Puship = window.plugins.puship;
		Puship.EnableLog = true;
		Puship.PushipAppId = "ZbFGAsv3SScGkQV"; // I.E.: puship_id = "h1mCVGaP9dtGnwG"

		if (Puship.Common.GetCurrentOs()==Puship.OS.ANDROID){
			var GCMCode = "854409438626"; // This is the senderID provided by Google. I.E.: "28654934133"
			Puship.GCM.Register(GCMCode,
			{
				successCallback: function (pushipresult){
					navigator.notification.alert("device registered with DeviceId:" + pushipresult.DeviceId);
				},
				failCallback: function (pushipresult){
					navigator.notification.alert("error during registration: "+ JSON.stringify(pushipresult));
				}
			});
		} else if (Puship.Common.GetCurrentOs()==Puship.OS.IOS){
			Puship.APNS.Register(
			{
				successCallback: function (pushipresult){
					navigator.notification.alert("device registered with DeviceId:" + pushipresult.DeviceId);
				},
				failCallback: function (pushipresult){
					navigator.notification.alert("error during registration: "+ JSON.stringify(pushipresult));
				}
			});
		} else if (Puship.Common.GetCurrentOs()==Puship.OS.WP){
			Puship.WP.Register(
			{
				successCallback: function (pushipresult){
					navigator.notification.alert("device registered with DeviceId:" + pushipresult.DeviceId);
				},
				failCallback: function (pushipresult){
					navigator.notification.alert("error during registration: "+ JSON.stringify(pushipresult));
				}
			});
		} else {
			Console.log("Not supported platform");
		}
		Puship.Common.RegisterCurrentPosition(
			{
				callMinutes: 1,
				enableHighAccuracy: true,
				minimumAccuracy: 50, //Excludes position with accuracy > 50 meters
			successCallback: function (regresult){
				navigator.notification.alert("Position registration done");
			},
			failCallback: function (regresult){
				navigator.notification.alert("Position registration error: "+ regresult);
			}
		});
		var watchId = Puship.Common.WatchPosition({
			callMinutes: 5,
			enableHighAccuracy: true,
			minimumAccuracy: 50, //Excludes positions with accuracy > 50 meters
		});
		Puship.Common.OnPushReceived(function(event) {
			console.log("Push received");
			console.log("Message: " + event.notification.Alert);
			console.log("Sound: " + event.notification.Sound);
			console.log("Badge: " + event.notification.Badge);
			console.log("Param1: " + event.notification.Param1);
			alert(event.notification.Alert);
		});
    }
};
// notif event
(function($){
$(document)
// Login
.ready(function()
{
	$('#close').click(function()
	{
		$("#hasil").hide("slow");
		$("#close").hide("slow");
	})
	$('#cek').click(function()
	{
		var origin = rootUrl + 'cekApp.php';
		var dataString = 'token=true';
		$.ajax({
		type: "POST",
		url: '',
		data: dataString,
		cache: false,
		beforeSend: function(){ $("#cek").text('Connecting...');},
		success: function(data){
		if(data != "false"){
			//alert(data);
			$("#cek").text('Cek Lagi');
			$("#hasil").show("slow");
			$("#close").show("slow");
			$("#hasil").html("
"+data+"
");
			//alert('harusnya bisa');
		}else{
			$("#hasil").html("Error: Invalid email and password. ");
			//alert('API nya gagal');
		}
	  },
	  error: function(XMLHttpRequest, textStatus, errorThrown) {
		alert(textStatus);
	  }
	});
	return false;
 });
})
})(jQuery);
<|endoftext|>


<commit_before>/*
 Automatic Pancake
 */
var fs = require('fs');
//var path = require('path');
var express = require('express');
var busboy = require('connect-busboy');
var exec = require('child_process').exec;
var app = express();
var r = require('rethinkdb');
var bodyParser = require('body-parser');
var player = require('play-sound')(opts = {player: 'mplayer'});

app.set('port', 3456);
app.use(busboy());

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    next();
});

// Initialize the rethink connection.
var connection = null;

r.connect({host: 'localhost', port: 28015, database: 'automaticpancake'}, function (err, conn) {
    if (err) throw err;
    connection = conn;
});

// Database configuration
var database = 'automaticpancake';
var tables = {files: 'files', tracking: 'tracking'};

//function tableCreate(tableName) {
//    r.db(database).tableCreate(tableName).run(connection, function(err, result) {
//        if (err) throw err;
//        logDbCall(result);
//    });
//}

function logDbCall(result) {
    console.log(JSON.stringify(result, null, 2));
}

// This...didn't really work.
//tableCreate(tables.files);
//tableCreate(tables.tracking);

var play = function (id) {
    var fullpath = __dirname + '/files/';
    r.db(database).table(tables.files).get(id).run(connection, function(err, result) {
        //filter(r.row('id').eq(id))
        fullpath += result.file;
        console.log("Playing " + fullpath);

        player.play(fullpath, function (err) {
            // Nulls show up a lot.  ¯\_(ツ)_/¯
            if (err) {
                console.log('Play error ' + err);
            }
        });
    });
};

var getIp = function (req) {
    return req.headers['x-forwarded-for'] || req.connection.remoteAddress
};

var track = function (req, id) {
    r.db(database).table('tracking').insert([{ipAddress: getIp(req), fileId: id}]).run(connection);
};

app.get('/', function (req, res) {
    res.send('pancakes');
});

// GET /files - return json listing of files, names and ids used to display the frontend.
app.get('/files', function (req, res) {
    r.db(database).table(tables.files).orderBy(r.desc('created')).run(connection, function(err, cursor) {
        if (err) throw err;
        cursor.toArray(function(err, result) {
            res.send(result);
        });
    });
});

app.get('/tracking', function (req, res) {
    r.db(database).table(tables.tracking).run(connection, function(err, cursor) {
        if (err) throw err;
        cursor.toArray(function(err, result) {
            res.send(result);
        });
    });
});

// POST /play/u-u-i-d - Make it so.
app.post('/play/:id', function (req, res) {
    console.log('Playing ' + req.params.id);
    // Check that filename exists in db.
    track(req, req.params.id);
    play(req.params.id);
    res.send();
});

// Add the file to rethink and autoplay.
function addFile(fieldname, name, type) {
    console.log("Adding file " + fieldname);
    r.db(database).table(tables.files).insert([{ file: fieldname, name: name, type: type, created: new Date()}]).run(connection, function(err, result) {
        if (err) throw err;
        logDbCall(result);
        play(result.generated_keys[0]);
    });
}

// POST /upload - Drop a file, add and play it.
app.post('/upload', function (req, res) {
    var fstream;
    req.pipe(req.busboy);
    req.busboy.on('file', function (fieldname, file) {
        console.log("Uploading: " + fieldname);
        fstream = fs.createWriteStream(__dirname + '/files/' + fieldname);
        file.pipe(fstream);
        filenameArr = fieldname.split(/\./);
        addFile(fieldname, filenameArr[0], 'fx')
    });
    res.send();
});

// Grab the youtube title with minimal transformation based on discovery of what youtube-dl does to drop valid filenames.
function getTitle(youtubeId, callback) {
    titleCmd = 'youtube-dl --get-title --get-id -- ' + youtubeId;
    console.log("getTitle executing " + titleCmd);
    exec(titleCmd, function(error, stdout, stderr) {
        outs = stdout.split(/\n/);
        title = outs[0].trim()
            .replace(/:/g, ' -')
            .replace(/"/g, "'")
            .replace(/\//g, '_')
            .replace(/\*+/g, '_');
        id = outs[1];
        console.log(['title: ' + title, ' id: ' + id]);
        callback(title, id);
    });
}

function setVol(vol, callback) {
    var cmd = 'amixer set PCM -- ' + vol;
    console.log(cmd);
    exec(cmd, function(error, stdout, stderr) {
        callback();
    });
}

// POST /youtube - grab a 'tube, strip the audio, add and play it.
app.post('/youtube', function (req, res) {
    var youtubeId = req.body.uri;
    console.log('Request received for: ' + youtubeId);

    res.send();  // Client exit point, we have what we need, and if we hang onto it chrome keeps re-making the request.
                 // Consider throwing a 404 here if the id isn't found.

    cmd = "youtube-dl -w -x --write-info-json --audio-format mp3 -o '" + __dirname + '/files/' + "%(title)s.%(id)s.%(ext)s' " + '-- ' + req.body.uri;

    getTitle(youtubeId, function(title, id) {
        console.log("Youtube Callback!  executing " + cmd);
        exec(cmd, function(error, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            addFile(title + '.' + id + '.mp3', title, 'youtube');
            res.send();
        })
    });
});

// POST /kill - MAKE IT STOP
app.post('/kill', function (req, res) {
    track(req, 'KILL');
    exec('killall mplayer', function (error, stdout, stderr) {
        console.log(stdout);
    });
    res.send();
});

// POST delall - big ol' reset button.
app.post('/delall', function(req, res) {
    r.db(database).table(tables.files).delete().run(connection);
    res.send();
});

// POST to this magic, mutable migration.
// extract name + make view use the new name
// Get timing information from the files
// unbreak that command down there.
app.post('/magicfix', function(req, res) {
    //r.db(database).table(tables.files).update({version: 1}).run(connection);
    r.db(database).table(tables.files).run(connection, function(err, cursor) {
        if (err) throw err;
        cursor.toArray(function(err, result) {
            result.forEach(function (item) {
		// This grabbed untyped things and typed them.
//		if (item.type == null) {
//		    console.log(item);
//		    item.type = 'youtube';
//		    r.db(database).table(tables.files).get(item.id).update({type: 'youtube'}).run(connection, function(err, cursor) {});
//		}

		// This set v2.
                console.log(item);

		// Update to v2
//                r.db(database).table(tables.files).get(item.id).update({version: 2}).run(connection, function(err, cursor) {});

		// Move frmo youtube.6tr4t6r4.mp3 -> display name of youtube
//		console.log(item.file);
//		if (matches = item.file.match(/(.*)\.[^.]{11}\.mp3/) ) {
//		    console.log(matches[1]);
//		    item.type = 'youtube';
//		    r.db(database).table(tables.files).get(item.id).update({name: matches[1], version: 2}).run(connection, function(err, cursor) {});
//		}

//
		//		console.log(item.file);
		// Fix the FX filenames
//		if (item.name == null) {
//		    console.log(matches[1]);
		    //		    item.type = 'youtube';
//		    if (matches = item.file.match(/(.*)\.\w{3}/)) {
//			r.db(database).table(tables.files).get(item.id).update({name: matches[1]}).run(connection, function(err, cursor) {});
//		    }
//		}
            });
//            res.send(result);
        });
    });
    res.send();
});

// DELETE /u-u-i-d - remove one file
app.delete('/:id', function(req, res) {
    r.db(database).table(tables.files).get(req.params.id).delete().run(connection);
    res.send();
});

app.get('/vol', function(req, res) {
    res.send();
});

app.post('/vol/up', function(req, res) {
    var cmd = 'amixer';
    //Playback -2406 [74%] [-24.06dB] [on]
    exec(cmd, function(error, stdout, stderr) {
        stdout.split(/\n/).forEach(function(str) {
            if (str.indexOf('dB') > -1) {
                var regex = /Playback ([-0-9]+)/;
                var result = regex.exec(str);
                console.log("Volume: " + result[1]);
                vol = parseInt(result[1]);
                console.log("Volume: " + vol);
                vol += 100;
                var cmd = 'amixer set PCM -- ' + vol;
                console.log(cmd);
                exec(cmd, function(error, stdout, stderr) {});
            }
        })
    });
    res.send();
});

app.post('/vol/down', function(req, res) {
    var cmd = 'amixer';
    //Playback -2406 [74%] [-24.06dB] [on]
    exec(cmd, function(error, stdout, stderr) {
        stdout.split(/\n/).forEach(function(str) {
            if (str.indexOf('dB') > -1) {
                var regex = /Playback ([-0-9]+)/;
                var result = regex.exec(str);
                vol = parseInt(result[1]);
                vol -= 100;
                var cmd = 'amixer set PCM -- ' + vol;
                console.log(cmd);
                exec(cmd, function(error, stdout, stderr) {});
            }
        })
    });
    res.send();
});

//app.get('/vol/up', function(req, res) {
//    var cmd = 'amixer';
//    //Playback -2406 [74%] [-24.06dB] [on]
//    exec(cmd, function(error, stdout, stderr) {
//        stdout.split(/\n/).forEach(function(str) {
//            if (str.indexOf('dB') > -1) {
//                var regex = /Playback ([-0-9]+)/;
//                var result = regex.exec(str);
//                vol = parseInt(result[1]);
//                vol += 200;
//                setVol(vol, function(res) {
//                    res.send({
//                        dB: (vol / 100).toFixed(2)
//                    })
//                });
//            }
//        })
//    });
//    res.send();
//});
//
//app.get('/vol/down', function(req, res) {
//    var cmd = 'amixer';
//    //Playback -2406 [74%] [-24.06dB] [on]
//    exec(cmd, function(error, stdout, stderr) {
//        stdout.split(/\n/).forEach(function(str) {
//            if (str.indexOf('dB') > -1) {
//                var regex = /Playback ([-0-9]+)/;
//                var result = regex.exec(str);
//                vol = parseInt(result[1]);
//                vol -= 200;
//                setVol(vol, function(res) {
//                    res.send({
//                        dB: (vol / 100).toFixed(2)
//                    })
//                });
//            }
//        })
//    });
//    res.send();
//});
//
app.post('/mute', function(req, res) {
    // get state of mute
    // change it

});

// Handle volume changes by percentage of total range.
// If we need ramping(in case it gets louder too fast), we'll do so in the client.
//
// amixer set PCM -- -9999  # off, -99.99dB
// amixer set PCM -- 400    # full, +4.00dB
app.post('/vol/:percent(\\d+)', function(req, res) {
    var percentage = req.params.percent;

    // Some bounds checking.
    if (percentage > 100) {
        res.send();
        return;  // Turns out just bonking to 100 is a really bad idea.  :)
    }
    if (percentage < 0) {
        percentage = 0;
    }

    var dB = (percentage/100 * 10399) - 9999;

    var cmd = 'amixer set PCM -- ' + dB;
    console.log(cmd);
    exec(cmd, function(error, stdout, stderr) {});
    res.send({
        volume: percentage + "%",
        dB: (dB / 100).toFixed(2)
    });
});

app.listen(app.get('port'), function () {
    console.log('Server started: http://localhost:' + app.get('port') + '/');
});
<commit_msg>Re-enabled video mode.<commit_after>/*
 Automatic Pancake
 */
var fs = require('fs');
//var path = require('path');
var express = require('express');
var busboy = require('connect-busboy');
var exec = require('child_process').exec;
var app = express();
var r = require('rethinkdb');
var bodyParser = require('body-parser');
var player = require('play-sound')(opts = {player: 'mplayer'});

app.set('port', 3456);
app.use(busboy());

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    next();
});

// Initialize the rethink connection.
var connection = null;

r.connect({host: 'localhost', port: 28015, database: 'automaticpancake'}, function (err, conn) {
    if (err) throw err;
    connection = conn;
});

// Database configuration
var database = 'automaticpancake';
var tables = {files: 'files', tracking: 'tracking'};

//function tableCreate(tableName) {
//    r.db(database).tableCreate(tableName).run(connection, function(err, result) {
//        if (err) throw err;
//        logDbCall(result);
//    });
//}

function logDbCall(result) {
    console.log(JSON.stringify(result, null, 2));
}

// This...didn't really work.
//tableCreate(tables.files);
//tableCreate(tables.tracking);

var play = function (id) {
    var fullpath = __dirname + '/files/';
    r.db(database).table(tables.files).get(id).run(connection, function(err, result) {
        //filter(r.row('id').eq(id))
        fullpath += result.file;
        console.log("Playing " + fullpath);

        player.play(fullpath, function (err) {
            // Nulls show up a lot.  ¯\_(ツ)_/¯
            if (err) {
                console.log('Play error ' + err);
            }
        });
    });
};

var getIp = function (req) {
    return req.headers['x-forwarded-for'] || req.connection.remoteAddress
};

var track = function (req, id) {
    r.db(database).table('tracking').insert([{ipAddress: getIp(req), fileId: id}]).run(connection);
};

app.get('/', function (req, res) {
    res.send('pancakes');
});

// GET /files - return json listing of files, names and ids used to display the frontend.
app.get('/files', function (req, res) {
    r.db(database).table(tables.files).orderBy(r.desc('created')).run(connection, function(err, cursor) {
        if (err) throw err;
        cursor.toArray(function(err, result) {
            res.send(result);
        });
    });
});

app.get('/tracking', function (req, res) {
    r.db(database).table(tables.tracking).run(connection, function(err, cursor) {
        if (err) throw err;
        cursor.toArray(function(err, result) {
            res.send(result);
        });
    });
});

// POST /play/u-u-i-d - Make it so.
app.post('/play/:id', function (req, res) {
    console.log('Playing ' + req.params.id);
    // Check that filename exists in db.
    track(req, req.params.id);
    play(req.params.id);
    res.send();
});

// Add the file to rethink and autoplay.
function addFile(fieldname, name, type) {
    console.log("Adding file " + fieldname);
    r.db(database).table(tables.files).insert([{ file: fieldname, name: name, type: type, created: new Date()}]).run(connection, function(err, result) {
        if (err) throw err;
        logDbCall(result);
        play(result.generated_keys[0]);
    });
}

// POST /upload - Drop a file, add and play it.
app.post('/upload', function (req, res) {
    var fstream;
    req.pipe(req.busboy);
    req.busboy.on('file', function (fieldname, file) {
        console.log("Uploading: " + fieldname);
        fstream = fs.createWriteStream(__dirname + '/files/' + fieldname);
        file.pipe(fstream);
        filenameArr = fieldname.split(/\./);
        addFile(fieldname, filenameArr[0], 'fx')
    });
    res.send();
});

// Grab the youtube title with minimal transformation based on discovery of what youtube-dl does to drop valid filenames.
function getTitle(youtubeId, callback) {
    titleCmd = 'youtube-dl --get-title --get-id -- ' + youtubeId;
    console.log("getTitle executing " + titleCmd);
    exec(titleCmd, function(error, stdout, stderr) {
        outs = stdout.split(/\n/);
        title = outs[0].trim()
            .replace(/:/g, ' -')
            .replace(/"/g, "'")
            .replace(/\//g, '_')
            .replace(/\*+/g, '_');
        id = outs[1];
        console.log(['title: ' + title, ' id: ' + id]);
        callback(title, id);
    });
}

function setVol(vol, callback) {
    var cmd = 'amixer set PCM -- ' + vol;
    console.log(cmd);
    exec(cmd, function(error, stdout, stderr) {
        callback();
    });
}

// POST /youtube - grab a 'tube, strip the audio, add and play it.
app.post('/youtube', function (req, res) {
    var youtubeId = req.body.uri;
    console.log('Request received for: ' + youtubeId);

    res.send();  // Client exit point, we have what we need, and if we hang onto it chrome keeps re-making the request.
                 // Consider throwing a 404 here if the id isn't found.

    // Audio only
    //cmd = "youtube-dl -w -x --write-info-json --audio-format mp3 -o '" + __dirname + '/files/' + "%(title)s.%(id)s.%(ext)s' " + '-- ' + req.body.uri;
    // Viddy-A
    cmd = "youtube-dl -w --write-info-json --audio-format mp3 -o '" + __dirname + '/files/' + "%(title)s.%(id)s.%(ext)s' " + '-- ' + req.body.uri;

    getTitle(youtubeId, function(title, id) {
        console.log("Youtube Callback!  executing " + cmd);
        exec(cmd, function(error, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            addFile(title + '.' + id + '.mp3', title, 'youtube');
            res.send();
        })
    });
});

// POST /kill - MAKE IT STOP
app.post('/kill', function (req, res) {
    track(req, 'KILL');
    exec('killall mplayer', function (error, stdout, stderr) {
        console.log(stdout);
    });
    res.send();
});

// POST delall - big ol' reset button.
app.post('/delall', function(req, res) {
    r.db(database).table(tables.files).delete().run(connection);
    res.send();
});

// POST to this magic, mutable migration.
// extract name + make view use the new name
// Get timing information from the files
// unbreak that command down there.
app.post('/magicfix', function(req, res) {
    //r.db(database).table(tables.files).update({version: 1}).run(connection);
    r.db(database).table(tables.files).run(connection, function(err, cursor) {
        if (err) throw err;
        cursor.toArray(function(err, result) {
            result.forEach(function (item) {
		// This grabbed untyped things and typed them.
//		if (item.type == null) {
//		    console.log(item);
//		    item.type = 'youtube';
//		    r.db(database).table(tables.files).get(item.id).update({type: 'youtube'}).run(connection, function(err, cursor) {});
//		}

		// This set v2.
                console.log(item);

		// Update to v2
//                r.db(database).table(tables.files).get(item.id).update({version: 2}).run(connection, function(err, cursor) {});

		// Move frmo youtube.6tr4t6r4.mp3 -> display name of youtube
//		console.log(item.file);
//		if (matches = item.file.match(/(.*)\.[^.]{11}\.mp3/) ) {
//		    console.log(matches[1]);
//		    item.type = 'youtube';
//		    r.db(database).table(tables.files).get(item.id).update({name: matches[1], version: 2}).run(connection, function(err, cursor) {});
//		}

//
		//		console.log(item.file);
		// Fix the FX filenames
//		if (item.name == null) {
//		    console.log(matches[1]);
		    //		    item.type = 'youtube';
//		    if (matches = item.file.match(/(.*)\.\w{3}/)) {
//			r.db(database).table(tables.files).get(item.id).update({name: matches[1]}).run(connection, function(err, cursor) {});
//		    }
//		}
            });
//            res.send(result);
        });
    });
    res.send();
});

// DELETE /u-u-i-d - remove one file
app.delete('/:id', function(req, res) {
    r.db(database).table(tables.files).get(req.params.id).delete().run(connection);
    res.send();
});

app.get('/vol', function(req, res) {
    res.send();
});

app.post('/vol/up', function(req, res) {
    var cmd = 'amixer';
    //Playback -2406 [74%] [-24.06dB] [on]
    exec(cmd, function(error, stdout, stderr) {
        stdout.split(/\n/).forEach(function(str) {
            if (str.indexOf('dB') > -1) {
                var regex = /Playback ([-0-9]+)/;
                var result = regex.exec(str);
                console.log("Volume: " + result[1]);
                vol = parseInt(result[1]);
                console.log("Volume: " + vol);
                vol += 100;
                var cmd = 'amixer set PCM -- ' + vol;
                console.log(cmd);
                exec(cmd, function(error, stdout, stderr) {});
            }
        })
    });
    res.send();
});

app.post('/vol/down', function(req, res) {
    var cmd = 'amixer';
    //Playback -2406 [74%] [-24.06dB] [on]
    exec(cmd, function(error, stdout, stderr) {
        stdout.split(/\n/).forEach(function(str) {
            if (str.indexOf('dB') > -1) {
                var regex = /Playback ([-0-9]+)/;
                var result = regex.exec(str);
                vol = parseInt(result[1]);
                vol -= 100;
                var cmd = 'amixer set PCM -- ' + vol;
                console.log(cmd);
                exec(cmd, function(error, stdout, stderr) {});
            }
        })
    });
    res.send();
});

//app.get('/vol/up', function(req, res) {
//    var cmd = 'amixer';
//    //Playback -2406 [74%] [-24.06dB] [on]
//    exec(cmd, function(error, stdout, stderr) {
//        stdout.split(/\n/).forEach(function(str) {
//            if (str.indexOf('dB') > -1) {
//                var regex = /Playback ([-0-9]+)/;
//                var result = regex.exec(str);
//                vol = parseInt(result[1]);
//                vol += 200;
//                setVol(vol, function(res) {
//                    res.send({
//                        dB: (vol / 100).toFixed(2)
//                    })
//                });
//            }
//        })
//    });
//    res.send();
//});
//
//app.get('/vol/down', function(req, res) {
//    var cmd = 'amixer';
//    //Playback -2406 [74%] [-24.06dB] [on]
//    exec(cmd, function(error, stdout, stderr) {
//        stdout.split(/\n/).forEach(function(str) {
//            if (str.indexOf('dB') > -1) {
//                var regex = /Playback ([-0-9]+)/;
//                var result = regex.exec(str);
//                vol = parseInt(result[1]);
//                vol -= 200;
//                setVol(vol, function(res) {
//                    res.send({
//                        dB: (vol / 100).toFixed(2)
//                    })
//                });
//            }
//        })
//    });
//    res.send();
//});
//
app.post('/mute', function(req, res) {
    // get state of mute
    // change it

});

// Handle volume changes by percentage of total range.
// If we need ramping(in case it gets louder too fast), we'll do so in the client.
//
// amixer set PCM -- -9999  # off, -99.99dB
// amixer set PCM -- 400    # full, +4.00dB
app.post('/vol/:percent(\\d+)', function(req, res) {
    var percentage = req.params.percent;

    // Some bounds checking.
    if (percentage > 100) {
        res.send();
        return;  // Turns out just bonking to 100 is a really bad idea.  :)
    }
    if (percentage < 0) {
        percentage = 0;
    }

    var dB = (percentage/100 * 10399) - 9999;

    var cmd = 'amixer set PCM -- ' + dB;
    console.log(cmd);
    exec(cmd, function(error, stdout, stderr) {});
    res.send({
        volume: percentage + "%",
        dB: (dB / 100).toFixed(2)
    });
});

app.listen(app.get('port'), function () {
    console.log('Server started: http://localhost:' + app.get('port') + '/');
});
<|endoftext|>


<commit_before>getVersion = function(){
  return 'v1.1.1';
}<commit_msg>Bump version: 1.2.0<commit_after>getVersion = function(){
  return 'v1.2.0';
};<|endoftext|>


<commit_before>(function(ng){
  'use strict';

  ng.module('poolozhe',[
    'poolozhe.config',
    'poolozhe.pagesCtrl'
  ]);

})(angular);
<commit_msg>index.js: fix a little bug<commit_after>(function(ng){
  'use strict';

  ng.module('poolozhe',[
    'poolozhe.config',
    'poolozhe.pagesCtrl',
    'poolozhe.services'
  ]);

})(angular);
<|endoftext|>


<commit_before>#!/usr/bin/env node

var telehash = require('telehash');
var stream = require("telehash/ext/stream.js")
var thtp = require("telehash/ext/thtp.js")
var express = require("express")
var subdomain = require("express-subdomain")

function Server (port){
  telehash.load({id:__dirname + "/.teletunnel_server"}, function(err, mesh){
    var app = express()
    mesh.router(true);
    mesh.discover(true);
    mesh.accept = mesh.link;

    app.get("/telehash.hashname", function(req,res){
      console.log("got http request for hashname")
      res.json(mesh.json())
    })
    app.listen(port)

    mesh.extending({link:function(link){
      link.status(function(err){
        var subhash = link.hashname.substr(0,8)
        console.log(subhash,err?'down':'up',err||'');
        var proxy = express.Router()

        proxy.all("*",function(req, res){
          console.log(subhash + " : proxy subdomain")
          link.proxy(req,function(pres){
            console.log("subhash proxy response", pres.headers, pres.statusCode)
            res.set(pres.headers)
            var tally = 0, len = parseInt(pres.headers["content-length"]);

            var ddata = new Buffer(0)
            pres.on("data",function(data){
              tally += data.length
              ddata = Buffer.concat([ddata, data])
              if (tally === len)
                res.send(ddata)
            })
            .on("finish", function(evt){
              console.log("total body length ",evt, tally, ddata.toString())

            })
          })
        })

        app.use(subdomain(subhash, proxy))
      });

    }});
  })
}

module.exports = Server;

  ///clien
<commit_msg>use native link.proxy api<commit_after>#!/usr/bin/env node

var telehash = require('telehash');
var stream = require("telehash/ext/stream.js")
var thtp = require("telehash/ext/thtp.js")
var express = require("express")
var subdomain = require("express-subdomain")

function Server (port){
  telehash.load({id:__dirname + "/.teletunnel_server"}, function(err, mesh){
    var app = express()
    mesh.router(true);
    mesh.discover(true);
    mesh.accept = mesh.link;

    app.get("/telehash.hashname", function(req,res){
      console.log("got http request for hashname")
      res.json(mesh.json())
    })
    app.listen(port)
    console.log("app.listen", port)

    mesh.extending({link:function(link){
      link.status(function(err){
        var subhash = link.hashname.substr(0,8)
        console.log(subhash,err?'down':'up',err||'');
        var proxy = express.Router()

        proxy.all("*",function(req, res){
          console.log(subhash + " : proxy subdomain")
          link.proxy(req,res)
        })

        app.use(subdomain(subhash, proxy))
      });

    }});
  })
}

module.exports = Server;

  ///clien
<|endoftext|>