<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013 <NAME>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

var http = require("http");
var https = require("https");
var domain = require("domain");
var Logger = require("./logger.js");
var Media = require("./media.js").Media;
var CustomEmbedFilter = require("./customembed").filter;
var Server = require("./server");

var urlRetrieve = function (transport, options, callback) {
    // Catch any errors that crop up along the way of the request
    // in order to prevent them from reaching the global handler.
    // This should cut down on needing to restart the server
    var d = domain.create();
    d.on("error", function (err) {
        Logger.errlog.log(err.trace());
        Logger.errlog.log("urlRetrieve failed: " + err);
        Logger.errlog.log("Request was: " + options.host + options.path);
        callback(503, err);
    });
    d.run(function () {
        var req = transport.request(options, function (res) {
            var buffer = "";
            res.setEncoding("utf-8");
            res.on("data", function (chunk) {
                buffer += chunk;
            });
            res.on("end", function () {
                callback(res.statusCode, buffer);
            });
        });

        req.end();
    });
};

var Getters = {
    /* youtube.com */
    yt: function (id, callback) {
        var sv = Server.getServer();
        if (sv.cfg["enable-ytv3"] && sv.cfg["ytv3apikey"]) {
            Getters["ytv3"](id, callback);
            return;
        }

        var m = id.match(/([\w-]+)/);
        if (m) {
            id = m[1];
        } else {
            callback("Invalid ID", null);
            return;
        }

        var options = {
            host: "gdata.youtube.com",
            port: 443,
            path: "/feeds/api/videos/" + id + "?v=2&alt=json",
            method: "GET",
            dataType: "jsonp",
            timeout: 1000
        };

        if(sv.cfg["ytv2devkey"]) {
            options.headers = {
                "X-Gdata-Key": "key=" + sv.cfg["ytv2devkey"]
            };
        }

        urlRetrieve(https, options, function (status, data) {
            if(status === 404) {
                callback("Video not found", null);
                return;
            } else if(status === 403) {
                callback("Private video", null);
                return;
            } else if(status === 400) {
                callback("Invalid video", null);
                return;
            } else if(status === 503) {
                callback("API failure", null);
                return;
            } else if(status !== 200) {
                callback("HTTP " + status, null);
                return;
            }
            
            var buffer = data;
            try {
                data = JSON.parse(data);
                if (data.entry.yt$accessControl) {
                    var ac = data.entry.yt$accessControl;
                    for (var i = 0; i < ac.length; i++) {
                        if (ac[i].action === "embed") {
                            if (ac[i].permission === "denied") {
                                callback("Embedding disabled", null);
                                return;
                            }
                            break;
                        }
                    }
                }

                var seconds = data.entry.media$group.yt$duration.seconds;
                var title = data.entry.title.$t;
                var media = new Media(id, title, seconds, "yt");
                if (data.entry.media$group.media$restriction) {
                    var rest = data.entry.media$group.media$restriction;
                    if (rest.length > 0) {
                        if (rest[0].relationship === "deny") {
                            media.restricted = rest[0].$t;
                        }
                    }
                }
                callback(false, media);
            } catch(e) {
                // Gdata version 2 has the rather silly habit of
                // returning error codes in XML when I explicitly asked
                // for JSON
                var m = buffer.match(/<internalReason>([^<]+)<\/internalReason>/);
                if(m === null)
                    m = buffer.match(/<code>([^<]+)<\/code>/);

                var err = e;
                if(m) {
                    if(m[1] === "too_many_recent_calls") {
                        err = "YouTube is throttling the server right "+
                               "now for making too many requests.  "+
                               "Please try again in a moment.";
                    } else {
                        err = m[1];
                    }
                }

                callback(err, null);
            }
        });
    },

    /* youtube.com API v3 (requires API key) */
    ytv3: function (id, callback) {
        var sv = Server.getServer();
        var m = id.match(/([\w-]+)/);
        if (m) {
            id = m[1];
        } else {
            callback("Invalid ID", null);
            return;
        }
        var params = [
            "part=" + encodeURIComponent("id,snippet,contentDetails"),
            "id=" + id,
            "key=" + sv.cfg["ytapikey"]
        ].join("&");
        var options = {<commit_msg>Fix a typo<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013 <NAME>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

var http = require("http");
var https = require("https");
var domain = require("domain");
var Logger = require("./logger.js");
var Media = require("./media.js").Media;
var CustomEmbedFilter = require("./customembed").filter;
var Server = require("./server");

var urlRetrieve = function (transport, options, callback) {
    // Catch any errors that crop up along the way of the request
    // in order to prevent them from reaching the global handler.
    // This should cut down on needing to restart the server
    var d = domain.create();
    d.on("error", function (err) {
        Logger.errlog.log(err.trace());
        Logger.errlog.log("urlRetrieve failed: " + err);
        Logger.errlog.log("Request was: " + options.host + options.path);
        callback(503, err);
    });
    d.run(function () {
        var req = transport.request(options, function (res) {
            var buffer = "";
            res.setEncoding("utf-8");
            res.on("data", function (chunk) {
                buffer += chunk;
            });
            res.on("end", function () {
                callback(res.statusCode, buffer);
            });
        });

        req.end();
    });
};

var Getters = {
    /* youtube.com */
    yt: function (id, callback) {
        var sv = Server.getServer();
        if (sv.cfg["enable-ytv3"] && sv.cfg["ytv3apikey"]) {
            Getters["ytv3"](id, callback);
            return;
        }

        var m = id.match(/([\w-]+)/);
        if (m) {
            id = m[1];
        } else {
            callback("Invalid ID", null);
            return;
        }

        var options = {
            host: "gdata.youtube.com",
            port: 443,
            path: "/feeds/api/videos/" + id + "?v=2&alt=json",
            method: "GET",
            dataType: "jsonp",
            timeout: 1000
        };

        if(sv.cfg["ytv2devkey"]) {
            options.headers = {
                "X-Gdata-Key": "key=" + sv.cfg["ytv2devkey"]
            };
        }

        urlRetrieve(https, options, function (status, data) {
            if(status === 404) {
                callback("Video not found", null);
                return;
            } else if(status === 403) {
                callback("Private video", null);
                return;
            } else if(status === 400) {
                callback("Invalid video", null);
                return;
            } else if(status === 503) {
                callback("API failure", null);
                return;
            } else if(status !== 200) {
                callback("HTTP " + status, null);
                return;
            }
            
            var buffer = data;
            try {
                data = JSON.parse(data);
                if (data.entry.yt$accessControl) {
                    var ac = data.entry.yt$accessControl;
                    for (var i = 0; i < ac.length; i++) {
                        if (ac[i].action === "embed") {
                            if (ac[i].permission === "denied") {
                                callback("Embedding disabled", null);
                                return;
                            }
                            break;
                        }
                    }
                }

                var seconds = data.entry.media$group.yt$duration.seconds;
                var title = data.entry.title.$t;
                var media = new Media(id, title, seconds, "yt");
                if (data.entry.media$group.media$restriction) {
                    var rest = data.entry.media$group.media$restriction;
                    if (rest.length > 0) {
                        if (rest[0].relationship === "deny") {
                            media.restricted = rest[0].$t;
                        }
                    }
                }
                callback(false, media);
            } catch(e) {
                // Gdata version 2 has the rather silly habit of
                // returning error codes in XML when I explicitly asked
                // for JSON
                var m = buffer.match(/<internalReason>([^<]+)<\/internalReason>/);
                if(m === null)
                    m = buffer.match(/<code>([^<]+)<\/code>/);

                var err = e;
                if(m) {
                    if(m[1] === "too_many_recent_calls") {
                        err = "YouTube is throttling the server right "+
                               "now for making too many requests.  "+
                               "Please try again in a moment.";
                    } else {
                        err = m[1];
                    }
                }

                callback(err, null);
            }
        });
    },

    /* youtube.com API v3 (requires API key) */
    ytv3: function (id, callback) {
        var sv = Server.getServer();
        var m = id.match(/([\w-]+)/);
        if (m) {
            id = m[1];
        } else {
            callback("Invalid ID", null);
            return;
        }
        var params = [
            "part=" + encodeURIComponent("id,snippet,contentDetails"),
            "id=" + id,
            "key=" + sv.cfg["ytv3apikey"]
        ].join("&");
        var options = {
{'fraction_non_alphanumeric': 0.12031979735613077, 'fraction_numerical': 0.007519987334758173, 'mean_word_length': 1.449873957727361, 'pattern_counts': {'":': 2, '<': 19, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3548971', 'n_tokens_mistral': 3400, 'n_tokens_neox': 3161, 'n_words': 1012}