<commit_before>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

require(["jquery","sakai/sakai.api.core"], function($, sakai) {

    sakai_global.content_profile = function(){

        var previous_content_path = false;
        var content_path = ""; // The current path of the content
        var ready_event_fired = 0;
        var list_event_fired = false;
        var intervalId;

        var showPreview = true;
        var collectionID = false;
        var collectionName = false;
        var isCollection = false;

        ///////////////////////////////
        // PRIVATE UTILITY FUNCTIONS //
        ///////////////////////////////

        /**
         * Load the content profile for the current content path
         * @param {Boolean} ignoreActivity Flag to also update activity data or not
         */
        var loadContentProfile = function(callback, ignoreActivity){
            // Check whether there is actually a content path in the URL
            if (content_path) {
                // Get the content information, the members and managers and version information
                sakai.api.Content.loadFullProfile(content_path, function(success, data){
                    if (success) {
                        if (data.results.hasOwnProperty(0)) {
                            var contentInfo = false;
                            if (data.results[0]["status"] === 404){
                                sakai.api.Security.send404();
                                return;
                            } else if (data.results[0]["status"] === 403){
                                sakai.api.Security.send403();
                                return;
                            } else {
                                contentInfo = $.parseJSON(data.results[0].body);
                                if (contentInfo["_mimeType"] && contentInfo["_mimeType"] === "x-sakai/document" || contentInfo["_mimeType"] && contentInfo["_mimeType"] === "x-sakai/collection"){
                                    showPreview = false;
                                } else {
                                    setColumnLayout(false, false);
                                }

                                var collectionId = $.bbq.getState("collectionId");
                                var collectionName = $.bbq.getState("collectionName");
                                var currentPath = $.bbq.getState("p");
                                if(collectionId && collectionName && currentPath){
                                    // Show go back to collection link
                                    $("#back_to_collection_button #collection_title").text(collectionName);
                                    $("#back_to_collection_button").attr("href", "/content#p=" + collectionId + "/" + sakai.api.Util.safeURL(collectionName) + "&item=" + currentPath.split("/")[0]);
                                    $('#back_to_collection_container').show();
                                } else {
                                    $('#back_to_collection_container').hide();
                                }
                            }
                        }

                        sakai.api.Content.parseFullProfile(data.results, function(parsedData){
                            parsedData.mode = "content";
                            sakai_global.content_profile.content_data = parsedData;
                            $(window).trigger("ready.contentprofile.sakai", sakai_global.content_profile.content_data);
                            if ($.isFunction(callback)) {
                                callback(true);
                            }
                            initEntityWidget();

                            if (!showPreview){
                                renderSakaiDoc(parsedData.data);
                            }
                        });
                    }
                });
            } else {
                sakai.api.Security.send404();
            }
        };

        var initEntityWidget = function(){
            if (sakai_global.content_profile.content_data) {
                var context = "content";
                if (sakai.data.me.user.anon) {
                    type = "content_anon";
                } else if (sakai_global.content_profile.content_data.isManager) {
                    type = "content_managed";
                } else if (sakai_global.content_profile.content_data.isEditor) {
                    type = 'content_edited';
                } else if (sakai_global.content_profile.content_data.isViewer) {
                    type = "content_shared";
                } else {
                    type = "content_not_shared";
                }
                $(window).trigger("sakai.entity.init", [context, type, sakai_global.content_profile.content_data]);
            }
        };

        $(window).bind("sakai.entity.ready", function(){
            initEntityWidget();
        });

        $(window).bind("load.content_profile.sakai", function(e, callback) {
            loadContentProfile(callback);
        });

        var handleHashChange = function() {
            content_path = $.bbq.getState("p") || "";
            content_path = content_path.split("/");
            content_path = "/p/" + content_path[0];

            if (content_path != previous_content_path) {
                $('#contentauthoring_widget').html('');
                previous_content_path = content_path;
                globalPageStructure = false;
                loadContentProfile(function(){
                    // The request was successful so initialise the entity widget
                    if (sakai_global.entity && sakai_global.entity.isReady) {
                        $(window).trigger("render.entity.sakai", ["content", sakai_global.content_profile.content_data]);
                    }
                    else {
                        $(window).bind("ready.entity.sakai", function(e){
                            $(window).trigger("render.entity.sakai", ["content", sakai_global.content_profile.content_data]);
                            ready_event_fired++;
                        });
                    }
                    // The request was successful so initialise the relatedcontent widget
                    if (sakai_global.relatedcontent && sakai_global.relatedcontent.isReady) {
                        $(window).trigger("render.relatedcontent.sakai", sakai_global.content_profile.content_data);
                    }
                    else {
                        $(window).bind("ready.relatedcontent.sakai", function(e){
                            $(window).trigger("render.relatedcontent.sakai", sakai_global.content_profile.content_data);
                            ready_event_fired++;
                        });
                    }
                    // The request was successful so initialise the relatedcontent widget
                    if (sakai_global.contentpreview && sakai_global.contentpreview.isReady) {
                        if (showPreview) {
                            $(window).trigger("start.contentpreview.sakai", sakai_global.content_profile.content_data);
                        }
                    }
                    else {
                        $(window).bind("ready.contentpreview.sakai", function(e){
                            if (showPreview) {
                                $(window).trigger("start.contentpreview.sakai", sakai_global.content_profile.content_data);
                                ready_event_fired++;
                            }
                        });
                    }
                    // The request was successful so initialise the metadata widget
                    if (sakai_global.contentmetadata && sakai_global.contentmetadata.isReady) {
                        $(window).trigger("render.contentmetadata.sakai");
                    }
                    else {
                        $(window).bind("ready.contentmetadata.sakai", function(e){
                            $(window).trigger("render.contentmetadata.sakai");
                            ready_event_fired++;
                        });
                    }
                    sakai.api.Security.showPage();
                    sakai.api.Util.setPageTitle(
                        ' ' + sakai_global.content_profile.content_data.data['sakai:pooled-content-file-name'],
                        'pageLevel'
                    );

                    // rerender comments widget
                    $(window).trigger("content_profile_hash_change");
                });
            }
            showPreview = true;
        };

        $("#entity_content_share").live("click", function(){
            $(window).trigger("init.sharecontent.sakai");
            return false;
        });

        $("#entity_content_add_to_library").live("click", function(){
            sakai.api.Content.addToLibrary(sakai_global.content_profile.content_data.data["_path"], sakai.data.me.user.userid, false, function(){
                $("#entity_content_add_to_library").hide();
                sakai.api.Util.notification.show($("#content_profile_add_library_title").html(), $("#content_profile_add_library_body").html());
            });
        });

        ////////////////////
        // Initialisation //
        ////////////////////

        /**
         * Initialise the content profile page
         */
        var init = function(){
            // Bind an event to window.onhashchange that, when the history state changes,
            // loads all the information for the current resource
            $(window).bind('hashchange', function(){
                handleHashChange();
            });
            handleHashChange();
        };

        // //////////////////////////
        // Dealing with Sakai docs //
        /////////////////////////////

        var globalPageStructure = false;

        var generateNav = function(pagestructure){
            if (pagestructure) {
                $(window).trigger("lhnav.init", [pagestructure, {}, {
                    parametersToCarryOver: {
                        "p": sakai_global.content_profile.content_data.content_path.replace("/p/", "")
                    }
                }, sakai_global.content_profile.content_data.content_path]);
            }
        };

        $(window).bind("lhnav.ready", function(){
            generateNav(globalPageStructure);
        });

        var getPageCount = function(pagestructure){
            var pageCount = 0;
            for (var tl in pagestructure["structure0"]){
                if (pagestructure["structure0"].hasOwnProperty(tl) && tl !== "_childCount"){
                    pageCount++;
                    if (pageCount >= 3){
                        return 3;
                    }
                    for (var ll in pagestructure["structure0"][tl]){
                        if (ll.substring(0,1) !== "_"){
                            pageCount++;
                            if (pageCount >= 3){
                                return 3;
                            }
                        }
                    }
                }
            }
            return pageCount;
        };

        $(window).bind("sakai.contentauthoring.needsTwoColumns", function(){
            setColumnLayout(true, true);
        });

        $(window).bind("sakai.contentauthoring.needsOneColumn", function(){
            setColumnLayout(true, false);
        });

        var setEditProperty = function(structure, manager, editor) {
            for (var i in structure) {
                if (structure.hasOwnProperty(i)) {
                    structure[i]._canEdit = manager || editor;
                    structure[i]._canSubedit = manager || editor;
                }
            }
            return structure;
        };

        var renderSakaiDoc = function(pagestructure) {
            pagestructure = sakai.api.Server.cleanUpSakaiDocObject(pagestructure);
            pagestructure.structure0 = setEditProperty(pagestructure.structure0, sakai_global.content_profile.content_data.isManager, sakai_global.content_profile.content_data.isEditor);
            if (getPageCount(pagestructure) >= 3) {
                setColumnLayout(true, true);
            } else {
                setColumnLayout(true, false);
            }
            globalPageStructure = pagestructure;
            generateNav(pagestructure);
        };

        var setColumnLayout = function(isSakaiDoc, isTwoColumn) {
            $('body').toggleClass('has_nav', isTwoColumn);
            $('#content_profile_preview_container').toggle(!isSakaiDoc);
            $('#content_profile_contentauthoring_container').toggle(isSakaiDoc);
            $('#content_profile_left_column').toggle(isTwoColumn);
            $('#content_profile_main_container').toggleClass('s3d-twocolumn', isTwoColumn);
            $('#content_profile_right_container').toggleClass('s3d-page-column-right', isTwoColumn);
            $('#content_profile_right_metacomments').toggleClass('fl-container-650', !isTwoColumn).toggleClass('fl-container-470', isTwoColumn);
        };

        // Initialise the content profile page
        init();

    };

    sakai.api.Widgets.Container.registerForLoad("content_profile");
});
<commit_msg>SAKIII-6097 fixed threedots of topnav displayname on content profile page<commit_after>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

require(["jquery","sakai/sakai.api.core"], function($, sakai) {

    sakai_global.content_profile = function(){

        var previous_content_path = false;
        var content_path = ""; // The current path of the content
        var ready_event_fired = 0;
        var list_event_fired = false;
        var intervalId;

        var showPreview = true;
        var collectionID = false;
        var collectionName = false;
        var isCollection = false;

        ///////////////////////////////
        // PRIVATE UTILITY FUNCTIONS //
        ///////////////////////////////

        /**
         * Load the content profile for the current content path
         * @param {Boolean} ignoreActivity Flag to also update activity data or not
         */
        var loadContentProfile = function(callback, ignoreActivity){
            // Check whether there is actually a content path in the URL
            if (content_path) {
                // Get the content information, the members and managers and version information
                sakai.api.Content.loadFullProfile(content_path, function(success, data){
                    if (success) {
                        if (data.results.hasOwnProperty(0)) {
                            var contentInfo = false;
                            if (data.results[0]["status"] === 404){
                                sakai.api.Security.send404();
                                return;
                            } else if (data.results[0]["status"] === 403){
                                sakai.api.Security.send403();
                                return;
                            } else {
                                contentInfo = $.parseJSON(data.results[0].body);
                                if (contentInfo["_mimeType"] && contentInfo["_mimeType"] === "x-sakai/document" || contentInfo["_mimeType"] && contentInfo["_mimeType"] === "x-sakai/collection"){
                                    showPreview = false;
                                } else {
                                    setColumnLayout(false, false);
                                }

                                var collectionId = $.bbq.getState("collectionId");
                                var collectionName = $.bbq.getState("collectionName");
                                var currentPath = $.bbq.getState("p");
                                if(collectionId && collectionName && currentPath){
                                    // Show go back to collection link
                                    $("#back_to_collection_button #collection_title").text(collectionName);
                                    $("#back_to_collection_button").attr("href", "/content#p=" + collectionId + "/" + sakai.api.Util.safeURL(collectionName) + "&item=" + currentPath.split("/")[0]);
                                    $('#back_to_collection_container').show();
                                } else {
                                    $('#back_to_collection_container').hide();
                                }
                            }
                        }

                        sakai.api.Content.parseFullProfile(data.results, function(parsedData){
                            parsedData.mode = "content";
                            sakai_global.content_profile.content_data = parsedData;
                            $(window).trigger("ready.contentprofile.sakai", sakai_global.content_profile.content_data);
                            if ($.isFunction(callback)) {
                                callback(true);
                            }
                            initEntityWidget();

                            if (!showPreview){
                                renderSakaiDoc(parsedData.data);
                            }
                        });
                    }
                });
            } else {
                sakai.api.Security.send404();
            }
        };

        var initEntityWidget = function(){
            if (sakai_global.content_profile.content_data) {
                var context = "content";
                if (sakai.data.me.user.anon) {
                    type = "content_anon";
                } else if (sakai_global.content_profile.content_data.isManager) {
                    type = "content_managed";
                } else if (sakai_global.content_profile.content_data.isEditor) {
                    type = 'content_edited';
                } else if (sakai_global.content_profile.content_data.isViewer) {
                    type = "content_shared";
                } else {
                    type = "content_not_shared";
                }
                $(window).trigger("sakai.entity.init", [context, type, sakai_global.content_profile.content_data]);
            }
        };

        $(window).bind("sakai.entity.ready", function(){
            initEntityWidget();
        });

        $(window).bind("load.content_profile.sakai", function(e, callback) {
            loadContentProfile(callback);
        });

        var handleHashChange = function() {
            content_path = $.bbq.getState("p") || "";
            content_path = content_path.split("/");
            content_path = "/p/" + content_path[0];

            if (content_path != previous_content_path) {
                $('#contentauthoring_widget').html('');
                previous_content_path = content_path;
                globalPageStructure = false;
                sakai.api.Security.showPage();
                loadContentProfile(function(){
                    // The request was successful so initialise the entity widget
                    if (sakai_global.entity && sakai_global.entity.isReady) {
                        $(window).trigger("render.entity.sakai", ["content", sakai_global.content_profile.content_data]);
                    }
                    else {
                        $(window).bind("ready.entity.sakai", function(e){
                            $(window).trigger("render.entity.sakai", ["content", sakai_global.content_profile.content_data]);
                            ready_event_fired++;
                        });
                    }
                    // The request was successful so initialise the relatedcontent widget
                    if (sakai_global.relatedcontent && sakai_global.relatedcontent.isReady) {
                        $(window).trigger("render.relatedcontent.sakai", sakai_global.content_profile.content_data);
                    }
                    else {
                        $(window).bind("ready.relatedcontent.sakai", function(e){
                            $(window).trigger("render.relatedcontent.sakai", sakai_global.content_profile.content_data);
                            ready_event_fired++;
                        });
                    }
                    // The request was successful so initialise the relatedcontent widget
                    if (sakai_global.contentpreview && sakai_global.contentpreview.isReady) {
                        if (showPreview) {
                            $(window).trigger("start.contentpreview.sakai", sakai_global.content_profile.content_data);
                        }
                    }
                    else {
                        $(window).bind("ready.contentpreview.sakai", function(e){
                            if (showPreview) {
                                $(window).trigger("start.contentpreview.sakai", sakai_global.content_profile.content_data);
                                ready_event_fired++;
                            }
                        });
                    }
                    // The request was successful so initialise the metadata widget
                    if (sakai_global.contentmetadata && sakai_global.contentmetadata.isReady) {
                        $(window).trigger("render.contentmetadata.sakai");
                    }
                    else {
                        $(window).bind("ready.contentmetadata.sakai", function(e){
                            $(window).trigger("render.contentmetadata.sakai");
                            ready_event_fired++;
                        });
                    }
                    sakai.api.Util.setPageTitle(
                        ' ' + sakai_global.content_profile.content_data.data['sakai:pooled-content-file-name'],
                        'pageLevel'
                    );

                    // rerender comments widget
                    $(window).trigger("content_profile_hash_change");
                });
            }
            showPreview = true;
        };

        $("#entity_content_share").live("click", function(){
            $(window).trigger("init.sharecontent.sakai");
            return false;
        });

        $("#entity_content_add_to_library").live("click", function(){
            sakai.api.Content.addToLibrary(sakai_global.content_profile.content_data.data["_path"], sakai.data.me.user.userid, false, function(){
                $("#entity_content_add_to_library").hide();
                sakai.api.Util.notification.show($("#content_profile_add_library_title").html(), $("#content_profile_add_library_body").html());
            });
        });

        ////////////////////
        // Initialisation //
        ////////////////////

        /**
         * Initialise the content profile page
         */
        var init = function(){
            // Bind an event to window.onhashchange that, when the history state changes,
            // loads all the information for the current resource
            $(window).bind('hashchange', function(){
                handleHashChange();
            });
            handleHashChange();
        };

        // //////////////////////////
        // Dealing with Sakai docs //
        /////////////////////////////

        var globalPageStructure = false;

        var generateNav = function(pagestructure){
            if (pagestructure) {
                $(window).trigger("lhnav.init", [pagestructure, {}, {
                    parametersToCarryOver: {
                        "p": sakai_global.content_profile.content_data.content_path.replace("/p/", "")
                    }
                }, sakai_global.content_profile.content_data.content_path]);
            }
        };

        $(window).bind("lhnav.ready", function(){
            generateNav(globalPageStructure);
        });

        var getPageCount = function(pagestructure){
            var pageCount = 0;
            for (var tl in pagestructure["structure0"]){
                if (pagestructure["structure0"].hasOwnProperty(tl) && tl !== "_childCount"){
                    pageCount++;
                    if (pageCount >= 3){
                        return 3;
                    }
                    for (var ll in pagestructure["structure0"][tl]){
                        if (ll.substring(0,1) !== "_"){
                            pageCount++;
                            if (pageCount >= 3){
                                return 3;
                            }
                        }
                    }
                }
            }
            return pageCount;
        };

        $(window).bind("sakai.contentauthoring.needsTwoColumns", function(){
            setColumnLayout(true, true);
        });

        $(window).bind("sakai.contentauthoring.needsOneColumn", function(){
            setColumnLayout(true, false);
        });

        var setEditProperty = function(structure, manager, editor) {
            for (var i in structure) {
                if (structure.hasOwnProperty(i)) {
                    structure[i]._canEdit = manager || editor;
                    structure[i]._canSubedit = manager || editor;
                }
            }
            return structure;
        };

        var renderSakaiDoc = function(pagestructure) {
            pagestructure = sakai.api.Server.cleanUpSakaiDocObject(pagestructure);
            pagestructure.structure0 = setEditProperty(pagestructure.structure0, sakai_global.content_profile.content_data.isManager, sakai_global.content_profile.content_data.isEditor);
            if (getPageCount(pagestructure) >= 3) {
                setColumnLayout(true, true);
            } else {
                setColumnLayout(true, false);
            }
            globalPageStructure = pagestructure;
            generateNav(pagestructure);
        };

        var setColumnLayout = function(isSakaiDoc, isTwoColumn) {
            $('body').toggleClass('has_nav', isTwoColumn);
            $('#content_profile_preview_container').toggle(!isSakaiDoc);
            $('#content_profile_contentauthoring_container').toggle(isSakaiDoc);
            $('#content_profile_left_column').toggle(isTwoColumn);
            $('#content_profile_main_container').toggleClass('s3d-twocolumn', isTwoColumn);
            $('#content_profile_right_container').toggleClass('s3d-page-column-right', isTwoColumn);
            $('#content_profile_right_metacomments').toggleClass('fl-container-650', !isTwoColumn).toggleClass('fl-container-470', isTwoColumn);
        };

        // Initialise the content profile page
        init();

    };

    sakai.api.Widgets.Container.registerForLoad("content_profile");
});
<|endoftext|>


<commit_before>
var express = require('express');
var unixlib = require('./deps/unixlib/build/Release/unixlib');
var crypto = require('crypto');

var config = require('./config');

var auth = require('../bindings/build/Release/rs_serve_auth');

var app = express();

module.exports = app;

var STATE = {
  sessions: {}
};

function generateToken(bytes, callback) {
  crypto.randomBytes(bytes, function(err, buf) {
    if(err) {
      console.error(err);
    } else {
      callback(buf.toString('base64'));
    }
  });
}

function generateSessionToken(username, callback) {
  generateToken(64, function(token) {
    STATE.sessions[token] = {
      username: username,
      token: token
    };
    callback(token);
  });
}

function verifySessionToken(req, res, next) {
  var session = STATE.sessions[req.query.session_token];
  if(session) {
    req.session = session;
    next();
  } else {
    res.send(401, "ERROR: couldn't verify session_token");
  }
}

// LOGGING
app.use(function(req, res, next){
  console.log('%s %s', req.method, req.url);
  next();
});

// CORS
app.use(function(req, res, next) {
  res.set('Access-Control-Allow-Origin', '*');
  res.set('Access-Control-Allow-Methods', 'GET, PUT, DELETE');
  res.set('Access-Control-Allow-Headers', 'Content-Type, Origin');
  next();
});

app.use(express.bodyParser());

app.use(express.static('./auth/frontend'));

app.post('/authenticate', function(req, res) {
  unixlib.pamauth('remotestorage', req.body.username, req.body.password, function(result) {
    if(result) {
      generateSessionToken(req.body.username, function(key) {
        res.json({ success: true, session_token: key });
      });
    } else {
      res.json({ success: false });
    }
  });
});

app.delete('/authenticate', verifySessionToken, function(req, res) {
  delete STATE.sessions[req.session.token];
  delete req.session;
  res.send(204);
});

app.get('/authorizations', verifySessionToken, function(req, res) {
  var list = auth.list(req.session.username);
  res.json(list);
});

app.post('/authorizations', verifySessionToken, function(req, res) {
  generateToken(64, function(token) {
    auth.add(req.session.username, token, req.body.scopes);
    res.json({ token: token });
  });
});
<commit_msg>return success on logout, even if session token is invalid.<commit_after>
var express = require('express');
var unixlib = require('./deps/unixlib/build/Release/unixlib');
var crypto = require('crypto');

var config = require('./config');

var auth = require('../bindings/build/Release/rs_serve_auth');

var app = express();

module.exports = app;

var STATE = {
  sessions: {}
};

function generateToken(bytes, callback) {
  crypto.randomBytes(bytes, function(err, buf) {
    if(err) {
      console.error(err);
    } else {
      callback(buf.toString('base64'));
    }
  });
}

function generateSessionToken(username, callback) {
  generateToken(64, function(token) {
    STATE.sessions[token] = {
      username: username,
      token: token
    };
    callback(token);
  });
}

function verifySessionToken(req, res, next) {
  var session = STATE.sessions[req.query.session_token];
  if(session) {
    req.session = session;
    next();
  } else {
    res.send(401, "ERROR: couldn't verify session_token");
  }
}

function verifySessionTokenOptional(req, res, next) {
  var session = STATE.sessions[req.query.session_token];
  if(session) {
    req.session = session;
  }
  next();
}

// LOGGING
app.use(function(req, res, next){
  console.log('%s %s', req.method, req.url);
  next();
});

// CORS
app.use(function(req, res, next) {
  res.set('Access-Control-Allow-Origin', '*');
  res.set('Access-Control-Allow-Methods', 'GET, PUT, DELETE');
  res.set('Access-Control-Allow-Headers', 'Content-Type, Origin');
  next();
});

app.use(express.bodyParser());

app.use(express.static('./auth/frontend'));

app.post('/authenticate', function(req, res) {
  unixlib.pamauth('remotestorage', req.body.username, req.body.password, function(result) {
    if(result) {
      generateSessionToken(req.body.username, function(key) {
        res.json({ success: true, session_token: key });
      });
    } else {
      res.json({ success: false });
    }
  });
});

app.delete('/authenticate', verifySessionTokenOptional, function(req, res) {
  if(req.session) {
    delete STATE.sessions[req.session.token];
    delete req.session;
  }
  res.send(204);
});

app.get('/authorizations', verifySessionToken, function(req, res) {
  var list = auth.list(req.session.username);
  res.json(list);
});

app.post('/authorizations', verifySessionToken, function(req, res) {
  generateToken(64, function(token) {
    auth.add(req.session.username, token, req.body.scopes);
    res.json({ token: token });
  });
});
<|endoftext|>


<commit_before>var _ = require('underscore');
module.exports = forms;
forms.usage = "fhc forms [list]\n" +
              "fhc forms create <form-file.json>\n" +
              "fhc forms update <form-file.json>\n" +
              "fhc forms get <form-id>\n" +
              "fhc forms delete <form-id>\n" +
              "fhc forms apps list <app-id>\n" +
              "fhc forms apps update <app-id> <form-id>*";

forms.doUpdate = doUpdate;

var fs = require('fs');
var util = require('util');
var fhc = require("./fhc");
var fhreq = require("./utils/request");

// Get FeedHenry platform version
function forms (args, cb) {
  var url = fhreq.getFeedHenryUrl();
  if (args.length === 0) return doList(cb);
  var action = args[0];

  if (action === 'list') return doList(cb);
  if (action === 'create') {
    if (!args[1]) return cb(forms.usage);
    return doCreateUpdate(args[1], cb);
  }
  if (action === 'update') {
    if (!args[1]) return cb(forms.usage);
    return doCreateUpdate(args[1], cb);
  }
  if (action === 'get') {
    if (!args[1]) return cb(forms.usage);
    return doGetForm(args[1], cb);
  }
  if (action === 'delete') {
    if (!args[1]) return cb(forms.usage);
    return doDeleteForm(args[1], cb);
  }
  if (action === 'apps') {
    if (!args[1]) return cb(forms.usage);
    var act = args[1];
    if (act === 'list') {
      var appId = args[2];
      if (!appId) return cb(forms.usage);
      return doListAppForms(appId, cb);
    }
    if (act === 'update') {
      var appId = args[2];
      if (!appId) return cb(forms.usage);
      var formIds = _.rest(args, 3);
      if (formIds.length == 0) return cb(forms.usage);
      return doAppFormsUpdate(appId, formIds, cb);
    }
  }

  return cb(forms.usage);
};

function doList(cb) {
  fhreq.GET(fhreq.getFeedHenryUrl(), "api/v2/forms/form/list", function (err, remoteData, raw, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb('Unexpected response code: ' + res.statusCode + ' - ' + raw);

    remoteData.status = "ok";
    remoteData.statusCode = 200;
    return cb(err, remoteData);
  });
};

function doCreateUpdate(file, cb) {
  if (!fs.existsSync(file)) return cb("File does not exist: " + file);
  fs.readFile(file, function(err, data) {
    if (err) return cb(err);
    var form = JSON.parse(data);
    doUpdate(form, cb);
  });
};

// do the actual update, this api is used in fh-art directly
function doUpdate(form, cb) {
  fhreq.POST(fhreq.getFeedHenryUrl(), "api/v2/forms/form", form, function (err, remoteData, raw, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb('Unexpected response code: ' + res.statusCode + ' - ' + raw);

    remoteData.status = "ok";
    remoteData.statusCode = 200;
    return cb(err, remoteData);
  });
};

function doGetForm(formId, cb) {
  fhreq.GET(fhreq.getFeedHenryUrl(), "api/v2/forms/form/" + formId, function (err, remoteData, raw, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb('Unexpected response code: ' + res.statusCode + ' - ' + raw);

    remoteData.status = "ok";
    remoteData.statusCode = 200;
    return cb(err, remoteData);
  });
};

function doDeleteForm(formId, cb) {
  fhreq.DELETE(fhreq.getFeedHenryUrl(), "api/v2/forms/form/" + formId, function (err, remoteData, raw, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb('Unexpected response code: ' + res.statusCode + ' - ' + raw);

    remoteData.status = "ok";
    remoteData.statusCode = 200;
    return cb(err, remoteData);
  });
};

function doListAppForms(appId, cb) {
  fhreq.GET(fhreq.getFeedHenryUrl(), "api/v2/forms/apps/" + appId, function (err, remoteData, raw, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb('Unexpected response code: ' + res.statusCode + ' - ' + raw);

    remoteData.status = "ok";
    remoteData.statusCode = 200;
    return cb(err, remoteData);
  });
};

function doAppFormsUpdate(appId, formIds, cb) {
  fhreq.POST(fhreq.getFeedHenryUrl(), "api/v2/forms/apps/" + appId, formIds, function (err, remoteData, raw, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb('Unexpected response code: ' + res.statusCode + ' - ' + raw);

    remoteData.status = "ok";
    remoteData.statusCode = 200;
    return cb(err, remoteData);
  });
};
<commit_msg>#5200 - Listing apps using forms: 'fhc forms formsapp' added<commit_after>var _ = require('underscore');
module.exports = forms;
forms.usage = "fhc forms [list]\n" +
              "fhc forms create <form-file.json>\n" +
              "fhc forms update <form-file.json>\n" +
              "fhc forms get <form-id>\n" +
              "fhc forms delete <form-id>\n" +
              "fhc forms apps list <app-id>\n" +
              "fhc forms apps update <app-id> <form-id>*\n" +
              "fhc forms formapps <form-id>";

forms.doUpdate = doUpdate;

var fs = require('fs');
var util = require('util');
var fhc = require("./fhc");
var fhreq = require("./utils/request");

// Get FeedHenry platform version
function forms (args, cb) {
  var url = fhreq.getFeedHenryUrl();
  if (args.length === 0) return doList(cb);
  var action = args[0];

  if (action === 'list') return doList(cb);
  if (action === 'create') {
    if (!args[1]) return cb(forms.usage);
    return doCreateUpdate(args[1], cb);
  }
  if (action === 'update') {
    if (!args[1]) return cb(forms.usage);
    return doCreateUpdate(args[1], cb);
  }
  if (action === 'get') {
    if (!args[1]) return cb(forms.usage);
    return doGetForm(args[1], cb);
  }
  if (action === 'delete') {
    if (!args[1]) return cb(forms.usage);
    return doDeleteForm(args[1], cb);
  }
  if (action === 'apps') {
    if (!args[1]) return cb(forms.usage);
    var act = args[1];
    if (act === 'list') {
      var appId = args[2];
      if (!appId) return cb(forms.usage);
      return doListAppForms(appId, cb);
    }
    if (act === 'update') {
      var appId = args[2];
      if (!appId) return cb(forms.usage);
      var formIds = _.rest(args, 3);
      if (formIds.length == 0) return cb(forms.usage);
      return doAppFormsUpdate(appId, formIds, cb);
    }
  }
  if (action === 'formapps') {
    if (!args[1]) return cb(forms.usage);
    return doFormApps(args[1], cb);
  }

  return cb(forms.usage);
};

function doList(cb) {
  fhreq.GET(fhreq.getFeedHenryUrl(), "api/v2/forms/form/list", function (err, remoteData, raw, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb('Unexpected response code: ' + res.statusCode + ' - ' + raw);

    remoteData.status = "ok";
    remoteData.statusCode = 200;
    return cb(err, remoteData);
  });
};

function doCreateUpdate(file, cb) {
  if (!fs.existsSync(file)) return cb("File does not exist: " + file);
  fs.readFile(file, function(err, data) {
    if (err) return cb(err);
    var form = JSON.parse(data);
    doUpdate(form, cb);
  });
};

// do the actual update, this api is used in fh-art directly
function doUpdate(form, cb) {
  fhreq.POST(fhreq.getFeedHenryUrl(), "api/v2/forms/form", form, function (err, remoteData, raw, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb('Unexpected response code: ' + res.statusCode + ' - ' + raw);

    remoteData.status = "ok";
    remoteData.statusCode = 200;
    return cb(err, remoteData);
  });
};

function doGetForm(formId, cb) {
  fhreq.GET(fhreq.getFeedHenryUrl(), "api/v2/forms/form/" + formId, function (err, remoteData, raw, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb('Unexpected response code: ' + res.statusCode + ' - ' + raw);

    remoteData.status = "ok";
    remoteData.statusCode = 200;
    return cb(err, remoteData);
  });
};

function doDeleteForm(formId, cb) {
  fhreq.DELETE(fhreq.getFeedHenryUrl(), "api/v2/forms/form/" + formId, function (err, remoteData, raw, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb('Unexpected response code: ' + res.statusCode + ' - ' + raw);

    remoteData.status = "ok";
    remoteData.statusCode = 200;
    return cb(err, remoteData);
  });
};

function doListAppForms(appId, cb) {
  fhreq.GET(fhreq.getFeedHenryUrl(), "api/v2/forms/apps/" + appId, function (err, remoteData, raw, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb('Unexpected response code: ' + res.statusCode + ' - ' + raw);

    remoteData.status = "ok";
    remoteData.statusCode = 200;
    return cb(err, remoteData);
  });
};

function doAppFormsUpdate(appId, formIds, cb) {
  fhreq.POST(fhreq.getFeedHenryUrl(), "api/v2/forms/apps/" + appId, formIds, function (err, remoteData, raw, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb('Unexpected response code: ' + res.statusCode + ' - ' + raw);

    remoteData.status = "ok";
    remoteData.statusCode = 200;
    return cb(err, remoteData);
  });
};

function doFormApps(formId, cb) {
  fhreq.GET(fhreq.getFeedHenryUrl(), "api/v2/forms/formapps/" + formId, function (err, remoteData, raw, res) {
    if (err) return cb(err);
    if (res.statusCode !== 200) return cb('Unexpected response code: ' + res.statusCode + ' - ' + raw);

    remoteData.status = "ok";
    remoteData.statusCode = 200;
    return cb(err, remoteData);
  });
};
<|endoftext|>


<commit_before><commit_msg>building js<commit_after><|endoftext|>


<commit_before>/**
 * @fileOverview Helper Library for Automatic New Tab Features
 * @author       YUKI "Piro" Hiroshi
 * @version      11
 *
 * @license
 *   The MIT License, Copyright (c) 2009-2016 YUKI "Piro" Hiroshi.
 *   http://github.com/piroor/fxaddonlib-auto-new-tab-helper/blob/master/license.txt
 * @url http://github.com/piroor/fxaddonlib-auto-new-tab-helper
 */

var EXPORTED_SYMBOLS = ['autoNewTabHelper'];

const Cc = Components.classes;
const Ci = Components.interfaces;

var autoNewTabHelper = {
	kID : 'checknewtab-id',

	get _IOService() {
		if (!this.__IOService) {
			this.__IOService = Cc['@mozilla.org/network/io-service;1'].getService(Ci.nsIIOService);
		}
		return this.__IOService;
	},
	__IOService : null,

	get _WindowMediator() {
		if (!this.__WindowMediator) {
			this.__WindowMediator = Cc['@mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator);
		}
		return this.__WindowMediator;
	},
	__WindowMediator : null,

	get _EffectiveTLD()
	{
		if (!('__EffectiveTLD' in this)) {
			this.__EffectiveTLD = 'nsIEffectiveTLDService' in Ci ?
				Cc['@mozilla.org/network/effective-tld-service;1'].getService(Ci.nsIEffectiveTLDService) :
				null ;
		}
		return this.__EffectiveTLD;
	},
//	__EffectiveTLD : null,

	get _URIFixup()
	{
		if (!('__URIFixup' in this)) {
			this.__URIFixup = Cc['@mozilla.org/docshell/urifixup;1'].getService(Ci.nsIURIFixup);
		}
		return this.__URIFixup;
	},

	get _Task()
	{
		if (!this.__Task) {
			let TaskNS = {};
			Components.utils.import('resource://gre/modules/Task.jsm', TaskNS);
			this.__Task = TaskNS.Task;
		}
		return this.__Task;
	},

/* utilities */

	get browserWindow()
	{
		return this._WindowMediator.getMostRecentWindow('navigator:browser');
	},

	get browser()
	{
		var w = this.browserWindow;
		return w && w.gBrowser;
	},

// tabbrowser

	getTabBrowserFromChild : function OLITUtils_getTabBrowserFromChild(aTabBrowserChild)
	{
		if (!aTabBrowserChild)
			return null;

		if (aTabBrowserChild.localName == 'tabbrowser') // itself
			return aTabBrowserChild;

		if (aTabBrowserChild.tabbrowser) // tabs, Firefox 4.0 or later
			return aTabBrowserChild.tabbrowser;

		if (aTabBrowserChild.id == 'TabsToolbar') // tabs toolbar, Firefox 4.0 or later
			return aTabBrowserChild.getElementsByTagName('tabs')[0].tabbrowser;

		var b = aTabBrowserChild.ownerDocument.evaluate(
				'ancestor::*[local-name()="tabbrowser"] | '+
				'ancestor::*[local-name()="tabs" and @tabbrowser] |'+
				'ancestor::*[local-name()="toolbar" and @id="TabsToolbar"]/descendant::*[local-name()="tabs"]',
				aTabBrowserChild,
				null,
				Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE,
				null
			).singleNodeValue;
		return (b && b.tabbrowser) || b;
	},

/* get tab(s) */

	_getTabId : function OLITUtils_getTabId(aTab)
	{
		if (!aTab)
			return '';
		var id = aTab.getAttribute(this.kID);
		if (!id) {
			id = 'tab-<'+Date.now()+'-'+parseInt(Math.random() * 65000)+'>';
			aTab.setAttribute(this.kID, id);
		}
		return id;
	},

	_getTabById : function OLITUtils_getTabById(aId, aTabBrowserChildren)
	{
		if (!aId) return null;
		var b = this.getTabBrowserFromChild(aTabBrowserChildren) || this.browser;
		return b.ownerDocument.evaluate(
			'descendant::*[local-name()="tab" and @'+this.kID+' = "'+aId+'"]',
			b.mTabContainer,
			null,
			Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE,
			null
		).singleNodeValue;
	},

	_getNextVisibleTab : function OLITUtils_getNextVisibleTab(aTab)
	{
		if (!aTab) return null;
		var next = aTab;
		do {
			next = next.nextSibling;
		}
		while (next && next.boxObject.width && next.boxObject.height);
		return next;
	},

	/*
	 params:
	   global: the global object of the caller's namespace
	   uri: uri ustring (or a nsIURI instance)
	   external: hash
	     external.newTab: bool
	     external.forceChild: bool
	   internal: hash
	     internal.newTab: bool
	     internal.forceChild: bool
	   useEffectiveTLD: bool
	   checkUserHome: bool
	   sourceURI: uri string
	   newTab: bool
	   invert: bool

	   sourceTab: XUL element
	 */
	checkReadyToOpenNewTab : function OLITUtils_checkReadyToOpenNewTab(aParams)
	{
/*
	挙動の説明

	・現在のサイトと異なるサイトを読み込む場合にタブを開く時：
	  →特に何もしない。新しく開くタブを子タブにする場合は別途
	    readyToOpenChildTabを使う。

	・現在のサイトと同じサイトのページを読み込む場合にタブを開く時：
	  →親のタブは同じサイトか？
	    No ：子タブを開く
	    Yes：兄弟としてタブを開く。ただし、このタブからのタブはすべて
	         現在のタブと次の兄弟タブとの間に開かれ、仮想サブツリーとなる。
	         →現在のタブに「__autoNewTabHelper__next」プロパティが
	           あるか？
	           Yes：__autoNewTabHelper__nextで示されたタブの直前に
	                新しい兄弟タブを挿入する。
	           No ：現在のタブの次の兄弟タブのIDを__autoNewTabHelper__next
	                プロパティに保持し、仮想の子タブを挿入する位置の
	                基準とする。
*/

		aParams = aParams || { uri : '' };
		try{
			aParams.uri = this._URIFixup.createFixupURI(aParams.uri, Ci.nsIURIFixup.FIXUP_FLAG_USE_UTF8);
			aParams.uri = aParams.uri.spec || '';
		}
		catch(e) {
		}

		if (/^(javascript|moz-action|mailto):/.test(aParams.uri))
			return false;

		var external = aParams.external || {};
		var internal = aParams.internal || {};

		var useEffectiveTLD = 'useEffectiveTLD' in aParams ? aParams.useEffectiveTLD : true ;
		var checkUserHome = 'checkUserHome' in aParams ? aParams.checkUserHome : true ;

		var targetHost  = this._getDomainFromURI(aParams.uri, useEffectiveTLD, checkUserHome);
		var sourceURI   = aParams.sourceURI;
		var sourceHost  = this._getDomainFromURI(sourceURI, useEffectiveTLD, checkUserHome);

		// tab detection: unavailable on the content process
		var sourceTab   = aParams.sourceTab;
		var tabbrowser  = currentTab ? this.getTabBrowserFromChild(currentTab.linkedBrowser) : null ;
		var TST         = tabbrowser && 'treeStyleTab' in tabbrowser ? tabbrowser.treeStyleTab : null ;
		var ownerTab    = TST ?
							TST.getParentTab(sourceTab) :
						sourceTab ?
							sourceTab.owner :
							null ;
		var ownerURI    = ownerTab ? ownerTab.linkedBrowser.currentURI : null ;
		var ownerHost   = this._getDomainFromURI(ownerURI, useEffectiveTLD, checkUserHome);

		var shouldOpenNewTab = Boolean(aParams.newTab);
		var nextOwnerTab = null;
		var lastRelated  = null;

		var global = aParams.global;
		var isBlank = global && global.isBlankPageURL ? global.isBlankPageURL(sourceURI) : (sourceURI == 'about:blank');
		if (
			internal.newTab &&
			sourceHost == targetHost &&
			!this._isRedirectorLink(aParams.uri, targetHost, sourceHost) &&
			!isBlank &&
			sourceURI.split('#')[0] != aParams.uri.split('#')[0] &&
			tabbrowser
			) {
			openTab = aParams.newTab && aParams.invert ? !openTab : true ;
			nextOwnerTab = ('forceChild' in internal && !internal.forceChild) ? null :
					(ownerHost == targetHost && !internal.forceChild) ? ownerTab :
					sourceTab ;
			let nextTab = TST ?
							TST.getNextSiblingTab(sourceTab) :
							this._getNextVisibleTab(sourceTab) ;
			let insertNewChildAtFirst = false;
			if (TST) {
				try {
					insertNewChildAtFirst = this.getPref('extensions.treestyletab.insertNewChildAt') == 0;
				}
				catch(e) {
				}
			}
			let insertBefore = ownerHost == targetHost && !internal.forceChild &&
					(insertNewChildAtFirst ?
						nextTab :
						(
							this._getTabById(sourceTab.__autoNewTabHelper__next, tabbrowser) ||
							(nextTab ? (sourceTab.__autoNewTabHelper__next = this._getTabId(nextTab), nextTab) : null )
						)
					);
			lastRelated = insertBefore ? insertBefore.previousSibling : null ;
		}
		else if (
			external.newTab &&
			(
				sourceHost != targetHost ||
				this._isRedirectorLink(aParams.uri, targetHost, sourceHost)
			) &&
			!isBlank
			) {
			shouldOpenNewTab = aParams.newTab && aParams.invert ? !shouldOpenNewTab : true ;
			if (external.forceChild)
				nextOwnerTab = sourceTab;
		}

		return {
			shouldOpenNewTab : shouldOpenNewTab,
			ownerTab         : nextOwnerTab,
			lastRelatedTab   : lastRelated,
			tabbrowser       : tabbrowser
		};
	},

	_getDomainFromURI : function OLITUtils__getDomainFromURI(aURI, aUseEffectiveTLD, aCheckUserHome)
	{
		if (!aURI) return null;

		var str = aURI;
		if (str instanceof Ci.nsIURI) str = aURI.spec;

		var userHomePart = aCheckUserHome ? str.match(/^\w+:\/\/[^\/]+(\/~[^\/]+)\//) : '' ;
		if (userHomePart) userHomePart = userHomePart[1];

		if (aUseEffectiveTLD && this._EffectiveTLD) {
			try {
				var uri = aURI;
				if (!(uri instanceof Ci.nsIURI)) uri = this._makeURIFromSpec(uri);
				var domain = this._EffectiveTLD.getBaseDomain(uri, 0);
				if (domain) return domain + userHomePart;
			}
			catch(e) {
			}
		}

		var domainMatchResult = str.match(/^\w+:(?:\/\/)?([^:\/]+)/);
		return domainMatchResult ?
				domainMatchResult[1] + userHomePart :
				null ;
	},

	_makeURIFromSpec : function OLITUtils_makeURIFromSpec(aURI)
	{
		var newURI;
		aURI = aURI || '';
		if (aURI && String(aURI).indexOf('file:') == 0) {
			var fileHandler = this._IOService.getProtocolHandler('file').QueryInterface(Ci.nsIFileProtocolHandler);
			var tempLocalFile = fileHandler.getFileFromURLSpec(aURI);
			newURI = this._IOService.newFileURI(tempLocalFile);
		}
		else {
			if (!/^\w+\:/.test(aURI)) aURI = 'http://'+aURI;
			newURI = this._IOService.newURI(aURI, null, null);
		}
		return newURI;
	},

	_isRedirectorLink : function OLITUtils_isRedirectorLink(aURIToOpen, aTargetHost, aSourceHost)
	{
		if (aTargetHost != aSourceHost) return false;

		var isGoogleRedirectLink = /https?:\/\/[^\/]*\.google\.[^\/]+\/url\?/.test(aURIToOpen);
		return isGoogleRedirectLink;
	}

};
<commit_msg>Fix mismatched variable name<commit_after>/**
 * @fileOverview Helper Library for Automatic New Tab Features
 * @author       YUKI "Piro" Hiroshi
 * @version      11
 *
 * @license
 *   The MIT License, Copyright (c) 2009-2016 YUKI "Piro" Hiroshi.
 *   http://github.com/piroor/fxaddonlib-auto-new-tab-helper/blob/master/license.txt
 * @url http://github.com/piroor/fxaddonlib-auto-new-tab-helper
 */

var EXPORTED_SYMBOLS = ['autoNewTabHelper'];

const Cc = Components.classes;
const Ci = Components.interfaces;

var autoNewTabHelper = {
	kID : 'checknewtab-id',

	get _IOService() {
		if (!this.__IOService) {
			this.__IOService = Cc['@mozilla.org/network/io-service;1'].getService(Ci.nsIIOService);
		}
		return this.__IOService;
	},
	__IOService : null,

	get _WindowMediator() {
		if (!this.__WindowMediator) {
			this.__WindowMediator = Cc['@mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator);
		}
		return this.__WindowMediator;
	},
	__WindowMediator : null,

	get _EffectiveTLD()
	{
		if (!('__EffectiveTLD' in this)) {
			this.__EffectiveTLD = 'nsIEffectiveTLDService' in Ci ?
				Cc['@mozilla.org/network/effective-tld-service;1'].getService(Ci.nsIEffectiveTLDService) :
				null ;
		}
		return this.__EffectiveTLD;
	},
//	__EffectiveTLD : null,

	get _URIFixup()
	{
		if (!('__URIFixup' in this)) {
			this.__URIFixup = Cc['@mozilla.org/docshell/urifixup;1'].getService(Ci.nsIURIFixup);
		}
		return this.__URIFixup;
	},

	get _Task()
	{
		if (!this.__Task) {
			let TaskNS = {};
			Components.utils.import('resource://gre/modules/Task.jsm', TaskNS);
			this.__Task = TaskNS.Task;
		}
		return this.__Task;
	},

/* utilities */

	get browserWindow()
	{
		return this._WindowMediator.getMostRecentWindow('navigator:browser');
	},

	get browser()
	{
		var w = this.browserWindow;
		return w && w.gBrowser;
	},

// tabbrowser

	getTabBrowserFromChild : function OLITUtils_getTabBrowserFromChild(aTabBrowserChild)
	{
		if (!aTabBrowserChild)
			return null;

		if (aTabBrowserChild.localName == 'tabbrowser') // itself
			return aTabBrowserChild;

		if (aTabBrowserChild.tabbrowser) // tabs, Firefox 4.0 or later
			return aTabBrowserChild.tabbrowser;

		if (aTabBrowserChild.id == 'TabsToolbar') // tabs toolbar, Firefox 4.0 or later
			return aTabBrowserChild.getElementsByTagName('tabs')[0].tabbrowser;

		var b = aTabBrowserChild.ownerDocument.evaluate(
				'ancestor::*[local-name()="tabbrowser"] | '+
				'ancestor::*[local-name()="tabs" and @tabbrowser] |'+
				'ancestor::*[local-name()="toolbar" and @id="TabsToolbar"]/descendant::*[local-name()="tabs"]',
				aTabBrowserChild,
				null,
				Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE,
				null
			).singleNodeValue;
		return (b && b.tabbrowser) || b;
	},

/* get tab(s) */

	_getTabId : function OLITUtils_getTabId(aTab)
	{
		if (!aTab)
			return '';
		var id = aTab.getAttribute(this.kID);
		if (!id) {
			id = 'tab-<'+Date.now()+'-'+parseInt(Math.random() * 65000)+'>';
			aTab.setAttribute(this.kID, id);
		}
		return id;
	},

	_getTabById : function OLITUtils_getTabById(aId, aTabBrowserChildren)
	{
		if (!aId) return null;
		var b = this.getTabBrowserFromChild(aTabBrowserChildren) || this.browser;
		return b.ownerDocument.evaluate(
			'descendant::*[local-name()="tab" and @'+this.kID+' = "'+aId+'"]',
			b.mTabContainer,
			null,
			Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE,
			null
		).singleNodeValue;
	},

	_getNextVisibleTab : function OLITUtils_getNextVisibleTab(aTab)
	{
		if (!aTab) return null;
		var next = aTab;
		do {
			next = next.nextSibling;
		}
		while (next && next.boxObject.width && next.boxObject.height);
		return next;
	},

	/*
	 params:
	   global: the global object of the caller's namespace
	   uri: uri ustring (or a nsIURI instance)
	   external: hash
	     external.newTab: bool
	     external.forceChild: bool
	   internal: hash
	     internal.newTab: bool
	     internal.forceChild: bool
	   useEffectiveTLD: bool
	   checkUserHome: bool
	   sourceURI: uri string
	   newTab: bool
	   invert: bool

	   sourceTab: XUL element
	 */
	checkReadyToOpenNewTab : function OLITUtils_checkReadyToOpenNewTab(aParams)
	{
/*
	挙動の説明

	・現在のサイトと異なるサイトを読み込む場合にタブを開く時：
	  →特に何もしない。新しく開くタブを子タブにする場合は別途
	    readyToOpenChildTabを使う。

	・現在のサイトと同じサイトのページを読み込む場合にタブを開く時：
	  →親のタブは同じサイトか？
	    No ：子タブを開く
	    Yes：兄弟としてタブを開く。ただし、このタブからのタブはすべて
	         現在のタブと次の兄弟タブとの間に開かれ、仮想サブツリーとなる。
	         →現在のタブに「__autoNewTabHelper__next」プロパティが
	           あるか？
	           Yes：__autoNewTabHelper__nextで示されたタブの直前に
	                新しい兄弟タブを挿入する。
	           No ：現在のタブの次の兄弟タブのIDを__autoNewTabHelper__next
	                プロパティに保持し、仮想の子タブを挿入する位置の
	                基準とする。
*/

		aParams = aParams || { uri : '' };
		try{
			aParams.uri = this._URIFixup.createFixupURI(aParams.uri, Ci.nsIURIFixup.FIXUP_FLAG_USE_UTF8);
			aParams.uri = aParams.uri.spec || '';
		}
		catch(e) {
		}

		if (/^(javascript|moz-action|mailto):/.test(aParams.uri))
			return false;

		var external = aParams.external || {};
		var internal = aParams.internal || {};

		var useEffectiveTLD = 'useEffectiveTLD' in aParams ? aParams.useEffectiveTLD : true ;
		var checkUserHome = 'checkUserHome' in aParams ? aParams.checkUserHome : true ;

		var targetHost  = this._getDomainFromURI(aParams.uri, useEffectiveTLD, checkUserHome);
		var sourceURI   = aParams.sourceURI;
		var sourceHost  = this._getDomainFromURI(sourceURI, useEffectiveTLD, checkUserHome);

		// tab detection: unavailable on the content process
		var sourceTab   = aParams.sourceTab;
		var tabbrowser  = sourceTab ? this.getTabBrowserFromChild(sourceTab.linkedBrowser) : null ;
		var TST         = tabbrowser && 'treeStyleTab' in tabbrowser ? tabbrowser.treeStyleTab : null ;
		var ownerTab    = TST ?
							TST.getParentTab(sourceTab) :
						sourceTab ?
							sourceTab.owner :
							null ;
		var ownerURI    = ownerTab ? ownerTab.linkedBrowser.currentURI : null ;
		var ownerHost   = this._getDomainFromURI(ownerURI, useEffectiveTLD, checkUserHome);

		var shouldOpenNewTab = Boolean(aParams.newTab);
		var nextOwnerTab = null;
		var lastRelated  = null;

		var global = aParams.global;
		var isBlank = global && global.isBlankPageURL ? global.isBlankPageURL(sourceURI) : (sourceURI == 'about:blank');
		if (
			internal.newTab &&
			sourceHost == targetHost &&
			!this._isRedirectorLink(aParams.uri, targetHost, sourceHost) &&
			!isBlank &&
			sourceURI.split('#')[0] != aParams.uri.split('#')[0] &&
			tabbrowser
			) {
			openTab = aParams.newTab && aParams.invert ? !openTab : true ;
			nextOwnerTab = ('forceChild' in internal && !internal.forceChild) ? null :
					(ownerHost == targetHost && !internal.forceChild) ? ownerTab :
					sourceTab ;
			let nextTab = TST ?
							TST.getNextSiblingTab(sourceTab) :
							this._getNextVisibleTab(sourceTab) ;
			let insertNewChildAtFirst = false;
			if (TST) {
				try {
					insertNewChildAtFirst = this.getPref('extensions.treestyletab.insertNewChildAt') == 0;
				}
				catch(e) {
				}
			}
			let insertBefore = ownerHost == targetHost && !internal.forceChild &&
					(insertNewChildAtFirst ?
						nextTab :
						(
							this._getTabById(sourceTab.__autoNewTabHelper__next, tabbrowser) ||
							(nextTab ? (sourceTab.__autoNewTabHelper__next = this._getTabId(nextTab), nextTab) : null )
						)
					);
			lastRelated = insertBefore ? insertBefore.previousSibling : null ;
		}
		else if (
			external.newTab &&
			(
				sourceHost != targetHost ||
				this._isRedirectorLink(aParams.uri, targetHost, sourceHost)
			) &&
			!isBlank
			) {
			shouldOpenNewTab = aParams.newTab && aParams.invert ? !shouldOpenNewTab : true ;
			if (external.forceChild)
				nextOwnerTab = sourceTab;
		}

		return {
			shouldOpenNewTab : shouldOpenNewTab,
			ownerTab         : nextOwnerTab,
			lastRelatedTab   : lastRelated,
			tabbrowser       : tabbrowser
		};
	},

	_getDomainFromURI : function OLITUtils__getDomainFromURI(aURI, aUseEffectiveTLD, aCheckUserHome)
	{
		if (!aURI) return null;

		var str = aURI;
		if (str instanceof Ci.nsIURI) str = aURI.spec;

		var userHomePart = aCheckUserHome ? str.match(/^\w+:\/\/[^\/]+(\/~[^\/]+)\//) : '' ;
		if (userHomePart) userHomePart = userHomePart[1];

		if (aUseEffectiveTLD && this._EffectiveTLD) {
			try {
				var uri = aURI;
				if (!(uri instanceof Ci.nsIURI)) uri = this._makeURIFromSpec(uri);
				var domain = this._EffectiveTLD.getBaseDomain(uri, 0);
				if (domain) return domain + userHomePart;
			}
			catch(e) {
			}
		}

		var domainMatchResult = str.match(/^\w+:(?:\/\/)?([^:\/]+)/);
		return domainMatchResult ?
				domainMatchResult[1] + userHomePart :
				null ;
	},

	_makeURIFromSpec : function OLITUtils_makeURIFromSpec(aURI)
	{
		var newURI;
		aURI = aURI || '';
		if (aURI && String(aURI).indexOf('file:') == 0) {
			var fileHandler = this._IOService.getProtocolHandler('file').QueryInterface(Ci.nsIFileProtocolHandler);
			var tempLocalFile = fileHandler.getFileFromURLSpec(aURI);
			newURI = this._IOService.newFileURI(tempLocalFile);
		}
		else {
			if (!/^\w+\:/.test(aURI)) aURI = 'http://'+aURI;
			newURI = this._IOService.newURI(aURI, null, null);
		}
		return newURI;
	},

	_isRedirectorLink : function OLITUtils_isRedirectorLink(aURIToOpen, aTargetHost, aSourceHost)
	{
		if (aTargetHost != aSourceHost) return false;

		var isGoogleRedirectLink = /https?:\/\/[^\/]*\.google\.[^\/]+\/url\?/.test(aURIToOpen);
		return isGoogleRedirectLink;
	}

};
<|endoftext|>


<commit_before>export { ShuffleInfo };
export { ShuffleInfoPool };

import * as Pool from "../../../util/Pool.js";
import { ShuffleInfo as ChannelShuffler_ShuffleInfo } from "../ChannelShuffler_ShuffleInfo.js";

/**
 *
 */
class ShuffleInfo extends ChannelShuffler_ShuffleInfo {

  constructor( concatenatedShape, outputGroupCount ) {
    super( concatenatedShape, outputGroupCount );
  }

  /**
   * After calling this method, this object should be viewed as disposed and should not be operated again.
   *
   * Sub-class should override this method for recycling to its pool (and NEVER call super.disposeResources_and_recycleToPool()).
   */
  disposeResources_and_recycleToPool() {
    this.disposeResources();
    ShuffleInfoPool.Singleton.recycle( this );
  }

  /**
   * Permute the input tensor by reshape-transpose-reshape.
   *
   * @param {tf.tensor} concatenatedTensor
   *   An single tensor (not array) to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor}
   *   A shuffled tensor. Its size is the same as concatenatedTensor but its last dimension is shuffled.
   */
  reshapeTransposeReshape_dispose_finally( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    try {
      let t2 = t1.transpose( this.transposePermutation );

      try {
        return t2.reshape( this.concatenatedShape );

      } finally {
        t2.dispose();
      }

    } finally {
      t1.dispose();
    }
  }

  reshapeTransposeReshape_dispose_direct( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    let t2 = t1.transpose( this.transposePermutation );
    t1.dispose();

    let t3 = t2.reshape( this.concatenatedShape );
    t2.dispose();

    return t3;
  }

  reshapeTransposeReshape_tidy( concatenatedTensor ) {
    return tf.tidy( "ChannelShuffler.ShuffleInfo.reshapeTransposeReshape", () => {
      return concatenatedTensor
        .reshape( this.intermediateShape )
        .transpose( this.transposePermutation )
        .reshape( this.concatenatedShape );
    });
  }

  /**
   * Permute and split the input tensor by reshape-transpose-reshape-split.
   *
   * @param {tf.tensor} concatenatedTensor
   *   An single tensor (not array) to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor[]}
   *   An array of shuffled tensors. Their total channel count is the same as concatenatedTensor, but their
   * last dimensions are shuffled.
   */
  reshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_finally( concatenatedTensor );

    try {
      return t.split( this.outputGroupCount, this.lastAxisId );

    } finally {
      t.dispose();
    }
  }

  reshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_direct( concatenatedTensor );

    try {
      return t.split( this.outputGroupCount, this.lastAxisId );

    } finally {
      t.dispose();
    }
  }

  reshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_finally( concatenatedTensor );

    let tArray = t.split( this.outputGroupCount, this.lastAxisId );
    t.dispose();

    return tArray;
  }

  reshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_direct( concatenatedTensor );

    let tArray = t.split( this.outputGroupCount, this.lastAxisId );
    t.dispose();

    return tArray;
  }

  reshapeTransposeReshapeSplit_dispose_finally( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    try {
      let t2 = t1.transpose( this.transposePermutation );

      try {
        let t3 = t2.reshape( this.concatenatedShape );

        try {
          return t3.split( this.outputGroupCount, this.lastAxisId );

        } finally {
          t3.dispose();
        }

      } finally {
        t2.dispose();
      }

    } finally {
      t1.dispose();
    }
  }

  reshapeTransposeReshapeSplit_dispose_direct( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    let t2 = t1.transpose( this.transposePermutation );
    t1.dispose();

    let t3 = t2.reshape( this.concatenatedShape );
    t2.dispose();

    let tArray = t3.split( this.outputGroupCount, this.lastAxisId );
    t3.dispose();

    return tArray;
  }

  reshapeTransposeReshapeSplit_tidy( concatenatedTensor ) {
    return tf.tidy( "ChannelShuffler.ShuffleInfo.reshapeTransposeReshapeSplit", () => {
      return concatenatedTensor
        .reshape( this.intermediateShape )
        .transpose( this.transposePermutation )
        .reshape( this.concatenatedShape )
        .split( this.outputGroupCount, this.lastAxisId );
    });
  }

  /**
   * Concatenate and permute the input tensor by concat-reshape-transpose-reshape.
   *
   * @param {tf.tensor[]} tensorArray
   *   An array of tensors to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor}
   *   A shuffled tensor. Its total channel count is the same as concatenated tensorArray, but their
   * last dimensions are shuffled.
   */
  concatReshapeTransposeReshape_dispose_direct_call( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let t = this.reshapeTransposeReshape( concatenatedTensor );
    concatenatedTensor.dispose();

    return t;
  }

  /**
   * Concatenate, permute and split the input tensor by concat-reshape-transpose-reshape-split.
   *
   * @param {tf.tensor[]} tensorArray
   *   An array of tensors to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor[]}
   *   An array of shuffled tensors. Their total channel count is the same as concatenated tensorArray, but their
   * last dimensions are shuffled.
   */
  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_finally( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_finally( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_direct( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_direct( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_tidy( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_tidy( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_tidy( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_tidy( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      let t1 = concatenatedTensor.reshape( this.intermediateShape );

      try {
        let t2 = t1.transpose( this.transposePermutation );

        try {
          let t3 = t2.reshape( this.concatenatedShape );

          try {
            return t3.split( this.outputGroupCount, this.lastAxisId );

          } finally {
            t3.dispose();
          }

        } finally {
          t2.dispose();
        }

      } finally {
        t1.dispose();
      }

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let t1 = concatenatedTensor.reshape( this.intermediateShape );
    concatenatedTensor.dispose();

    let t2 = t1.transpose( this.transposePermutation );
    t1.dispose();

    let t3 = t2.reshape( this.concatenatedShape );
    t2.dispose();

    let tArray = t3.split( this.outputGroupCount, this.lastAxisId );
    t3.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_tidy( tensorArray ) {
    return tf.tidy( "ChannelShuffler.ShuffleInfo.concatReshapeTransposeReshapeSplit", () => {
      return tf.concat( tensorArray, this.lastAxisId )
        .reshape( this.intermediateShape )
        .transpose( this.transposePermutation )
        .reshape( this.concatenatedShape )
        .split( this.outputGroupCount, this.lastAxisId );
    });
  }

}

/**
 * Providing ChannelShuffler.PerformanceTest.ShuffleInfo
 *
 */
class ShuffleInfoPool extends Pool.Root {

  constructor() {
    super( "ChannelShuffler.PerformanceTest.ShuffleInfoPool", ShuffleInfo, ShuffleInfo.setAsConstructor );
  }

}

/**
 * Used as default ChannelShuffler.PerformanceTest.ShuffleInfo provider.
 */
ShuffleInfoPool.Singleton = new ShuffleInfoPool();

<commit_msg>Update ChannelShuffler_PerformanceTest_ShuffleInfo.js<commit_after>export { ShuffleInfo };
export { ShuffleInfoPool };

import * as Pool from "../../../util/Pool.js";
import { ShuffleInfo as ChannelShuffler_ShuffleInfo } from "../ChannelShuffler_ShuffleInfo.js";

/**
 *
 */
class ShuffleInfo extends ChannelShuffler_ShuffleInfo {

  constructor( concatenatedShape, outputGroupCount ) {
    super( concatenatedShape, outputGroupCount );
  }

//!!! (2022/06/25 Remarked) Inherits from Recyclable.Base instead.
//   /**
//    * After calling this method, this object should be viewed as disposed and should not be operated again.
//    *
//    * Sub-class should override this method for recycling to its pool (and NEVER call super.disposeResources_and_recycleToPool()).
//    */
//   disposeResources_and_recycleToPool() {
//     this.disposeResources();
//     ShuffleInfoPool.Singleton.recycle( this );
//   }

  /**
   * Permute the input tensor by reshape-transpose-reshape.
   *
   * @param {tf.tensor} concatenatedTensor
   *   An single tensor (not array) to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor}
   *   A shuffled tensor. Its size is the same as concatenatedTensor but its last dimension is shuffled.
   */
  reshapeTransposeReshape_dispose_finally( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    try {
      let t2 = t1.transpose( this.transposePermutation );

      try {
        return t2.reshape( this.concatenatedShape );

      } finally {
        t2.dispose();
      }

    } finally {
      t1.dispose();
    }
  }

  reshapeTransposeReshape_dispose_direct( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    let t2 = t1.transpose( this.transposePermutation );
    t1.dispose();

    let t3 = t2.reshape( this.concatenatedShape );
    t2.dispose();

    return t3;
  }

  reshapeTransposeReshape_tidy( concatenatedTensor ) {
    return tf.tidy( "ChannelShuffler.ShuffleInfo.reshapeTransposeReshape", () => {
      return concatenatedTensor
        .reshape( this.intermediateShape )
        .transpose( this.transposePermutation )
        .reshape( this.concatenatedShape );
    });
  }

  /**
   * Permute and split the input tensor by reshape-transpose-reshape-split.
   *
   * @param {tf.tensor} concatenatedTensor
   *   An single tensor (not array) to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor[]}
   *   An array of shuffled tensors. Their total channel count is the same as concatenatedTensor, but their
   * last dimensions are shuffled.
   */
  reshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_finally( concatenatedTensor );

    try {
      return t.split( this.outputGroupCount, this.lastAxisId );

    } finally {
      t.dispose();
    }
  }

  reshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_direct( concatenatedTensor );

    try {
      return t.split( this.outputGroupCount, this.lastAxisId );

    } finally {
      t.dispose();
    }
  }

  reshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_finally( concatenatedTensor );

    let tArray = t.split( this.outputGroupCount, this.lastAxisId );
    t.dispose();

    return tArray;
  }

  reshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_direct( concatenatedTensor );

    let tArray = t.split( this.outputGroupCount, this.lastAxisId );
    t.dispose();

    return tArray;
  }

  reshapeTransposeReshapeSplit_dispose_finally( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    try {
      let t2 = t1.transpose( this.transposePermutation );

      try {
        let t3 = t2.reshape( this.concatenatedShape );

        try {
          return t3.split( this.outputGroupCount, this.lastAxisId );

        } finally {
          t3.dispose();
        }

      } finally {
        t2.dispose();
      }

    } finally {
      t1.dispose();
    }
  }

  reshapeTransposeReshapeSplit_dispose_direct( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    let t2 = t1.transpose( this.transposePermutation );
    t1.dispose();

    let t3 = t2.reshape( this.concatenatedShape );
    t2.dispose();

    let tArray = t3.split( this.outputGroupCount, this.lastAxisId );
    t3.dispose();

    return tArray;
  }

  reshapeTransposeReshapeSplit_tidy( concatenatedTensor ) {
    return tf.tidy( "ChannelShuffler.ShuffleInfo.reshapeTransposeReshapeSplit", () => {
      return concatenatedTensor
        .reshape( this.intermediateShape )
        .transpose( this.transposePermutation )
        .reshape( this.concatenatedShape )
        .split( this.outputGroupCount, this.lastAxisId );
    });
  }

  /**
   * Concatenate and permute the input tensor by concat-reshape-transpose-reshape.
   *
   * @param {tf.tensor[]} tensorArray
   *   An array of tensors to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor}
   *   A shuffled tensor. Its total channel count is the same as concatenated tensorArray, but their
   * last dimensions are shuffled.
   */
  concatReshapeTransposeReshape_dispose_direct_call( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let t = this.reshapeTransposeReshape( concatenatedTensor );
    concatenatedTensor.dispose();

    return t;
  }

  /**
   * Concatenate, permute and split the input tensor by concat-reshape-transpose-reshape-split.
   *
   * @param {tf.tensor[]} tensorArray
   *   An array of tensors to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor[]}
   *   An array of shuffled tensors. Their total channel count is the same as concatenated tensorArray, but their
   * last dimensions are shuffled.
   */
  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_finally( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_finally( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_direct( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_direct( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_tidy( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_tidy( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_tidy( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_tidy( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      let t1 = concatenatedTensor.reshape( this.intermediateShape );

      try {
        let t2 = t1.transpose( this.transposePermutation );

        try {
          let t3 = t2.reshape( this.concatenatedShape );

          try {
            return t3.split( this.outputGroupCount, this.lastAxisId );

          } finally {
            t3.dispose();
          }

        } finally {
          t2.dispose();
        }

      } finally {
        t1.dispose();
      }

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let t1 = concatenatedTensor.reshape( this.intermediateShape );
    concatenatedTensor.dispose();

    let t2 = t1.transpose( this.transposePermutation );
    t1.dispose();

    let t3 = t2.reshape( this.concatenatedShape );
    t2.dispose();

    let tArray = t3.split( this.outputGroupCount, this.lastAxisId );
    t3.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_tidy( tensorArray ) {
    return tf.tidy( "ChannelShuffler.ShuffleInfo.concatReshapeTransposeReshapeSplit", () => {
      return tf.concat( tensorArray, this.lastAxisId )
        .reshape( this.intermediateShape )
        .transpose( this.transposePermutation )
        .reshape( this.concatenatedShape )
        .split( this.outputGroupCount, this.lastAxisId );
    });
  }

}

/**
 * Providing ChannelShuffler.PerformanceTest.ShuffleInfo
 *
 */
class ShuffleInfoPool extends Pool.Root {

  constructor() {
    super( "ChannelShuffler.PerformanceTest.ShuffleInfoPool", ShuffleInfo, ShuffleInfo.setAsConstructor );
  }

}

/**
 * Used as default ChannelShuffler.PerformanceTest.ShuffleInfo provider for conforming to Recyclable interface.
 */
ShuffleInfo.Pool = new ShuffleInfoPool();

<|endoftext|>