<commit_before>$(document).ready(function () {
    if (!window.jQuery) {
    } else {
        /** Do not touch this **/
        let path = $("#main-table").attr("data-path");
        let $factory = $('#archive_entry_search_form_factory');
        let searchForm = $("#archive_entry_search_form");
        let resetButton = $("#archive_entry_search_form_resetButton");
        let createFolderBlock = $("#addFolder");
        let uploadFileBlock = $("#addFile");
        let downloadFileBlock = $("#downloadFile");

        /** Seriously, it'a a bad idea  :) **/

        /** Archive entries main table factory->settings AJAX loader **/

        $factory.on("change", function settingsLoadAction() {
            let data = {};
            data[$factory.attr('name')] = $factory.val();
            $.ajax({
                url: path,
                method: searchForm.attr('method'),
                data: data,
                success: function (response) {
                    $('#archive_entry_search_form_setting').replaceWith(
                        $(response).find('#archive_entry_search_form_setting')
                    );
                }
            });

            return false;
        });

        /** Archive entries main table content AJAX loader **/

        searchForm.on("submit", function searchAction(event) {
            event.preventDefault();
            let fields = searchForm.serializeArray();
            let values = {};
            jQuery.each(fields, function (i, field) {
                values[field.name] = field.value;
            });
            $.ajax({
                url: path,
                method: searchForm.attr('method'),
                data: values,
                success: function (response) {
                    $('#main-tbody').replaceWith(
                        $(response).find('#main-tbody')
                    );
                }
            });

            return false;
        });

        /** Archive entries main table search form reset to default stdout AJAX loader **/

        resetButton.on("click", function resetAction() {
            searchForm.trigger('reset');
            $.ajax({
                url: path,
                method: searchForm.attr('method'),
                data: null,
                success: function (response) {
                    $('#main-tbody').replaceWith(
                        $(response).find('#main-tbody'));
                    $('#archive_entry_search_form_setting').attr('disabled', 'disabled');
                    $('#addFolder').hide();
                }
            });

            return false;
        });

        /** Archive entries content loader **/

        $(document).on("click", "a[name='entryId']", openEntryContents);

        function openEntryContents() {
            let entryId = $(this).parent().attr("id");
            let contentPlace = $('#entryContent_' + entryId);
            if ($(contentPlace).is(":hidden")) {
                $.ajax({
                    url: "view",
                    method: searchForm.attr('method'),
                    data: {entryId: entryId},
                    success: function (response) {
                        contentPlace.html($(response));
                        loadLastUpdateInfo(entryId, null);
                        let folderId = contentPlace.find('#rootEntry').children('td').attr('id');
                        openFolder(folderId);
                        contentPlace.show();
                    }
                });
            }
            else {
                $(contentPlace).hide();
            }

            return false;
        }

        /** Archive entries content navigation **/

        $(document).on("click", "a[name='openFolder']", function ()
        {
            let folderId = $(this).attr("id");
            openFolder(folderId);

            return false;
        });

        function openFolder(folderId) {
            let folderContent = $('#folderContent_' + folderId);
            let fileContent = $('#fileContent_' + folderId);
            if ($(folderContent).is(":hidden")) {
                $.ajax({
                    url: "view_folders",
                    method: "POST",
                    data: {folderId: folderId},
                    success: function (response) {
                        folderContent.html(response);
                        loadLastUpdateInfo(null, folderId);
                    }
                });
                $.ajax({
                    url: "view_files",
                    method: "POST",
                    data: {folderId: folderId},
                    success: function (response) {
                        fileContent.html(response);
                    }
                });
                folderContent.show();
                fileContent.show();
            }
            else {
                folderContent.hide();
                fileContent.hide();
            }

            return false;
        }

        /** Archive entries folder creation with form loader **/

        $(document).on("click", 'a[name="addFolder"]', createFolder);

        function createFolder() {
            let entryId = $(this).attr("id");
            /** Load folder creation form **/
            $.ajax({
                url: "new_folder",
                method: searchForm.attr('mehtod'),
                data: {entryId: entryId},
                success: function (loadFormResponse) {
                    createFolderBlock.html($(loadFormResponse));
                    createFolderBlock.show();
                    let $folderAddForm = createFolderBlock.find('#folder_add_form');
                    $folderAddForm.on("submit", function createFolder(event) {
                        event.preventDefault();
                        let folderSerialized = $folderAddForm.serialize();
                        /** Submit new folder **/
                        $.ajax({
                            url: "new_folder",
                            method: $folderAddForm.attr('method'),
                            data: folderSerialized,
                            success: function () {
                                createFolderBlock.hide();
                                let folderId = $folderAddForm.find('select[id="folder_add_form_parentFolder"]').val();
                                let folderContent = $('#folderContent_' + folderId);
                                /** Reload folder view order **/
                                $.ajax({
                                    url: "view_folders",
                                    method: searchForm.attr('method'),
                                    data: {folderId: folderId},
                                    success: function (reloadResponse) {
                                        // @TODO: create proper design
                                        folderContent.hide();
                                        //openFolder(folderId);
                                        folderContent.html(reloadResponse);
                                        folderContent.show();
                                        loadLastUpdateInfo(null, folderId);
                                    }
                                });
                                loadFlashMessages();
                            }
                        });
                    });
                }
            });

            return false;
        }

        /** Archive entries file upload with form loader **/

        $(document).on("click", 'a[name="addFile"]', uploadFile);

        function uploadFile() {
            let entryId = $(this).attr("id");
            /** Load file upload form **/
            $.ajax({
                url: "new_file",
                method: searchForm.attr('mehtod'),
                data: {entryId: entryId},
                success: function (loadFormResponse) {
                    uploadFileBlock.html($(loadFormResponse));
                    uploadFileBlock.show();
                    let $fileAddForm = uploadFileBlock.find('#file_add_form');
                    $fileAddForm.on("submit", function uploadFile(event) {
                        event.preventDefault();
                        //var fileSerialized = $fileAddForm.serialize();
                        let fileSerialized = new FormData($(this)[0]);
                        /** Submit new file **/
                        $.ajax({
                            url: "new_file",
                            method: $fileAddForm.attr('method'),
                            data: fileSerialized,
                            processData: false,
                            contentType: false,
                            success: function () {
                                uploadFileBlock.hide();
                                let folderId = $fileAddForm.find('select[id="file_add_form_parentFolder"]').val();
                                let folderContent = $('#folderContent_' + folderId);
                                let fileContent = $('#fileContent_' + folderId);
                                /** Reload folder view order **/
                                $.ajax({
                                    url: "view_files",
                                    method: searchForm.attr('method'),
                                    data: {folderId: folderId},
                                    success: function (reloadResponse) {
                                        // @TODO: create proper design
                                        fileContent.hide();
                                        //folderContent.hide();
                                        //openFolder(folderId);
                                        fileContent.html(reloadResponse);
                                        fileContent.show();
                                        loadLastUpdateInfo(null, folderId);
                                    }
                                });
                                /** Load flash messages **/
                                loadFlashMessagesSummary();
                            }
                        });
                    });
                }
            });

            return false;
        }

        /** Archive entries file download with md5 verification **/

        $(document).on("click", 'a[name="downloadFile"]', downloadFile);

        function downloadFile() {
            let fileId = $(this).attr("id");
            /** Load file download block **/
            $.ajax({
                url: "download_file",
                method: "POST",
                data: {fileId: fileId},
                success: function (downloadBlockResponse) {
                    downloadFileBlock.html($(downloadBlockResponse));
                    downloadFileBlock.show();
                }
            });
            let fileInfo = $('#file_' + fileId);
            $.ajax({
                url: "reload_file",
                method: "POST",
                data: {fileId: fileId},
                success: function (reloadFileInfo) {
                    fileInfo.replaceWith(reloadFileInfo);
                }
            });

            return false;
        }

        /** Last entry update information load & refresh **/

        function loadLastUpdateInfo(entryId, folderId) {
            if (entryId !== null) {
                $.ajax({
                    url: "last_update_info",
                    method: "POST",
                    data: {entryId: entryId},
                    success: function (reloadLastUpdateInfo) {
                        $($('#entryContent_' + entryId).find('#last-update')).html(reloadLastUpdateInfo);
                    }
                });
            }
            else if (folderId !== null) {
                $.ajax({
                        url: "get_folder_entryId",
                        method: "POST",
                        data: {folderId: folderId},
                        success: function (entryId) {
                            $.ajax({
                                url: "last_update_info",
                                method: "POST",
                                data: {folderId: folderId},
                                success: function (reloadLastUpdateInfo) {
                                    $($('#entryContent_' + entryId).find('#last-update')).html(reloadLastUpdateInfo);
                                }
                            });
                        }
                    }
                );
            }

            return false;
        }

        /** Archive entries file removal action **/

        $(document).on("click", 'a[name="removeFile"]', removeFile);

        function removeFile() {
            let fileId = $(this).attr("id");
            $.ajax({
                url: "remove_file",
                method: "POST",
                data: {fileId: fileId},
                success: function (fileRemoval) {
                    $('#file_' + fileId).replaceWith(fileRemoval);
                }
            });

            return false;
        }

        /** Archive entries file restore action **/

        $(document).on("click", 'a[name="restoreFile"]', restoreFile);

        function restoreFile() {
            let fileId = $(this).attr("id");
            $.ajax({
                url: "restore_file",
                method: "POST",
                data: {fileId: fileId},
                success: function (fileRestoration) {
                    $('#file_' + fileId).replaceWith(fileRestoration);
                }
            });

            return false;
        }

        /** Archive entries folder removal action **/

        $(document).on("click", 'a[name="removeFolder"]', removeFolder);

        function removeFolder() {
            let folderId = $(this).attr("id");
            let folderContent = $('#folderContent_' + folderId);
            $.ajax({
                url: "remove_folder",
                method: "POST",
                data: {folderId: folderId},
                success: function (folderRemoval) {
                    $('#folder_' + folderId).replaceWith(folderRemoval);
                    folderContent.html('');
                    folderContent.hide();
                }
            });

            return false;
        }

        /** Archive entries folder restore action **/

        $(document).on("click", 'a[name="restoreFolder"]', restoreFolder);

        function restoreFolder() {
            let folderId = $(this).attr("id");
            $.ajax({
                url: "restore_folder",
                method: "POST",
                data: {folderId: folderId},
                success: function (folderRestoration) {
                    $('#folder_' + folderId).replaceWith(folderRestoration);
                }
            });

            return false;
        }

        /** Archive entry removal action **/

        $(document).on("click", 'a[name="removeEntry"]', removeEntry);

        function removeEntry() {
            let entryId = $(this).attr("id");
            $.ajax({
                url: "remove_entry",
                method: "POST",
                data: {entryId: entryId},
                success: function (entryRemoval) {
                    $('#entry_' + entryId).replaceWith(entryRemoval);
                }
            });

            return false;
        }

        /** Archive entry restore action **/

        $(document).on("click", 'a[name="restoreEntry"]', restoreEntry);

        function restoreEntry() {
            let entryId = $(this).attr("id");
            $.ajax({
                url: "restore_entry",
                method: "POST",
                data: {entryId: entryId},
                success: function (entryRestoration) {
                    $('#entry_' + entryId).replaceWith(entryRestoration);

                }
            });

            return false;
        }

        /** Popup window close **/

        $(document).on("click", "a[name='closeForm']", function closeForm(event) {
            event.preventDefault();
            $(this).parent().hide();
        });

        /** Flash messages loader **/

        function loadFlashMessages() {
            $.ajax({
                url: "flash_messages",
                method: "POST",
                success: function (reloadFlashMessages) {
                    $('#flash-messages').replaceWith(
                        $(reloadFlashMessages));
                }
            });

            return false;
        }

        /** Flash messages summary loader **/

        function loadFlashMessagesSummary() {
            $.ajax({
                url: "flash_messages_summary",
                method: "POST",
                success: function (reloadFlashMessages) {
                    $('#flash-messages').replaceWith(
                        $(reloadFlashMessages));
                }
            });

            return false;
        }
    }
});
<commit_msg>Bug fix for incorrectly displayed entry content when opened<commit_after>$(document).ready(function () {
    if (!window.jQuery) {
    } else {
        /** Do not touch this **/
        let path = $("#main-table").attr("data-path");
        let $factory = $('#archive_entry_search_form_factory');
        let searchForm = $("#archive_entry_search_form");
        let resetButton = $("#archive_entry_search_form_resetButton");
        let createFolderBlock = $("#addFolder");
        let uploadFileBlock = $("#addFile");
        let downloadFileBlock = $("#downloadFile");

        /** Seriously, it'a a bad idea  :) **/

        /** Archive entries main table factory->settings AJAX loader **/

        $factory.on("change", function settingsLoadAction() {
            let data = {};
            data[$factory.attr('name')] = $factory.val();
            $.ajax({
                url: path,
                method: searchForm.attr('method'),
                data: data,
                success: function (response) {
                    $('#archive_entry_search_form_setting').replaceWith(
                        $(response).find('#archive_entry_search_form_setting')
                    );
                }
            });

            return false;
        });

        /** Archive entries main table content AJAX loader **/

        searchForm.on("submit", function searchAction(event) {
            event.preventDefault();
            let fields = searchForm.serializeArray();
            let values = {};
            jQuery.each(fields, function (i, field) {
                values[field.name] = field.value;
            });
            $.ajax({
                url: path,
                method: searchForm.attr('method'),
                data: values,
                success: function (response) {
                    $('#main-tbody').replaceWith(
                        $(response).find('#main-tbody')
                    );
                }
            });

            return false;
        });

        /** Archive entries main table search form reset to default stdout AJAX loader **/

        resetButton.on("click", function resetAction() {
            searchForm.trigger('reset');
            $.ajax({
                url: path,
                method: searchForm.attr('method'),
                data: null,
                success: function (response) {
                    $('#main-tbody').replaceWith(
                        $(response).find('#main-tbody'));
                    $('#archive_entry_search_form_setting').attr('disabled', 'disabled');
                    $('#addFolder').hide();
                }
            });

            return false;
        });

        /** Archive entries content loader **/

        $(document).on("click", "a[name='entryId']", openEntryContents);

        function openEntryContents() {
            let entryId = $(this).parent().attr("id");
            let contentPlace = $('#entryContent_' + entryId);
            if ($(contentPlace).is(":hidden")) {
                $.ajax({
                    url: "view",
                    method: searchForm.attr('method'),
                    data: {entryId: entryId},
                    success: function (response) {
                        contentPlace.html($(response));
                        loadLastUpdateInfo(entryId, null);
                        let folderId = contentPlace.find('#rootEntry').children('td').attr('id');
                        openFolder(folderId);
                        contentPlace.show().css('display', 'table-cell');
                    }
                });
            }
            else {
                $(contentPlace).hide();
            }

            return false;
        }

        /** Archive entries content navigation **/

        $(document).on("click", "a[name='openFolder']", function ()
        {
            let folderId = $(this).attr("id");
            openFolder(folderId);

            return false;
        });

        function openFolder(folderId) {
            let folderContent = $('#folderContent_' + folderId);
            let fileContent = $('#fileContent_' + folderId);
            if ($(folderContent).is(":hidden")) {
                $.ajax({
                    url: "view_folders",
                    method: "POST",
                    data: {folderId: folderId},
                    success: function (response) {
                        folderContent.html(response);
                        loadLastUpdateInfo(null, folderId);
                    }
                });
                $.ajax({
                    url: "view_files",
                    method: "POST",
                    data: {folderId: folderId},
                    success: function (response) {
                        fileContent.html(response);
                    }
                });
                folderContent.show();
                fileContent.show();
            }
            else {
                folderContent.hide();
                fileContent.hide();
            }

            return false;
        }

        /** Archive entries folder creation with form loader **/

        $(document).on("click", 'a[name="addFolder"]', createFolder);

        function createFolder() {
            let entryId = $(this).attr("id");
            /** Load folder creation form **/
            $.ajax({
                url: "new_folder",
                method: searchForm.attr('mehtod'),
                data: {entryId: entryId},
                success: function (loadFormResponse) {
                    createFolderBlock.html($(loadFormResponse));
                    createFolderBlock.show();
                    let $folderAddForm = createFolderBlock.find('#folder_add_form');
                    $folderAddForm.on("submit", function createFolder(event) {
                        event.preventDefault();
                        let folderSerialized = $folderAddForm.serialize();
                        /** Submit new folder **/
                        $.ajax({
                            url: "new_folder",
                            method: $folderAddForm.attr('method'),
                            data: folderSerialized,
                            success: function () {
                                createFolderBlock.hide();
                                let folderId = $folderAddForm.find('select[id="folder_add_form_parentFolder"]').val();
                                let folderContent = $('#folderContent_' + folderId);
                                /** Reload folder view order **/
                                $.ajax({
                                    url: "view_folders",
                                    method: searchForm.attr('method'),
                                    data: {folderId: folderId},
                                    success: function (reloadResponse) {
                                        // @TODO: create proper design
                                        folderContent.hide();
                                        //openFolder(folderId);
                                        folderContent.html(reloadResponse);
                                        folderContent.show();
                                        loadLastUpdateInfo(null, folderId);
                                    }
                                });
                                loadFlashMessages();
                            }
                        });
                    });
                }
            });

            return false;
        }

        /** Archive entries file upload with form loader **/

        $(document).on("click", 'a[name="addFile"]', uploadFile);

        function uploadFile() {
            let entryId = $(this).attr("id");
            /** Load file upload form **/
            $.ajax({
                url: "new_file",
                method: searchForm.attr('mehtod'),
                data: {entryId: entryId},
                success: function (loadFormResponse) {
                    uploadFileBlock.html($(loadFormResponse));
                    uploadFileBlock.show();
                    let $fileAddForm = uploadFileBlock.find('#file_add_form');
                    $fileAddForm.on("submit", function uploadFile(event) {
                        event.preventDefault();
                        //var fileSerialized = $fileAddForm.serialize();
                        let fileSerialized = new FormData($(this)[0]);
                        /** Submit new file **/
                        $.ajax({
                            url: "new_file",
                            method: $fileAddForm.attr('method'),
                            data: fileSerialized,
                            processData: false,
                            contentType: false,
                            success: function () {
                                uploadFileBlock.hide();
                                let folderId = $fileAddForm.find('select[id="file_add_form_parentFolder"]').val();
                                let folderContent = $('#folderContent_' + folderId);
                                let fileContent = $('#fileContent_' + folderId);
                                /** Reload folder view order **/
                                $.ajax({
                                    url: "view_files",
                                    method: searchForm.attr('method'),
                                    data: {folderId: folderId},
                                    success: function (reloadResponse) {
                                        // @TODO: create proper design
                                        fileContent.hide();
                                        //folderContent.hide();
                                        //openFolder(folderId);
                                        fileContent.html(reloadResponse);
                                        fileContent.show();
                                        loadLastUpdateInfo(null, folderId);
                                    }
                                });
                                /** Load flash messages **/
                                loadFlashMessagesSummary();
                            }
                        });
                    });
                }
            });

            return false;
        }

        /** Archive entries file download with md5 verification **/

        $(document).on("click", 'a[name="downloadFile"]', downloadFile);

        function downloadFile() {
            let fileId = $(this).attr("id");
            /** Load file download block **/
            $.ajax({
                url: "download_file",
                method: "POST",
                data: {fileId: fileId},
                success: function (downloadBlockResponse) {
                    downloadFileBlock.html($(downloadBlockResponse));
                    downloadFileBlock.show();
                }
            });
            let fileInfo = $('#file_' + fileId);
            $.ajax({
                url: "reload_file",
                method: "POST",
                data: {fileId: fileId},
                success: function (reloadFileInfo) {
                    fileInfo.replaceWith(reloadFileInfo);
                }
            });

            return false;
        }

        /** Last entry update information load & refresh **/

        function loadLastUpdateInfo(entryId, folderId) {
            if (entryId !== null) {
                $.ajax({
                    url: "last_update_info",
                    method: "POST",
                    data: {entryId: entryId},
                    success: function (reloadLastUpdateInfo) {
                        $($('#entryContent_' + entryId).find('#last-update')).html(reloadLastUpdateInfo);
                    }
                });
            }
            else if (folderId !== null) {
                $.ajax({
                        url: "get_folder_entryId",
                        method: "POST",
                        data: {folderId: folderId},
                        success: function (entryId) {
                            $.ajax({
                                url: "last_update_info",
                                method: "POST",
                                data: {folderId: folderId},
                                success: function (reloadLastUpdateInfo) {
                                    $($('#entryContent_' + entryId).find('#last-update')).html(reloadLastUpdateInfo);
                                }
                            });
                        }
                    }
                );
            }

            return false;
        }

        /** Archive entries file removal action **/

        $(document).on("click", 'a[name="removeFile"]', removeFile);

        function removeFile() {
            let fileId = $(this).attr("id");
            $.ajax({
                url: "remove_file",
                method: "POST",
                data: {fileId: fileId},
                success: function (fileRemoval) {
                    $('#file_' + fileId).replaceWith(fileRemoval);
                }
            });

            return false;
        }

        /** Archive entries file restore action **/

        $(document).on("click", 'a[name="restoreFile"]', restoreFile);

        function restoreFile() {
            let fileId = $(this).attr("id");
            $.ajax({
                url: "restore_file",
                method: "POST",
                data: {fileId: fileId},
                success: function (fileRestoration) {
                    $('#file_' + fileId).replaceWith(fileRestoration);
                }
            });

            return false;
        }

        /** Archive entries folder removal action **/

        $(document).on("click", 'a[name="removeFolder"]', removeFolder);

        function removeFolder() {
            let folderId = $(this).attr("id");
            let folderContent = $('#folderContent_' + folderId);
            $.ajax({
                url: "remove_folder",
                method: "POST",
                data: {folderId: folderId},
                success: function (folderRemoval) {
                    $('#folder_' + folderId).replaceWith(folderRemoval);
                    folderContent.html('');
                    folderContent.hide();
                }
            });

            return false;
        }

        /** Archive entries folder restore action **/

        $(document).on("click", 'a[name="restoreFolder"]', restoreFolder);

        function restoreFolder() {
            let folderId = $(this).attr("id");
            $.ajax({
                url: "restore_folder",
                method: "POST",
                data: {folderId: folderId},
                success: function (folderRestoration) {
                    $('#folder_' + folderId).replaceWith(folderRestoration);
                }
            });

            return false;
        }

        /** Archive entry removal action **/

        $(document).on("click", 'a[name="removeEntry"]', removeEntry);

        function removeEntry() {
            let entryId = $(this).attr("id");
            $.ajax({
                url: "remove_entry",
                method: "POST",
                data: {entryId: entryId},
                success: function (entryRemoval) {
                    $('#entry_' + entryId).replaceWith(entryRemoval);
                }
            });

            return false;
        }

        /** Archive entry restore action **/

        $(document).on("click", 'a[name="restoreEntry"]', restoreEntry);

        function restoreEntry() {
            let entryId = $(this).attr("id");
            $.ajax({
                url: "restore_entry",
                method: "POST",
                data: {entryId: entryId},
                success: function (entryRestoration) {
                    $('#entry_' + entryId).replaceWith(entryRestoration);

                }
            });

            return false;
        }

        /** Popup window close **/

        $(document).on("click", "a[name='closeForm']", function closeForm(event) {
            event.preventDefault();
            $(this).parent().hide();
        });

        /** Flash messages loader **/

        function loadFlashMessages() {
            $.ajax({
                url: "flash_messages",
                method: "POST",
                success: function (reloadFlashMessages) {
                    $('#flash-messages').replaceWith(
                        $(reloadFlashMessages));
                }
            });

            return false;
        }

        /** Flash messages summary loader **/

        function loadFlashMessagesSummary() {
            $.ajax({
                url: "flash_messages_summary",
                method: "POST",
                success: function (reloadFlashMessages) {
                    $('#flash-messages').replaceWith(
                        $(reloadFlashMessages));
                }
            });

            return false;
        }
    }
});
<|endoftext|>


<commit_before>const util = require('./util')
const time = require('./time')
const fs = require('fs')
const path = require('path')
const Updater = require('./updater')
const DisplayClient = require("./display")
const idGenerator = require('./id-generator')
const child_process = require('child_process')

const config = require('./updater-config').loadConfig()

let errorMessage = null

if (config.simulate) {
  console.log("simulate == true, so I will only pretend to execute local update scripts.")
}

function checkForUpdate() {
  updater.checkForUpdateAndTellHubHowItWorkedOut()
    .then((result) => {
      display.showNetworkOk()
      console.log("Update check completed. ", result)
      checkUpdateInterval(result.newUpdateInterval)

      console.log("Waiting " + config.updateIntervalSeconds + " seconds...")
      setTimeout(checkForUpdate, config.updateIntervalSeconds * 1000)

    })
    .catch((err) => {
      if (err.networkError) {
        display.showNetworkError(err)
      }
      if (err.updateError) {
        display.showUpdateError(err)
      }

      console.log("Waiting " + config.updateIntervalSeconds + " seconds...")
      setTimeout(checkForUpdate, config.updateIntervalSeconds * 1000)
    })

}

/**
 * Notifies me that updating is currently in progress.
 * So I'll show a progress bar.
 */
function onUpdating(updating) {
  console.log("onUpdating called", updating)
  if (updating) {
    display.showUpdatingProgressBar()
  } else {
    display.hideUpdatingProgressBar()
  }
}

function truncate(string, toLength) {
  return string.substring(0, toLength)
}

function displayStatus(statusRow1, statusRow2, errorMessage) {
  const row = 9
  const col = 0

  if (statusRow1) {
    display.call("writeText", [statusRow1 + "        ", row, col, false, config.mainDisplayTab])
  }
  if (statusRow2) {
    display.call("writeText", [statusRow2 + "        ", row + 1, col, false, config.mainDisplayTab])
  }
}

function displayError(errorMessage) {
  display.call("writeText", [errorMessage])
}

function checkUpdateInterval(newUpdateInterval) {
  if (newUpdateInterval) {
    try {
      newUpdateInterval = parseInt(newUpdateInterval)
      if (newUpdateInterval < config.minUpdateIntervalSeconds) {
        newUpdateInterval = config.minUpdateIntervalSeconds
      }
      if (newUpdateInterval > config.maxUpdateIntervalSeconds) {
        newUpdateInterval = config.maxUpdateIntervalSeconds
      }
      config.updateIntervalSeconds = newUpdateInterval
      console.log("Setting update interval to " + config.updateIntervalSeconds + " seconds")
    } catch (err) {
      console.log("Something went wrong while parsing newUpdateInterval (ignoring it and moving on)", newUpdateInterval, err)
    }

  }

}

function readDeviceId() {
  const deviceIdFile = path.join(config.rootDir, "device-id")
  let deviceId
  if (fs.existsSync(deviceIdFile)) {
    deviceId = fs.readFileSync(deviceIdFile).toString()
  } else {
    deviceId = generateDeviceIdAndSave()
  }
  return deviceId
}

function generateDeviceIdAndSave() {
  const deviceIdFile = path.join(config.rootDir, "device-id")
  const deviceId = idGenerator.generateRandomId(config.deviceIdLength)
  fs.writeFileSync(deviceIdFile, deviceId)
  console.log("Created " + deviceIdFile + " with ID " + deviceId)
  if (config.scriptToCallWhenDeviceIdHasBeenSet) {
    console.log("Will execute script: ", config.scriptToCallWhenDeviceIdHasBeenSet)
    try {
      const scriptWithArgument = config.scriptToCallWhenDeviceIdHasBeenSet + " " + deviceId
      child_process.exec(scriptWithArgument)
      console.log("Sucessfully executed script " + scriptWithArgument)
    } catch (err) {
      console.log("Failed to execute script " + scriptWithArgument, err)
    }

  }

  return deviceId
}

function createRootDirIfMissing() {
  if (!fs.existsSync(config.rootDir)) {
    fs.mkdirSync(config.rootDir)
    console.log("Created root dir: " + config.rootDir)
  }
}

function setSystemClock() {
  time.syncSystemClockWithServer(config.hubUrl)
}

createRootDirIfMissing()

const deviceId = readDeviceId()

const options = {
  updateScriptTimeoutSeconds: config.updateScriptTimeoutSeconds,
  simulate: config.simulate,
  sshTunnelCommand: config.sshTunnelCommand,
  onUpdating: onUpdating
}
const updater = new Updater(config.rootDir, config.hubUrl, options)

const display = new DisplayClient(deviceId, config.displayRpcPort, config.mainDisplayTab, config.networkInfoDisplayTab, true)

display.showDeviceId()

setSystemClock()
checkForUpdate()

<commit_msg>Removed unnecessary logging<commit_after>const util = require('./util')
const time = require('./time')
const fs = require('fs')
const path = require('path')
const Updater = require('./updater')
const DisplayClient = require("./display")
const idGenerator = require('./id-generator')
const child_process = require('child_process')

const config = require('./updater-config').loadConfig()

let errorMessage = null

if (config.simulate) {
  console.log("simulate == true, so I will only pretend to execute local update scripts.")
}

function checkForUpdate() {
  updater.checkForUpdateAndTellHubHowItWorkedOut()
    .then((result) => {
      display.showNetworkOk()
      console.log("Update check completed. ", result)
      checkUpdateInterval(result.newUpdateInterval)

      console.log("Waiting " + config.updateIntervalSeconds + " seconds...")
      setTimeout(checkForUpdate, config.updateIntervalSeconds * 1000)

    })
    .catch((err) => {
      if (err.networkError) {
        display.showNetworkError(err)
      }
      if (err.updateError) {
        display.showUpdateError(err)
      }

      console.log("Waiting " + config.updateIntervalSeconds + " seconds...")
      setTimeout(checkForUpdate, config.updateIntervalSeconds * 1000)
    })

}

/**
 * Notifies me that updating is currently in progress.
 * So I'll show a progress bar.
 */
function onUpdating(updating) {
  if (updating) {
    display.showUpdatingProgressBar()
  } else {
    display.hideUpdatingProgressBar()
  }
}

function truncate(string, toLength) {
  return string.substring(0, toLength)
}

function displayStatus(statusRow1, statusRow2, errorMessage) {
  const row = 9
  const col = 0

  if (statusRow1) {
    display.call("writeText", [statusRow1 + "        ", row, col, false, config.mainDisplayTab])
  }
  if (statusRow2) {
    display.call("writeText", [statusRow2 + "        ", row + 1, col, false, config.mainDisplayTab])
  }
}

function displayError(errorMessage) {
  display.call("writeText", [errorMessage])
}

function checkUpdateInterval(newUpdateInterval) {
  if (newUpdateInterval) {
    try {
      newUpdateInterval = parseInt(newUpdateInterval)
      if (newUpdateInterval < config.minUpdateIntervalSeconds) {
        newUpdateInterval = config.minUpdateIntervalSeconds
      }
      if (newUpdateInterval > config.maxUpdateIntervalSeconds) {
        newUpdateInterval = config.maxUpdateIntervalSeconds
      }
      config.updateIntervalSeconds = newUpdateInterval
      console.log("Setting update interval to " + config.updateIntervalSeconds + " seconds")
    } catch (err) {
      console.log("Something went wrong while parsing newUpdateInterval (ignoring it and moving on)", newUpdateInterval, err)
    }

  }

}

function readDeviceId() {
  const deviceIdFile = path.join(config.rootDir, "device-id")
  let deviceId
  if (fs.existsSync(deviceIdFile)) {
    deviceId = fs.readFileSync(deviceIdFile).toString()
  } else {
    deviceId = generateDeviceIdAndSave()
  }
  return deviceId
}

function generateDeviceIdAndSave() {
  const deviceIdFile = path.join(config.rootDir, "device-id")
  const deviceId = idGenerator.generateRandomId(config.deviceIdLength)
  fs.writeFileSync(deviceIdFile, deviceId)
  console.log("Created " + deviceIdFile + " with ID " + deviceId)
  if (config.scriptToCallWhenDeviceIdHasBeenSet) {
    console.log("Will execute script: ", config.scriptToCallWhenDeviceIdHasBeenSet)
    try {
      const scriptWithArgument = config.scriptToCallWhenDeviceIdHasBeenSet + " " + deviceId
      child_process.exec(scriptWithArgument)
      console.log("Sucessfully executed script " + scriptWithArgument)
    } catch (err) {
      console.log("Failed to execute script " + scriptWithArgument, err)
    }

  }

  return deviceId
}

function createRootDirIfMissing() {
  if (!fs.existsSync(config.rootDir)) {
    fs.mkdirSync(config.rootDir)
    console.log("Created root dir: " + config.rootDir)
  }
}

function setSystemClock() {
  time.syncSystemClockWithServer(config.hubUrl)
}

createRootDirIfMissing()

const deviceId = readDeviceId()

const options = {
  updateScriptTimeoutSeconds: config.updateScriptTimeoutSeconds,
  simulate: config.simulate,
  sshTunnelCommand: config.sshTunnelCommand,
  onUpdating: onUpdating
}
const updater = new Updater(config.rootDir, config.hubUrl, options)

const display = new DisplayClient(deviceId, config.displayRpcPort, config.mainDisplayTab, config.networkInfoDisplayTab, true)

display.showDeviceId()

setSystemClock()
checkForUpdate()

<|endoftext|>


<commit_before>// ==UserScript==
// @name        OUJS widelist
// @namespace   trespassersW
// @description extends list of scripts shown by OUJS to 100% width
// @include https://openuserjs.org/*
// @license MIT
// @version 2014.1005.1
//  .1005.1 tiny fixes
// @created 2014-10-05
// @updated 2014-10-05
// @run-at document-end
// @grant GM_none
// ==/UserScript==
(function(){ "use strict";
if(!document.querySelector(".tr-link")) return;
var css="\
.col-sm-8 {\
 width: 100% !important;\
}\
.col-sm-4 {\
 position: absolute !important;\
 right: 0 !important;\
 z-index: 9!important;\
}\
.col-sm-4 div.panel {\
 margin-bottom: 4px !important;\
}\
\
.col-sm-4:before {\
 border: thin solid grey !important;\
 background: white;\
 content: '\\21a7';\
 position: absolute;\
 left: -6px; top: 2px;\
 font-size: 20px;\
 color: gray;\
}\
.col-sm-4:hover:before {\
 border: thin solid red !important;\
 color: red !important;\
}\
.col-sm-4 .col-sm-40 \
{\
 position:absolute !important;\
 visibility: hidden !important;\
 padding: 0 !important; margin: 0 !important;\
 display: block !important;\
 transition-property: visibility;\
 transition-delay: 750ms\
}\
.col-sm-4:hover .col-sm-40\
{\
 visibility: visible !important;\
 display: block !important;\
 transition-property: visibility;\
 transition-delay: 300ms\
}\
/* name+description in single line */\
.tr-link span.inline-block ~ p\
{\
 display: inline !important;\
}\
.tr-link span.inline-block ~ p:before {\
 content: '\\0a0 -\\0a0'\
}\
.tr-link td.rating .progress {\
 margin-bottom: 0 !important;\
}\
.tr-link td.rating  {\
 line-height: 1 !important;\
}\
.tr-link {\
 background-image: linear-gradient(to top,\
 rgba(255,255,255, .75), rgba(237,237,255, .75) );\
}\
/* hide username in author's scripts list */\
.col-xs-12 .tr-link a.tr-link-a ~ span.inline-block{\
 display: none !important;\
}\
.oujsort-desc:after {content: '\\2193'; color: #DF691A;}\
.oujsort-asc:after {content: '\\2191'; color: #DF691A;}\
";
//
function stickStyle(css){
 var s=document.createElement("style"); s.type="text/css";
 s.appendChild(document.createTextNode(css));
 return (document.head||document.documentElement).appendChild(s);
}

stickStyle(css);
function toObj(s) {
 var r = {}, c = s.split('&'), t;
 for(var i = 0; i < c.length; i++) {
  t = c[i].split('=');
  r[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
 }
 return r;
}
function hp(h) {
 var r,x=h.indexOf("?");
 if(x>-1) r=toObj(h.substr(x+1));
 return r;
}
var defaultOrder = {
 topic: 'asc', name: 'asc', category: 'asc', users: 'asc',
 views: 'desc', created: 'desc', updated: 'desc',
 size: 'desc', rating: 'desc', installs: 'desc', comments: 'desc'
}

//window.addEventListener("load",function(e) {
var a, ah, lh = hp(location.href), o,i,il;
if(lh&&lh.orderBy) {
 a=document.querySelectorAll("th.text-center >a");
 for( il=a.length, i=0; i<il; i++ ) {
  ah=hp(a[i].href);
  if(ah) if(ah.orderBy==lh.orderBy) { // mark sorted column
    a[i].classList.add("oujsort-"+lh.orderDir);
   }else{ // set commonsensical sorting order
    o= defaultOrder[ah.orderBy];
    if(o && o!=ah.orderDir )
     a[i].href=a[i].href.replace('&orderDir='+ah.orderDir,'&orderDir='+o);
   }
 }
}

// rearrange right panel to get transition working
a = document.querySelectorAll("div.col-sm-4 > div.panel");
 if(a.length>1) {
  o = document.createElement('div');
  o.className="col-sm-40";
  var aa=[];
  for( i=a.length-1; i>0; i-- )
    aa.push(a[i].parentNode.removeChild(a[i]));
  for( i=aa.length; i>0; i-- )
    o.appendChild( aa.pop() );
  a[0].parentNode.appendChild(o);
 }
//},false);

})();<commit_msg>run on DOMContentLoaded<commit_after>// ==UserScript==
// @name        OUJS widelist
// @namespace   trespassersW
// @description extends list of scripts shown by OUJS to 100% width
// @include https://openuserjs.org/*
// @license MIT
// @version 2014.1006.0
//  .1006.0 table header fixes
// @created 2014-10-05
// @updated 2014-10-06
// @run-at document-end
// @grant GM_none
// ==/UserScript==
(function(){ "use strict";
if(!document.querySelector(".tr-link")) return;
var css="\
.col-sm-8 {\
 width: 100% !important;\
}\
.col-sm-4 {\
 position: absolute !important;\
 right: 0 !important;\
 z-index: 9!important;\
}\
.col-sm-4 div.panel {\
 margin-bottom: 4px !important;\
}\
\
.col-sm-4:before {\
 border: thin solid grey !important;\
 background: white;\
 content: '\\21a7';\
 position: absolute;\
 left: -6px; top: 2px;\
 font-size: 20px;\
 color: gray;\
}\
.col-sm-4:hover:before {\
 border: thin solid red !important;\
 color: red !important;\
}\
.col-sm-4 .col-sm-404 \
{\
 position:absolute !important;\
 visibility: hidden !important;\
 padding: 0 !important; margin: 0 !important;\
 display: block !important;\
 transition-property: visibility;\
 transition-delay: 750ms\
}\
.col-sm-4:hover .col-sm-404\
{\
 visibility: visible !important;\
 display: block !important;\
 transition-property: visibility;\
 transition-delay: 300ms\
}\
/* name+description in single line */\
.tr-link span.inline-block ~ p\
{\
 display: inline !important;\
}\
.tr-link span.inline-block ~ p:before {\
 content: '\\0a0 -\\0a0'\
}\
.tr-link td.rating .progress {\
 margin-bottom: 0 !important;\
}\
.tr-link td.rating  {\
 line-height: 1 !important;\
}\
.tr-link {\
 background-image: linear-gradient(to top,\
 rgba(255,255,255, .75), rgba(237,237,255, .75) );\
}\
/* hide username in author's scripts list */\
.col-xs-12 .tr-link a.tr-link-a ~ span.inline-block{\
 display: none !important;\
}\
.oujsort-desc:after {content: '\\2193';  visibility:hidden;}\
.oujsort-asc:after  {content: '\\2191';  visibility:hidden;}\
.oujsort-desc:hover:after, .oujsort-asc:hover:after{ visibility: visible;}\
.oujsort-sel:after {visibility: visible; }\
";
//
function stickStyle(css){
 var s=document.createElement("style"); s.type="text/css";
 s.appendChild(document.createTextNode(css));
 return (document.head||document.documentElement).appendChild(s);
}

stickStyle(css);
function toObj(s) {
 var r = {}, c = s.split('&'), t;
 for(var i = 0; i < c.length; i++) {
  t = c[i].split('=');
  r[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
 }
 return r;
}
function hp(h) {
 var r,x=h.indexOf("?");
 if(x>-1) r=toObj(h.substr(x+1));
 return r;
}

var odir=[ 'asc', 'desc' ];
var defaultOrder = {
 topic: 0, name: 0, category: 0, users: 0,
 views: 1, created: 1, updated: 1,
 size: 1, rating: 1, installs: 1, comments: 1
};

//window.addEventListener("load",function(e) {

var a, ah, lh = hp(location.href), o,i,il,t;
//if(lh) {
 a=document.querySelectorAll('th >a[href*="orderBy"]');
 for( il=a.length, i=0; i<il; i++ ) {
  ah=hp(a[i].href);
  if(ah && ah.orderBy) {
   o= defaultOrder[ah.orderBy]; o=odir[o];
   if(o){ t=0;
    if( lh && lh.orderBy && (t= (ah.orderBy==lh.orderBy)) ) // selected?
     o= ah.orderDir;
   // mark sorted column
    a[i].classList.add("oujsort-"+o);
    if(t) a[i].classList.add("oujsort-sel");
    if( o!=ah.orderDir )    // set commonsensical sorting order
     a[i].href=a[i].href.replace('&orderDir='+ah.orderDir,'&orderDir='+o);
   }
  }
 }
//}

//},false);

// rearrange right panel to get transition working
a = document.querySelectorAll("div.col-sm-4 > div.panel");
 if(a.length>1) {
  o = document.createElement('div');
  o.className="col-sm-404";
  var aa=[];
  for( i=a.length-1; i>0; i-- )
    aa.push(a[i].parentNode.removeChild(a[i]));
  for( i=aa.length; i>0; i-- )
    o.appendChild( aa.pop() );
  a[0].parentNode.appendChild(o);
 }
//},false);

})();<|endoftext|>


<commit_before>/*
 * library dependencies:
 *      jquery 1.8.3
 *      fos-routing
 *      fileUploader
 *      colorBox
 * external dependencies:
 *      appLocale
 */

// fansWorld file upload plugin 1.3

// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
//;(function ($, window, document, undefined) {
$(document).ready(function () {

    "use strict";

    // undefined is used here as the undefined global variable in ECMAScript 3 is
    // mutable (ie. it can be changed by someone else). undefined isn't really being
    // passed in so we can ensure the value of it is truly undefined. In ES5, undefined
    // can no longer be modified.

    // window and document are passed through as local variable rather than global
    // as this (slightly) quickens the resolution process and can be more efficiently
    // minified (especially when both are regularly referenced in your plugin).

    // Create the defaults once
    var pluginName = "fwUploader";
    var defaults = {
        propertyName: "fansworld",
        uploadtoken: null,
        ks: null,
        entryId: null,
        mediaExtensions: {
            photo: ['jpg', 'jpeg', 'png', 'gif'],                       // Allowed extensions by media type
            video: ['avi', 'mov', 'mpeg'],
            audio: ['wav', 'mp3', 'ogg', 'midi']
        },
        action: {
            photo: Routing.generate(appLocale + '_photo_fileupload'),   // link for photos
            video: 'http://www.kaltura.com/api_v3/index.php'            // link for videos
        },
        mediaType: null,
        // custom bindings
        onSubmit: function(id, fileName){},
        onComplete: function(id, fileName, responseJSON){},
        onCancel: function(id, fileName){},
        onUpload: function(id, fileName, xhr){},
        onProgress: function(id, fileName, loaded, total){},
        onError: function(id, fileName, reason) {}
    };

    // The actual plugin constructor
    function Plugin(element, options) {
        this.element = element;
        // jQuery has an extend method which merges the contents of two or
        // more objects, storing the result in the first object. The first object
        // is generally empty as we don't want to alter the default options for
        // future instances of the plugin
        this.options = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    Plugin.prototype = {
        init: function () {
            var that = this;
            $(that.element).addClass(that._name);
            that.options.mediaType = $(that.element).attr('data-upload');
            $(that.element).bind("destroyed", $.proxy(that.teardown, that));
            $(that.element).colorbox({
                innerWidth: 700,
                innerHeight: 475,
                onComplete: function() {
                    if(that.options.mediaType === 'video')
                    {
                        // Get kaltura token before popup opens
                        that.getToken('fileName', function(uploadToken) {
                            console.log("token: " + uploadToken)
                            that.createFwGenericUploader();
                            that.uploader.setParams({uploadTokenId: that.options.uploadtoken});
                            that.resizePopup(); // fire this event only when content has loaded
                        });
                    } else {
                        that.createFwUploader();
                        that.resizePopup();
                    }
                }
            });
        },
        bindAlbumActions: function() {
            var that = this;
            if ($('#form_album').val() === 'NEW') {
                that.spawnNewAlbumField($('#form_album'));
            }
            $('#form_album').change(function(e){
                var el = $(this);
                if (el.val() === 'NEW') {
                    that.spawnNewAlbumField(el);
                } else {
                    $('#form_album_new_name').parents('.control-group').remove();
                }
            });
        },
        spawnNewAlbumField: function(el) {
            var that = this;
            var newfield = $(".templateFieldAlbumName .control-group").clone();
            newfield.find('input').attr('id', 'form_album_new_name');
            el.parents('.control-group').after(newfield);
            $('#form_album_new_name').parents('.control-group').slideDown('fast', function() {
                that.resizePopup();
            });
        },
        bindFormSubmit: function() {
            var that = this;
            console.log("bindFormSubmit")
            //$('#cboxLoadedContent').find("form") <--- suck it from above
            $("form.upload-" + that.options.mediaType).submit(function() {
                console.log("before submit")
                var data = $(this).serializeArray();
                var href = $(this).attr('action');
                $.colorbox({
                    href: href ,
                    data: data,
                    onComplete: function(){
                        that.bindFormActions();
                        that.resizePopup();
                    }
                });
                return false;
            });
        },
        bindFormActions: function() {
            var that = this;
            that.bindFormSubmit();
            that.bindAlbumActions();
            setTimeout(function(){ that.resizePopup(); }, 500);
        },
        createFwUploader: function() {
            var that = this;
            var uploader = new qq.FileUploader({
                element: $("#file-uploader")[0],
                action: that.options.action[that.options.mediaType],
                debug: true,
                multiple: false,
                maxConnections: 1,
                allowedExtensions: that.options.mediaExtensions[that.options.mediaType],
                onComplete: function(id, fileName, responseJSON) {
                    if(responseJSON.success) {
                        $.colorbox({
                            href: Routing.generate(appLocale + '_photo_filemeta', {
                                'originalFile': responseJSON.originalFile,
                                'tempFile':responseJSON.tempFile,
                                'width': responseJSON.width,
                                'height': responseJSON.height
                            }),
                            iframe: false,
                            innerWidth: 700,
                            innerHeight: 700,
                            onComplete: function() {
                                that.resizePopup();
                                that.bindFormActions();
                            }
                        });
                    }
                    return that.options.onComplete(id, fileName, responseJSON);
                },
                onUpload: function() {
                    console.log("onUpload");
                    that.resizePopup();
                },
                onProgress: function(id, fileName, loaded, total) {
                    if (loaded !== total){
                        $( "#progressbar .bar" ).css('width', Math.round(loaded / total * 100)+'%');
                    } else {
                        $( "#progressbar .bar" ).css('width','100%');
                    }
                    that.resizePopup();
                },
                onSubmit: function(id, fileName){
                    return that.options.onSubmit(id, fileName);
                }
            });
        },
        createFwVideoUploader: function() {
            var that = this;
            that.uploader = new qq.FileUploader({
                element: $('#file-uploader')[0],
                action: that.options.action[that.options.mediaType],
                multiple: false,
                forceMultipart: true,
                normalHeaders: false,
                responsePassthrough: true,
                debug: true,
                inputName: 'resource:fileData',
                failedUploadTextDisplay: {mode: 'none'},
                onSubmit: function(file, ext){
                    that.uploader.setParams({
                        service: 'media',
                        action: 'addContent',
                        entryId: that.options.entryId,
                        ks: that.options.ks,
                        'resource:objectType': 'KalturaUploadedFileResource'
                    });
                    return that.options.onSubmit(id, fileName);
                },
                // kaltura returns XML
                onComplete: function(id, fileName, xml){
                    var xmlDoc = $.parseXML(xml);
                    var $xml = $( xmlDoc );
                    //var result = $xml.find( "result" );
                    return that.options.onComplete(id, fileName, xml);
                },
                onUpload: function(id, fileName, xhr) {
                    that.resizePopup();
                    return that.options.onUpload(id, fileName, xhr);
                },
                onProgress: function(id, fileName, loaded, total) {
                    return that.options.onProgress(id, fileName, loaded, total);
                }
            });
        },
        createFwGenericUploader: function() {
            var that = this;
            that.uploader = new qq.FileUploader({
                element: $('#file-uploader')[0],
                action: that.options.action[that.options.mediaType],
                multiple: false,
                forceMultipart: true,
                normalHeaders: false,
                responsePassthrough: true,
                debug: true,
                inputName: 'resource:fileData',
                failedUploadTextDisplay: {mode: 'none'},
                onSubmit: function(id, fileName){
                    that.uploader.setParams({
                        service: 'media',
                        action: 'addContent',
                        entryId: that.options.entryId,
                        ks: that.options.ks,
                        'resource:objectType': 'KalturaUploadedFileResource'
                    });
                    that.options.onSubmit(id, fileName);
                },
                onComplete: function(id, fileName, responseJSON) {
                    return that.options.onComplete(id, fileName, responseJSON);
                },
                onUpload: function(id, fileName, xhr) {
                    that.resizePopup();
                    return that.options.onUpload(id, fileName, xhr);
                },
                onProgress: function(id, fileName, loaded, total) {
                    return that.options.onProgress(id, fileName, loaded, total);
                },
            });
        },
        getToken: function(filename, callback) {
            var that = this;
            that.getKs(function(ks){
                console.log("getKs: " + that.options.ks)
                that.getMediaId("filename", function(entryId) {
                    console.log("getMediaId: " + that.options.entryId)
                    $.ajax({
                        url: 'http://www.kaltura.com/api_v3/index.php',
                        data: {
                            service: 'uploadToken',
                            action: 'add',
                            ks: that.options.ks,
                            'uploadToken:fileName': filename,
                            'uploadToken:objectType': 'KalturaUploadToken'
                        },
                        dataType: 'xml',
                        success: function(r) {
                            that.options.uploadtoken = $(r).find('id').text();
                            callback(that.options.uploadtoken);
                        }
                    });
                });
            });
        },
        getKs: function(callback)
        {
            var that = this;
            $.ajax({
                url: Routing.generate(appLocale + '_video_kaltura_ks'),
                dataType: 'json',
                success: function(responseJSON) {
                    that.options.ks = responseJSON.ks;
                    callback(that.options.ks);
                }
            });
        },
        getMediaId: function(fileName, callback) {
            var that = this;
                $.ajax({
                    url: 'http://www.kaltura.com/api_v3/index.php',
                    data: {
                        service: 'media',
                        action: 'add',
                        ks: that.options.ks,
                        'entry:name': fileName,
                        'entry:objectType': 'KalturaMediaEntry',
                        'entry:mediaType': 1
                    },
                    dataType: 'xml',
                    success: function(responseJSON) {
                        that.options.entryId = $(responseJSON).find('id').text();
                        console.log("ive a new entryId: " + that.options.entryId);
                        callback(that.options.entryId);
                    }
                });
        },
        resizePopup: function() {
            window.top.resizeColorbox({innerHeight: $('.popup-content').height() });
        },
        destroy: function() {
            var that = this;
            $(that.element).unbind("destroyed", that.teardown);
            that.teardown();
        },
        teardown: function() {
            var that = this;
            $.removeData($(that.element)[0], that._name);
            $(that.element).removeClass(that._name);
            $(that.element).removeClass('cboxElement').removeData('colorbox');
            that.unbind();
            //$.colorbox.remove();
            that.element = null;
        },
        bind: function() {  },
        unbind: function() {  }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, pluginName)) {
                $.data(this, pluginName, new Plugin(this, options));
            }
        });
    };

});<commit_msg>cambios uploader de video<commit_after>/*
 * library dependencies:
 *      jquery 1.8.3
 *      fos-routing
 *      fileUploader
 *      colorBox
 * external dependencies:
 *      appLocale
 */

// fansWorld file upload plugin 1.4

// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
//;(function ($, window, document, undefined) {
$(document).ready(function () {

    "use strict";
    // Create the defaults once
    var pluginName = "fwUploader";
    var defaults = {
        propertyName: "fansworld",
        uploadtoken: null,
        ks: null,
        entryId: null,
        mediaExtensions: {
            photo: ['jpg', 'jpeg', 'png', 'gif'],                       // Allowed extensions by media type
            video: ['avi', 'mov', 'mpeg'],
            audio: ['wav', 'mp3', 'ogg', 'midi']
        },
        action: {
            photo: Routing.generate(appLocale + '_photo_fileupload'),   // link for photos
            video: 'http://www.kaltura.com/api_v3/index.php'            // link for videos
        },
        mediaType: null,
        // custom bindings
        onSubmit: function(id, fileName){},
        onComplete: function(id, fileName, responseJSON){},
        onCancel: function(id, fileName){},
        onUpload: function(id, fileName, xhr){},
        onProgress: function(id, fileName, loaded, total){},
        onError: function(id, fileName, reason) {}
    };

    // The actual plugin constructor
    function Plugin(element, options) {
        this.element = element;
        // jQuery has an extend method which merges the contents of two or
        // more objects, storing the result in the first object. The first object
        // is generally empty as we don't want to alter the default options for
        // future instances of the plugin
        this.options = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    Plugin.prototype = {
        init: function () {
            var that = this;
            $(that.element).addClass(that._name);
            that.options.mediaType = $(that.element).attr('data-upload');
            $(that.element).bind("destroyed", $.proxy(that.teardown, that));
            $(that.element).colorbox({
                innerWidth: 700,
                innerHeight: 475,
                onComplete: function() {
                    if(that.options.mediaType === 'video')
                    {
                        that.createFwGenericUploader();
                        that.resizePopup();
                        // Get kaltura KS + entryId + uploadToken
                        that.getToken('fileName', function(uploadToken) {
                            console.log("token: " + uploadToken)
                            that.uploader.setParams({uploadTokenId: that.options.uploadtoken});
                        });
                    } else {
                        that.createFwUploader();
                        that.resizePopup();
                    }
                }
            });
        },
        bindAlbumActions: function() {
            var that = this;
            if ($('#form_album').val() === 'NEW') {
                that.spawnNewAlbumField($('#form_album'));
            }
            $('#form_album').change(function(e){
                var el = $(this);
                if (el.val() === 'NEW') {
                    that.spawnNewAlbumField(el);
                } else {
                    $('#form_album_new_name').parents('.control-group').remove();
                }
            });
        },
        spawnNewAlbumField: function(el) {
            var that = this;
            var newfield = $(".templateFieldAlbumName .control-group").clone();
            newfield.find('input').attr('id', 'form_album_new_name');
            el.parents('.control-group').after(newfield);
            $('#form_album_new_name').parents('.control-group').slideDown('fast', function() {
                that.resizePopup();
            });
        },
        bindFormSubmit: function() {
            var that = this;
            console.log("bindFormSubmit")
            //$('#cboxLoadedContent').find("form") <--- suck it from above
            $("form.upload-" + that.options.mediaType).submit(function() {
                console.log("before submit")
                var data = $(this).serializeArray();
                var href = $(this).attr('action');
                $.colorbox({
                    href: href ,
                    data: data,
                    onComplete: function(){
                        that.bindFormActions();
                        that.resizePopup();
                    }
                });
                return false;
            });
        },
        bindFormActions: function() {
            var that = this;
            that.bindFormSubmit();
            that.bindAlbumActions();
            setTimeout(function(){ that.resizePopup(); }, 2000);
        },
        createFwUploader: function() {
            var that = this;
            var uploader = new qq.FileUploader({
                element: $("#file-uploader")[0],
                action: that.options.action[that.options.mediaType],
                debug: true,
                multiple: false,
                maxConnections: 1,
                allowedExtensions: that.options.mediaExtensions[that.options.mediaType],
                onComplete: function(id, fileName, responseJSON) {
                    if(responseJSON.success) {
                        $.colorbox({
                            href: Routing.generate(appLocale + '_photo_filemeta', {
                                'originalFile': responseJSON.originalFile,
                                'tempFile':responseJSON.tempFile,
                                'width': responseJSON.width,
                                'height': responseJSON.height
                            }),
                            iframe: false,
                            innerWidth: 700,
                            innerHeight: 700,
                            onComplete: function() {
                                that.resizePopup();
                                that.bindFormActions();
                            }
                        });
                    }
                    return that.options.onComplete(id, fileName, responseJSON);
                },
                onUpload: function() {
                    console.log("onUpload");
                    that.resizePopup();
                },
                onProgress: function(id, fileName, loaded, total) {
                    if (loaded !== total){
                        $( "#progressbar .bar" ).css('width', Math.round(loaded / total * 100)+'%');
                    } else {
                        $( "#progressbar .bar" ).css('width','100%');
                    }
                    that.resizePopup();
                },
                onSubmit: function(id, fileName){
                    return that.options.onSubmit(id, fileName);
                },
                onError: function(id, fileName, reason) {
                    return that.options.onError(id, fileName, reason);
                }
            });
        },
        createFwVideoUploader: function() {
            var that = this;
            that.uploader = new qq.FileUploader({
                element: $('#file-uploader')[0],
                action: that.options.action[that.options.mediaType],
                multiple: false,
                forceMultipart: true,
                normalHeaders: false,
                responsePassthrough: true,
                debug: true,
                inputName: 'resource:fileData',
                failedUploadTextDisplay: {mode: 'none'},
                onSubmit: function(file, ext){
                    that.uploader.setParams({
                        service: 'media',
                        action: 'addContent',
                        entryId: that.options.entryId,
                        ks: that.options.ks,
                        'resource:objectType': 'KalturaUploadedFileResource'
                    });
                    return that.options.onSubmit(id, fileName);
                },
                // kaltura returns XML
                onComplete: function(id, fileName, xml){
                    var xmlDoc = $.parseXML(xml);
                    var $xml = $( xmlDoc );
                    //var result = $xml.find( "result" );
                    return that.options.onComplete(id, fileName, xml);
                },
                onUpload: function(id, fileName, xhr) {
                    that.resizePopup();
                    return that.options.onUpload(id, fileName, xhr);
                },
                onProgress: function(id, fileName, loaded, total) {
                    return that.options.onProgress(id, fileName, loaded, total);
                },
                onError: function(id, fileName, reason) {
                    return that.options.onError(id, fileName, reason);
                }
            });
        },
        createFwGenericUploader: function() {
            var that = this;
            that.uploader = new qq.FileUploader({
                element: $('#file-uploader')[0],
                action: that.options.action[that.options.mediaType],
                multiple: false,
                forceMultipart: true,
                normalHeaders: false,
                responsePassthrough: true,
                debug: true,
                inputName: 'resource:fileData',
                failedUploadTextDisplay: {mode: 'none'},
                onSubmit: function(id, fileName){
                    that.uploader.setParams({
                        service: 'media',
                        action: 'addContent',
                        entryId: that.options.entryId,
                        ks: that.options.ks,
                        'resource:objectType': 'KalturaUploadedFileResource'
                    });
                    $(.'qq-uploader').hide().fadeOut('slow');
                    that.options.onSubmit(id, fileName);
                },
                onComplete: function(id, fileName, responseJSON) {
                    var entryId = $(responseJSON).find('id').text();
                    $('#form_entryid').val(entryId);
                    console.log("Video subido correctamente ID: " + entryId);
                    return that.options.onComplete(id, fileName, responseJSON);
                },
                onUpload: function(id, fileName, xhr) {
                    that.resizePopup();
                    return that.options.onUpload(id, fileName, xhr);
                },
                onProgress: function(id, fileName, loaded, total) {
                    if (loaded !== total){
                        $( "#progressbar .bar" ).css('width', Math.round(loaded / total * 100)+'%');
                    } else {
                        $( "#progressbar .bar" ).css('width','100%');
                    }
                    that.resizePopup();
                    return that.options.onProgress(id, fileName, loaded, total);
                },
                onError: function(id, fileName, reason) {
                    return that.options.onError(id, fileName, reason);
                }
            });
        },
        getToken: function(filename, callback) {
            var that = this;
            that.getKs(function(ks){
                console.log("getKs: " + that.options.ks)
                that.getMediaId("filename", function(entryId) {
                    console.log("getMediaId: " + that.options.entryId)
                    $.ajax({
                        url: 'http://www.kaltura.com/api_v3/index.php',
                        data: {
                            service: 'uploadToken',
                            action: 'add',
                            ks: that.options.ks,
                            'uploadToken:fileName': filename,
                            'uploadToken:objectType': 'KalturaUploadToken'
                        },
                        dataType: 'xml',
                        success: function(responseJSON) {
                            if($(responseJSON).find('id').text()) {
                                console.log(responseJSON)
                                that.options.uploadtoken = $(responseJSON).find('id').text();
                                callback(that.options.uploadtoken);
                            } else {
                                that.options.onError($(responseJSON).find('error').text());
                            }
                        },
                        error: function (jqXHR, status, error) {
                            return that.options.onError(error);
                        }
                    });
                });
            });
        },
        getKs: function(callback)
        {
            var that = this;
            $.ajax({
                url: Routing.generate(appLocale + '_video_kaltura_ks'),
                dataType: 'json',
                success: function(responseJSON) {
                    that.options.ks = responseJSON.ks;
                    callback(that.options.ks);
                },
                error: function (jqXHR, status, error) {
                    return that.options.onError(error);
                }
            });
        },
        getMediaId: function(fileName, callback) {
            var that = this;
                $.ajax({
                    url: 'http://www.kaltura.com/api_v3/index.php',
                    data: {
                        service: 'media',
                        action: 'add',
                        ks: that.options.ks,
                        'entry:name': fileName,
                        'entry:objectType': 'KalturaMediaEntry',
                        'entry:mediaType': 1
                    },
                    dataType: 'xml',
                    success: function(responseJSON) {
                        if($(responseJSON).find('id').text()) {
                            that.options.entryId = $(responseJSON).find('id').text();
                            callback(that.options.entryId);
                        } else {
                            that.options.onError($(responseJSON).find('error').text());
                        }
                    },
                    error: function (jqXHR, status, error) {
                        return that.options.onError(error);
                    }
                });
        },
        resizePopup: function() {
            window.top.resizeColorbox({innerHeight: $('.popup-content').height() });
        },
        destroy: function() {
            var that = this;
            $(that.element).unbind("destroyed", that.teardown);
            that.teardown();
        },
        teardown: function() {
            var that = this;
            $.removeData($(that.element)[0], that._name);
            $(that.element).removeClass(that._name);
            $(that.element).removeClass('cboxElement').removeData('colorbox');
            that.unbind();
            //$.colorbox.remove();
            that.element = null;
        },
        bind: function() {  },
        unbind: function() {  }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, pluginName)) {
                $.data(this, pluginName, new Plugin(this, options));
            }
        });
    };

});<|endoftext|>


<commit_before>// ==UserScript==
// @name          GitHub Sort Content
// @version       1.0.5
// @description   A userscript that makes some lists & markdown tables sortable
// @license       https://creativecommons.org/licenses/by-sa/4.0/
// @namespace     http://github.com/Mottie
// @include       https://github.com/*
// @grant         GM_addStyle
// @require       https://cdnjs.cloudflare.com/ajax/libs/tinysort/2.3.6/tinysort.js
// @run-at        document-idle
// @author        Rob Garrison
// @updateURL     https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-sort-content.user.js
// @downloadURL   https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-sort-content.user.js
// ==/UserScript==
/* global GM_addStyle, tinysort */
/* jshint esnext:true, unused:true */
(function() {
  "use strict";
  /* example pages:
    tables - https://github.com/Mottie/GitHub-userscripts
    Contribute repos & Your Repos - https://github.com/
    organization repos - https://github.com/jquery
    organization members - https://github.com/orgs/jquery/people
    pinned repos - https://github.com/addyosmani
    repos - https://github.com/addyosmani?tab=repositories
    stars - https://github.com/stars
  */
  const sorts = ["asc", "desc"],
  icons = {
    white: {
      unsorted : "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTE1IDggMSA4IDggMHpNMTUgOSAxIDkgOCAxNnoiIHN0eWxlPSJmaWxsOiNkZGQ7b3BhY2l0eTowLjIiLz48L3N2Zz4=",
      asc : "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTE1IDggMSA4IDggMHoiIHN0eWxlPSJmaWxsOiNkZGQiLz48cGF0aCBkPSJNMTUgOSAxIDkgOCAxNnoiIHN0eWxlPSJmaWxsOiNkZGQ7b3BhY2l0eTowLjIiLz48L3N2Zz4=",
      desc : "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTE1IDggMSA4IDggMHoiIHN0eWxlPSJmaWxsOiNkZGQ7b3BhY2l0eTowLjIiLz48cGF0aCBkPSJNMTUgOSAxIDkgOCAxNnoiIHN0eWxlPSJmaWxsOiNkZGQiLz48L3N2Zz4="
    },
    black: {
      unsorted : "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTE1IDggMSA4IDggMHpNMTUgOSAxIDkgOCAxNnoiIHN0eWxlPSJmaWxsOiMyMjI7b3BhY2l0eTowLjIiLz48L3N2Zz4=",
      asc : "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTE1IDggMSA4IDggMHoiIHN0eWxlPSJmaWxsOiMyMjIiLz48cGF0aCBkPSJNMTUgOSAxIDkgOCAxNnoiIHN0eWxlPSJmaWxsOiMyMjI7b3BhY2l0eTowLjIiLz48L3N2Zz4=",
      desc : "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTE1IDggMSA4IDggMHoiIHN0eWxlPSJmaWxsOiMyMjI7b3BhY2l0eTowLjIiLz48cGF0aCBkPSJNMTUgOSAxIDkgOCAxNnoiIHN0eWxlPSJmaWxsOiMyMjIiLz48L3N2Zz4="
    }
  },
  // toolbars - target for sort arrows
  regexBars = /\b(filter-bar|org-toolbar|sort-bar|tabnav-tabs)\b/;

  function initSortTable(el) {
    removeSelection();
    let dir = el.classList.contains(sorts[0]) ? sorts[1] : sorts[0],
      table = closest(el, "table");
    tinysort($$("tbody tr", table), {
      order: dir,
      natural: true,
      selector: `td:nth-child(${el.cellIndex + 1})`
    });
    $$("th", table).forEach(elm => {
      elm.classList.remove(...sorts);
    });
    el.classList.add(dir);
  }

  function initSortUl(arrows, list, selector) {
    if (list && list.children) {
      removeSelection();
      let dir = arrows.classList.contains(sorts[0]) ? sorts[1] : sorts[0],
        options = { order: dir, natural: true };
      if (selector) {
        options.selector = selector;
      }
      // using children because the big repo contains UL > DIV
      tinysort(list.children, options);
      arrows.classList.remove(...sorts);
      arrows.classList.add(dir);
    }
  }

  function needDarkTheme() {
    let brightest = 0,
      // color will be "rgb(#, #, #)" or "rgba(#, #, #, #)"
      color = window.getComputedStyle(document.body).backgroundColor,
      rgb = (color || "").replace(/\s/g, "").match(/^rgba?\((\d+),(\d+),(\d+)/i);
    if (rgb) {
      color = rgb.slice(1); // remove "rgb.." part from match
      color.forEach(c => {
        // http://stackoverflow.com/a/15794784/145346
        brightest = Math.max(brightest, parseInt(c, 10));
      });
      // return true if we have a dark background
      return brightest < 128;
    }
    // fallback to bright background
    return false;
  }

  function $(str, el) {
    return (el || document).querySelector(str);
  }
  function $$(str, el) {
    return Array.from((el || document).querySelectorAll(str));
  }
  function closest(el, selector) {
    while (el && el.nodeName !== "BODY" && !el.matches(selector)) {
      el = el.parentNode;
    }
    return el && el.matches(selector) ? el : null;
  }
  function removeSelection() {
    // remove text selection - http://stackoverflow.com/a/3171348/145346
    var sel = window.getSelection ? window.getSelection() : document.selection;
    if (sel) {
      if (sel.removeAllRanges) {
        sel.removeAllRanges();
      } else if (sel.empty) {
        sel.empty();
      }
    }
  }

  function init() {
    let styles = needDarkTheme() ? icons.white : icons.black;

    GM_addStyle(`
      /* unsorted icon */
      .markdown-body table thead th {
        cursor:pointer;
        padding-right:22px !important;
        background:url(${styles.unsorted}) no-repeat calc(100% - 5px) center !important;
      }
      div.js-pinned-repos-reorder-container > h3, .dashboard-sidebar .boxed-group > h3,
      div.filter-repos, div.js-repo-filter .filter-bar, .org-toolbar, .sort-bar,
      h2 + .tabnav > .tabnav-tabs {
        cursor:pointer;
        padding-right:10px;
        background-image:url(${styles.unsorted}) !important;
        background-repeat:no-repeat !important;
        background-position:calc(100% - 5px) center !important;
      }
      /* https://github.com/ */
      div.filter-repos { background-position:calc(100% - 5px) 80% !important; }
      /* https://github.com/:user?tab=repositories */
      div.js-repo-filter .filter-bar { background-position:338px 10px !important; }
      /* https://github.com/:organization */
      .org-toolbar { background-position:calc(100% - 5px) 10px !important; }
      /* https://github.com/stars */
      .sort-bar { background-position:525px 10px !important; }
      /* asc/dec icons */
      table thead th.asc, div.boxed-group h3.asc,
      div.js-repo-filter.asc, div.filter-bar.asc,
      .org-toolbar.asc, .sort-bar.asc, h2 + .tabnav > .tabnav-tabs.asc {
        background-image:url(${styles.asc}) !important;
        background-repeat:no-repeat !important;
      }
      table thead th.desc, div.boxed-group h3.desc,
      div.js-repo-filter.desc, div.filter-bar.desc,
      .org-toolbar.desc, .sort-bar.desc, h2 + .tabnav > .tabnav-tabs.desc {
        background-image:url(${styles.desc}) !important;
        background-repeat:no-repeat !important;
      }
      /* remove sort arrows */
      .popular-repos + div.boxed-group h3 {
        background-image:none !important;
        cursor:default;
      }
      /* Remove margin that overlaps sort arrow - https://github.com/:user?tab=repositories */
      .filter-bar li:last-child { margin-left: 0 !important; }
      /* move "Customize your pinned..." - https://github.com/:self */
      .pinned-repos-setting-link { margin-right:14px; }
    `);

    document.body.addEventListener("click", event => {
      let el,
        target = event.target,
        name = target.nodeName;
      if (target && target.nodeType === 1 && (
        // nodes th|h3 - form for stars page
        name === "H3" || name === "TH" || name === "FORM" ||
        // mini-repo & https://github.com/:user?tab=repositories (filter-bar)
        // https://github.com/:organization filter bar (org-toolbar)
        // https://github.com/stars (sort-bar)
        regexBars.test(target.className)
      )) {
        // don't sort tables not inside of markdown
        if (name === "TH" && closest(target, ".markdown-body")) {
          return initSortTable(target);
        }

        // following
        el = $("ol.follow-list", closest(target, ".container"));
        if (el) {
          return initSortUl(target, el, ".follow-list-name a");
        }

        // organization people - https://github.com/orgs/:organization/people
        el = $("ul.member-listing", target.parentNode);
        if (el) {
          return initSortUl(target, el, ".member-link");
        }

        // big repo list - https://github.com/:user?tab=repositories
        // stars - https://github.com/stars
        el = closest(target, ".sort-bar, .filter-bar, .org-toolbar");
        if (el && $(".repo-list", el.parentNode)) {
          return initSortUl(el, $(".repo-list", el.parentNode), ".repo-list-name a");
        }

        // mini-repo listings with & without filter - https://github.com/
        el = closest(target, ".boxed-group");
        // prevent clicking on the H3 header of filtered repos
        if (el && !(name === "H3" && el.classList.contains("js-repo-filter"))) {
          return initSortUl(target, $(".mini-repo-list", el));
        }
      }
    });
  }

  init();

})();
<commit_msg>Sort-Content: Clean up code & Fix sorting issue on main page repo boxes<commit_after>// ==UserScript==
// @name          GitHub Sort Content
// @version       1.0.6
// @description   A userscript that makes some lists & markdown tables sortable
// @license       https://creativecommons.org/licenses/by-sa/4.0/
// @namespace     http://github.com/Mottie
// @include       https://github.com/*
// @grant         GM_addStyle
// @require       https://cdnjs.cloudflare.com/ajax/libs/tinysort/2.3.6/tinysort.min.js
// @run-at        document-idle
// @author        Rob Garrison
// @updateURL     https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-sort-content.user.js
// @downloadURL   https://raw.githubusercontent.com/Mottie/GitHub-userscripts/master/github-sort-content.user.js
// ==/UserScript==
/* global GM_addStyle, tinysort */
/* jshint esnext:true, unused:true */
(() => {
	"use strict";
	/* example pages:
	tables - https://github.com/Mottie/GitHub-userscripts
	Contribute repos & Your Repos - https://github.com/
	organization repos - https://github.com/jquery
	organization members - https://github.com/orgs/jquery/people
	pinned repos - https://github.com/addyosmani
	repos - https://github.com/addyosmani?tab=repositories
	stars - https://github.com/stars
	*/
	const sorts = ["asc", "desc"],
		icons = {
			white: {
				unsorted: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTE1IDggMSA4IDggMHpNMTUgOSAxIDkgOCAxNnoiIHN0eWxlPSJmaWxsOiNkZGQ7b3BhY2l0eTowLjIiLz48L3N2Zz4=",
				asc: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTE1IDggMSA4IDggMHoiIHN0eWxlPSJmaWxsOiNkZGQiLz48cGF0aCBkPSJNMTUgOSAxIDkgOCAxNnoiIHN0eWxlPSJmaWxsOiNkZGQ7b3BhY2l0eTowLjIiLz48L3N2Zz4=",
				desc: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTE1IDggMSA4IDggMHoiIHN0eWxlPSJmaWxsOiNkZGQ7b3BhY2l0eTowLjIiLz48cGF0aCBkPSJNMTUgOSAxIDkgOCAxNnoiIHN0eWxlPSJmaWxsOiNkZGQiLz48L3N2Zz4="
			},
			black: {
				unsorted: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTE1IDggMSA4IDggMHpNMTUgOSAxIDkgOCAxNnoiIHN0eWxlPSJmaWxsOiMyMjI7b3BhY2l0eTowLjIiLz48L3N2Zz4=",
				asc: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTE1IDggMSA4IDggMHoiIHN0eWxlPSJmaWxsOiMyMjIiLz48cGF0aCBkPSJNMTUgOSAxIDkgOCAxNnoiIHN0eWxlPSJmaWxsOiMyMjI7b3BhY2l0eTowLjIiLz48L3N2Zz4=",
				desc: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTE1IDggMSA4IDggMHoiIHN0eWxlPSJmaWxsOiMyMjI7b3BhY2l0eTowLjIiLz48cGF0aCBkPSJNMTUgOSAxIDkgOCAxNnoiIHN0eWxlPSJmaWxsOiMyMjIiLz48L3N2Zz4="
			}
		},
		// toolbars - target for sort arrows
		regexBars = /\b(filter-bar|org-toolbar|sort-bar|tabnav-tabs)\b/;

	function initSortTable(el) {
		removeSelection();
		const dir = el.classList.contains(sorts[0]) ? sorts[1] : sorts[0],
			table = closest(el, "table");
		tinysort($$("tbody tr", table), {
			order: dir,
			natural: true,
			selector: `td:nth-child(${el.cellIndex + 1})`
		});
		$$("th", table).forEach(elm => {
			elm.classList.remove(...sorts);
		});
		el.classList.add(dir);
	}

	function initSortUl(arrows, list, selector) {
		if (list && list.children) {
			removeSelection();
			const dir = arrows.classList.contains(sorts[0]) ? sorts[1] : sorts[0],
				options = {order: dir, natural: true};
			if (selector) {
				options.selector = selector;
			}
			// using children because the big repo contains UL > DIV
			tinysort(list.children, options);
			arrows.classList.remove(...sorts);
			arrows.classList.add(dir);
		}
	}

	function needDarkTheme() {
		let brightest = 0,
			// color will be "rgb(#, #, #)" or "rgba(#, #, #, #)"
			color = window.getComputedStyle(document.body).backgroundColor;
		const rgb = (color || "").replace(/\s/g, "").match(/^rgba?\((\d+),(\d+),(\d+)/i);
		if (rgb) {
			color = rgb.slice(1); // remove "rgb.." part from match
			color.forEach(c => {
				// http://stackoverflow.com/a/15794784/145346
				brightest = Math.max(brightest, parseInt(c, 10));
			});
			// return true if we have a dark background
			return brightest < 128;
		}
		// fallback to bright background
		return false;
	}

	function $(str, el) {
		return (el || document).querySelector(str);
	}
	function $$(str, el) {
		return Array.from((el || document).querySelectorAll(str));
	}
	function closest(el, selector) {
		while (el && el.nodeName !== "BODY" && !el.matches(selector)) {
			el = el.parentNode;
		}
		return el && el.matches(selector) ? el : null;
	}
	function removeSelection() {
		// remove text selection - http://stackoverflow.com/a/3171348/145346
		const sel = window.getSelection ? window.getSelection() : document.selection;
		if (sel) {
			if (sel.removeAllRanges) {
				sel.removeAllRanges();
			} else if (sel.empty) {
				sel.empty();
			}
		}
	}

	function init() {
		const styles = needDarkTheme() ? icons.white : icons.black;

		GM_addStyle(`
		/* unsorted icon */
		.markdown-body table thead th {
			cursor:pointer;
			padding-right:22px !important;
			background:url(${styles.unsorted}) no-repeat calc(100% - 5px) center !important;
		}
		div.js-pinned-repos-reorder-container > h3, .dashboard-sidebar .boxed-group > h3,
		div.filter-repos, div.js-repo-filter .filter-bar, .org-toolbar, .sort-bar,
		h2 + .tabnav > .tabnav-tabs {
			cursor:pointer;
			padding-right:10px;
			background-image:url(${styles.unsorted}) !important;
			background-repeat:no-repeat !important;
			background-position:calc(100% - 5px) center !important;
		}
		/* https://github.com/ -> your repositories */
		.dashboard-sidebar .user-repos h3 { background-position: 175px 10px !important; }
		/* https://github.com/:user?tab=repositories */
		div.js-repo-filter .filter-bar { background-position:338px 10px !important; }
		/* https://github.com/:organization */
		.org-toolbar { background-position:calc(100% - 5px) 10px !important; }
		/* https://github.com/stars */
		.sort-bar { background-position:525px 10px !important; }
		/* asc/dec icons */
		table thead th.asc, div.boxed-group h3.asc,
		div.js-repo-filter.asc, div.filter-bar.asc,
		.org-toolbar.asc, .sort-bar.asc, h2 + .tabnav > .tabnav-tabs.asc {
			background-image:url(${styles.asc}) !important;
			background-repeat:no-repeat !important;
		}
		table thead th.desc, div.boxed-group h3.desc,
		div.js-repo-filter.desc, div.filter-bar.desc,
		.org-toolbar.desc, .sort-bar.desc, h2 + .tabnav > .tabnav-tabs.desc {
			background-image:url(${styles.desc}) !important;
			background-repeat:no-repeat !important;
		}
		/* remove sort arrows */
		.popular-repos + div.boxed-group h3 {
			background-image:none !important;
			cursor:default;
		}
		/* Remove margin that overlaps sort arrow - https://github.com/:user?tab=repositories */
		.filter-bar li:last-child { margin-left: 0 !important; }
		/* move "Customize your pinned..." - https://github.com/:self */
		.pinned-repos-setting-link { margin-right:14px; }
		`);

		document.body.addEventListener("click", event => {
			let el;
			const target = event.target,
				name = target.nodeName;
			if (target && target.nodeType === 1 && (
				// nodes th|h3 - form for stars page
				name === "H3" || name === "TH" || name === "FORM" ||
				// mini-repo & https://github.com/:user?tab=repositories (filter-bar)
				// https://github.com/:organization filter bar (org-toolbar)
				// https://github.com/stars (sort-bar)
				regexBars.test(target.className)
			)) {
				// don't sort tables not inside of markdown
				if (name === "TH" && closest(target, ".markdown-body")) {
					return initSortTable(target);
				}

				// following
				el = $("ol.follow-list", closest(target, ".container"));
				if (el) {
					return initSortUl(target, el, ".follow-list-name a");
				}

				// organization people - https://github.com/orgs/:organization/people
				el = $("ul.member-listing", target.parentNode);
				if (el) {
					return initSortUl(target, el, ".member-link");
				}

				// big repo list - https://github.com/:user?tab=repositories
				// stars - https://github.com/stars
				el = closest(target, ".sort-bar, .filter-bar, .org-toolbar");
				if (el && $(".repo-list", el.parentNode)) {
					return initSortUl(el, $(".repo-list", el.parentNode), ".repo-list-name a");
				}

				// mini-repo listings with & without filter - https://github.com/
				// and pinned repo lists
				el = closest(target, ".boxed-group");
				// prevent clicking on the H3 header of filtered repos
				if (el && name === "H3" && (
				el.classList.contains("js-repo-filter") ||
				el.classList.contains("js-pinned-repos-reorder-container")
				)) {
					return initSortUl(target, $(".mini-repo-list", el));
				}
			}
		});
	}

	init();
})();
<|endoftext|>