Netfix QueueSorter (chrome) - Помощь по изменению скрипта для сортировки групп по алфавиту - PullRequest
0 голосов
/ 29 декабря 2010

У меня установлен сортировщик очереди Netflix в качестве расширения.Тем не менее, он случайным образом назначает порядок фильмов в жанре.Я хочу отсортировать по имени в жанре.

Я открываю C: \ Users \ MyUserName \ AppData \ Local \ Google \ Chrome \ Данные пользователя \ Default \ Extensions \ ExtensionId \ 1.13_0 \ script.js иЯ вижу, что JavaScript все еще нуждается в некоторой работе.Вот мой модифицированный метод, который сортирует по названию и жанру.

function sortByTitleAndGenre() {
    var articles;
    sortInfo = [];
    var pos = 1;

    var articlesKey = 'sortByTitle.articles';
    var ignoreArticlesKey = 'sortByTitle.ignoreArticles';
    var ignoreArticles = GM_getValue(ignoreArticlesKey);
    if (undefined === ignoreArticles) {
        // Use true as default as Netflix ignores articles too.
        ignoreArticles = true;

        // Store keys so that users can change it via about:config.
        GM_setValue(ignoreArticlesKey, ignoreArticles);
        // The articles are used "as-is", so there must be a space after
        // each one in most cases.  To avoid typos in the default, use [].
        articles = [
            "A ",
            "AN ",
            "THE ",
            "EL ",
            "LA ",
            "LE ",
            "LES ",
            "IL ",
            "L'"
        ];
        GM_setValue(articlesKey, articles.join(',').toUpperCase());
    }

    var elts = customGetElementsByClassName(document, 'input', 'o');
    for (var idx = 0; idx < elts.length; idx++) {
        var boxName = elts[idx].name;
        var boxId = boxName.substring(2);
        // If a movie is both at home and in the queue, or a movie has been
        // watched but is still in the queue, there is both _0 and _1.
        // Here we either one works.
        var titleId = 'b0' + boxId + '_0';
        var titleElt = document.getElementById(titleId);

        var genre = $("tr[data-mid='" + boxId + "'] .gn .genre").text().toUpperCase();

        var title = titleElt.innerHTML.toUpperCase();
        if (ignoreArticles) {
            // Get the articles, but default to empty string.
            var articlesStr = GM_getValue(articlesKey, '') || '';
            articlesStr = articlesStr.toUpperCase();
            articles = articlesStr.split(',');
            for (var aa = 0; aa < articles.length; aa++) {
                var article = articles[aa].toUpperCase();
                if (0 === title.indexOf(article)) {
                    // Move article to the end of the string.
                    title = title.substring(article.length) +
                            ', ' + article;
                    break;
                }
            }
        }

        var record = {
            "id": boxId,
            "title": title,
            "genre": genre,
            "origPos": pos++
        };
        sortInfo.push(record);
    }

    var sortFn = function (a, b) {
        if (a.genre == b.genre)
            return a.title > b.title ? -1 : 1;
        else
            return a.genre > b.genre ? -1 : 1;
    };
    sortInfo.sort(sortFn);

    setOrder("origPos", elts);
}

Моя проблема в том, что, хотя он сортируется нормально, он не игнорирует статьи.Моя функция сортировки отключена?Я думаю, что это может быть определено более кратко (в одну строку).

    var sortFn = function (a, b) {
        if (a.genre == b.genre)
            return a.title > b.title ? -1 : 1;
        else
            return a.genre > b.genre ? -1 : 1;
    };

1 Ответ

0 голосов
/ 30 декабря 2010

Я понял это. Код был создан, чтобы установить массив статей пустым. Это небольшой WTF, но я исправил его несколькими комментариями.

//var articlesStr = GM_getValue(articlesKey, '') || '';
//articlesStr = articlesStr.toUpperCase();
//articles = articlesStr.split(',');

для тех, кто использует это расширение, я исправил его, добавив в расширение библиотеку jquery. Я добавил ссылку на него в manifest.json.

Затем просто замените существующий sortByGenre этим методом

function sortByGenre() {
    var articles;
    sortInfo = [];
    var pos = 1;

    var articlesKey = 'sortByTitle.articles';
    var ignoreArticlesKey = 'sortByTitle.ignoreArticles';
    var ignoreArticles = GM_getValue(ignoreArticlesKey);
    if (undefined === ignoreArticles) {
        // Use true as default as Netflix ignores articles too.
        ignoreArticles = true;

        // Store keys so that users can change it via about:config.
        GM_setValue(ignoreArticlesKey, ignoreArticles);
        // The articles are used "as-is", so there must be a space after
        // each one in most cases.  To avoid typos in the default, use [].
        articles = [
            "A ",
            "AN ",
            "THE ",
            "EL ",
            "LA ",
            "LE ",
            "LES ",
            "IL ",
            "L'"
        ];
        //GM_setValue(articlesKey, articles.join(',').toUpperCase());
    }

    var elts = customGetElementsByClassName(document, 'input', 'o');
    for (var idx = 0; idx < elts.length; idx++) {
        var boxName = elts[idx].name;
        var boxId = boxName.substring(2);
        // If a movie is both at home and in the queue, or a movie has been
        // watched but is still in the queue, there is both _0 and _1.
        // Here we either one works.
        var titleId = 'b0' + boxId + '_0';
        var titleElt = document.getElementById(titleId);

        var genre = $("tr[data-mid='" + boxId + "'] .gn .genre").text().toUpperCase();

        var title = titleElt.innerHTML.toUpperCase();
        if (ignoreArticles) {
            // Get the articles, but default to empty string.
            //var articlesStr = GM_getValue(articlesKey, '') || '';
            //articlesStr = articlesStr.toUpperCase();
            //articles = articlesStr.split(',');
            for (var aa = 0; aa < articles.length; aa++) {
                var article = articles[aa].toUpperCase();
                if (0 === title.indexOf(article)) {
                    // Move article to the end of the string.
                    title = title.substring(article.length) +
                            ', ' + article;
                    break;
                }
            }
        }

        var record = {
            "id": boxId,
            "title": title,
            "genre": genre,
            "origPos": pos++
        };
        sortInfo.push(record);
    }

    var sortFn = function (a, b) {
        if (a.genre == b.genre)
            return a.title > b.title ? -1 : 1;
        else
            return a.genre > b.genre ? -1 : 1;
    };
    sortInfo.sort(sortFn);

    setOrder("origPos", elts);
}

Как только вы это сделаете, вы можете перейти в режим разработчика в Chrome и либо загрузить его распакованным, либо упаковать его как crx, перейти к файлу в Chrome и установить расширение.

...