phantombot-plugins/twitch/chatguessr.js

241 lines
25 KiB
JavaScript
Raw Normal View History

2022-02-09 02:52:17 +01:00
(function() {
/* axios v0.25.0 | (c) 2022 by Matt Zabriskie */
2022-02-09 02:51:18 +01:00
/* axios v0.24.0 | (c) 2022 by Matt Zabriskie */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.axios=t():e.axios=t()}(this,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=11)}([function(e,t,n){"use strict";var r=n(3),o=Object.prototype.toString;function i(e){return"[object Array]"===o.call(e)}function s(e){return void 0===e}function a(e){return null!==e&&"object"==typeof e}function u(e){if("[object Object]"!==o.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function c(e){return"[object Function]"===o.call(e)}function f(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),i(e))for(var n=0,r=e.length;n<r;n++)t.call(null,e[n],n,e);else for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.call(null,e[o],o,e)}e.exports={isArray:i,isArrayBuffer:function(e){return"[object ArrayBuffer]"===o.call(e)},isBuffer:function(e){return null!==e&&!s(e)&&null!==e.constructor&&!s(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:a,isPlainObject:u,isUndefined:s,isDate:function(e){return"[object Date]"===o.call(e)},isFile:function(e){return"[object File]"===o.call(e)},isBlob:function(e){return"[object Blob]"===o.call(e)},isFunction:c,isStream:function(e){return a(e)&&c(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:f,merge:function e(){var t={};function n(n,r){u(t[r])&&u(n)?t[r]=e(t[r],n):u(n)?t[r]=e({},n):i(n)?t[r]=n.slice():t[r]=n}for(var r=0,o=arguments.length;r<o;r++)f(arguments[r],n);return t},extend:function(e,t,n){return f(t,(function(t,o){e[o]=n&&"function"==typeof t?r(t,n):t})),e},trim:function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e}}},function(e,t,n){"use strict";var r=n(0),o=n(17),i=n(5),s={"Content-Type":"application/x-www-form-urlencoded"};function a(e,t){!r.isUndefined(e)&&r.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var u,c={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(u=n(6)),u),transformRequest:[function(e,t){return o(t,"Accept"),o(t,"Content-Type"),r.isFormData(e)||r.isArrayBuffer(e)||r.isBuffer(e)||r.isStream(e)||r.isFile(e)||r.isBlob(e)?e:r.isArrayBufferView(e)?e.buffer:r.isURLSearchParams(e)?(a(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):r.isObject(e)||t&&"application/json"===t["Content-Type
//# sourceMappingURL=axios.min.map
const BDC_KEY = "067c718d2bbd4a2ba8d0645e1633cac2";
class GameHelper {
/**
* Fetch a game seed
* @param {string} id
* @return {Promise} Seed Promise
*/
static async fetchSeed(id) {
return axios
.get(`https://www.geoguessr.com/api/v3/games/${id}`)
.then((res) => res.data)
.catch((error) => console.log(error));
};
static async getCountryBDC(location) {
return axios
.get(`https://api.bigdatacloud.net/data/reverse-geocode?latitude=${location.lat}&longitude=${location.lng}&key=${BDC_KEY}`)
.then((res) => countryCodes[res.data.countryCode])
.catch((error) => error);
};
/**
* Returns an array of 9 coodinates as objects.
* Each coordinate is 100 meters aways from the given
* coordinate y angles from 0 to 315
* The first coordinate is the original passed
* @param {Object} location {lat, lng}
* @return {Array} Coordinates [{lat, lng}, {lat, lng}] x 8
*/
static getSurroundings (location) {
const meters = 100;
const R_EARTH = 6378.137;
const M = 1 / (((2 * Math.PI) / 360) * R_EARTH) / 1000;
function moveFrom(coords, angle, distance) {
let radianAngle = (angle * Math.PI) / 180;
let x = 0 + distance * Math.cos(radianAngle);
let y = 0 + distance * Math.sin(radianAngle);
let newLat = coords.lat + y * M;
let newLng = coords.lng + (x * M) / Math.cos(coords.lat * (Math.PI / 180));
return { lat: newLat, lng: newLng };
}
let coordinates = [location];
for (let angle = 0; angle < 360; angle += 45) {
coordinates.push(moveFrom({ lat: location.lat, lng: location.lng }, angle, meters));
}
return coordinates;
};
/**
* Check if the param is coordinates
* @param {string} coordinates
* @return {boolean}
*/
static isCoordinates (coordinates) {
const regex = /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/g;
return regex.test(coordinates);
};
/**
* Returns map scale
* @param {Object} bounds map bounds
* @return {number} map scale
*/
static calculateScale(bounds){
return GameHelper.haversineDistance({ lat: bounds.min.lat, lng: bounds.min.lng }, { lat: bounds.max.lat, lng: bounds.max.lng }) / 7.458421;
}
/**
* Returns distance in km between two coordinates
* @param {Object} mk1 {lat, lng}
* @param {Object} mk2 {lat, lng}
* @return {number} km
*/
static haversineDistance(mk1, mk2){
const R = 6371.071;
const rlat1 = mk1.lat * (Math.PI / 180);
const rlat2 = mk2.lat * (Math.PI / 180);
const difflat = rlat2 - rlat1;
const difflon = (mk2.lng - mk1.lng) * (Math.PI / 180);
const km =
2 *
R *
Math.asin(Math.sqrt(Math.sin(difflat / 2) * Math.sin(difflat / 2) + Math.cos(rlat1) * Math.cos(rlat2) * Math.sin(difflon / 2) * Math.sin(difflon / 2)));
return km;
};
/**
* Returns score based on distance and scale
* @param {number} distance
* @param {number} scale
* @return {number} score
*/
static calculateScore(distance, scale){
return Math.round(5000 * Math.pow(0.99866017, (distance * 1000) / scale));
}
/** Replace special chars
* @param {String} val
*/
static normalize(val){
return val.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}
/** Matches words above 3 letters
* @param {String} input
* @param {String} key
*/
static isMatch(input, key){
return input.length >= 3 && key.includes(input) && input.length <= key.length;
}
/** Find country by code or name
* @param {String} input
* @return {Object} countryCodesNames
*/
static findCountry(input){
const normalized = GameHelper.normalize(input);
return countryCodesNames.find((country) => country.code === normalized || GameHelper.isMatch(normalized, country.names.toLowerCase()));
};
}
2022-02-09 02:28:05 +01:00
2022-02-09 02:52:17 +01:00
2022-02-09 02:51:18 +01:00
var isOpen = $.getSetIniDbBoolean('chatguessr', 'isOpen', false),
2022-02-09 02:28:05 +01:00
seed = {},
guesses = {
'1':[
{user:'Alpha',location:'0,0',distance:5,score:2,streak:0},
{user:'Beta',location:'5,0',distance:100,score:3,streak:0},
{user:'Charlie',location:'6,6',distance:1000,score:0,streak:0},
{user:'Delta',location:'42,6',distance:1,score:5,streak:1}
],
'2':[
],
};
function dbSetSeed(id) {
$.inidb.SetBoolean("chatguessr", "isOpen", "", open);
isOpen = open;
}
2022-02-07 17:19:38 +01:00
2022-02-09 02:28:05 +01:00
function dbSetOpen(open) {
2022-02-07 17:19:38 +01:00
$.inidb.SetBoolean("chatguessr", "isOpen", "", open);
isOpen = open;
sendData('status',open);
}
2022-02-09 02:28:05 +01:00
function dbClearGuesses() {
2022-02-07 17:19:38 +01:00
guesses = {};
$.inidb.SetString("chatguessr", "guesses", JSON.stringify(guesses));
sendData('guesses',guesses);
}
2022-02-09 02:28:05 +01:00
function dbAddGuess(user,position) {
2022-02-07 17:19:38 +01:00
if(guesses[user] && guesses[user].length > 0){
2022-02-08 15:59:11 +01:00
}else if(isCoordinates(position)){
2022-02-07 17:19:38 +01:00
guesses[user] = position;
$.inidb.SetString("chatguessr", "guesses", JSON.stringify(guesses));
2022-02-09 02:28:05 +01:00
sendData('guesses',JSON.stringify(guesses));
2022-02-07 17:19:38 +01:00
}
}
function sendData(tpe, data) {
$.panelsocketserver.sendJSONToAll(JSON.stringify({
'eventFamily': 'chatguessr',
'eventType': tpe,
'data': data
}));
}
2022-02-08 15:59:11 +01:00
function isCoordinates(coordinates) {
const regex = /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/g;
return regex.test(coordinates);
};
2022-02-07 17:19:38 +01:00
$.bind('command', function(event) {
const sender = "" + event.getSender().toLowerCase(),
command = event.getCommand(),
args = event.getArgs(),
action = args[0];
if (command.equalsIgnoreCase('g')) {
if(isOpen) DBAddG(sender,args);
}else if (command.equalsIgnoreCase('cg')) {
2022-02-09 02:28:05 +01:00
//send url
//$.say($.whisperPrefix(sender) + $.lang.get('chatguessr.help', ' Use "!cg [open | close | ...]" to open/close the feature.'));
}else if(command.equalsIgnoreCase('cga')){
if(action.equalsIgnoreCase('open')){
isOpen = true;
$.getSetIniDbBoolean('cgstatus', 'isOpen', true);
}else if(action.equalsIgnoreCase('close')){
isOpen = false;
$.getSetIniDbBoolean('cgstatus', 'isOpen', false)
}else if(action.equalsIgnoreCase('start')){
seed = GameHelper.fetchSeed(args[1]);
}else if(action.equalsIgnoreCase('end')){
isOpen = false;
$.getSetIniDbBoolean('cgstatus', 'isOpen', false)
}else if(action.equalsIgnoreCase('refresh')){
let newseed = GameHelper.fetchSeed(args[1]);
}else if(action.equalsIgnoreCase('gg')){
sendData('guesses',JSON.stringify(guesses));
2022-02-07 17:19:38 +01:00
}
}
});
$.bind('initReady', function() {
2022-02-09 02:28:05 +01:00
$.registerChatCommand('./custom/custom/chatguessr.js', 'cg',7);
2022-02-07 17:19:38 +01:00
$.registerChatCommand('./custom/custom/chatguessr.js', 'g',7);
2022-02-09 02:28:05 +01:00
$.registerChatCommand('./custom/custom/chatguessr.js', 'cga');
$.registerChatSubcommand('cga', 'open', 2);
$.registerChatSubcommand('cga', 'close', 2);
$.registerChatSubcommand('cga', 'start', 2);
$.registerChatSubcommand('cga', 'end', 2);
$.registerChatSubcommand('cga', 'refresh', 2);
2022-02-07 17:19:38 +01:00
});
2022-02-09 02:28:05 +01:00
})();