So basically what is happening, is this code is running when a command is run. If the user's string (UserID) fits into the array, it responds as true and sets the access level to 6. If that is false, it checks for roles and sets the access level if they have certain roles by the role names. However, the role names part is not working. For example, a user with the Moderator role (normally access level 3 / perms.three), is showing up as access level 0 and I cannot figure out why.
The way this is supposed to work is that it checks the ID of a user. If that ID is in a pre-defined array located in a .json file, it overrides all other access levels by giving an access level of 6. If the array doesn't exist it moves onto the roles function and searches to see if the role exists in the persons list of roles.
This is what I use to check the roles/userID.
if (command.accessLevel > perms.getAccess(message.member.roles) || command.accessLevel > perms.getAccess(message.member.id)){
return message.channel.send("``Error: Access Denied.``");
}
This is the permissions.js file:
const bot = require('./bot').skynet;
const config = require('./config.json');
const perms = require('./permissions.json').access;
function arrayHas(arr, val){
var result = false;
for (var item in arr){
if (arr[item] == val){
result = true;
break;
}
}
return result;
}
function getAccess(user){
var access = 0;
if (typeof(user) == 'string'){
if (arrayHas(perms.six, user)){
return 6;
}
}
var roles = user;
roles.forEach(function(role){
if (arrayHas(perms.five, role.name)){
access = 5;
return;
}
else if (arrayHas(perms.four, role.name)){
access = 4;
return;
}
else if (arrayHas(perms.three, role.name)){
access = 3;
return;
}
else if (arrayHas(perms.two, role.name)){
access = 2;
return;
}
else if (arrayHas(perms.one, role.name)){
access = 1;
return;
}
});
return access;
}
bot.on('message', message => {
console.log(getAccess(message.member.id));
console.log(getAccess(message.member.roles));
})
module.exports = {
arrayHas: arrayHas,
getAccess: getAccess,
};
In the first if statement, you should return a value after the inside if statement. Otherwise, you'll continue to the following code roles.forEach for a string which will fail (roles.forEach is not a function)
Or place the non-string logic inside an else statement:
function getAccess(user){
var access = 0;
if (typeof(user) == 'string'){
if (arrayHas(perms.six, user)){
return 6;
}
} else {
var roles = user;
roles.forEach(function(role){
if (arrayHas(perms.five, role.name)){
access = 5;
return;
}
else if (arrayHas(perms.four, role.name)){
access = 4;
return;
}
else if (arrayHas(perms.three, role.name)){
access = 3;
return;
}
else if (arrayHas(perms.two, role.name)){
access = 2;
return;
}
else if (arrayHas(perms.one, role.name)){
access = 1;
return;
}
});
}
return access;
}
In your function getAccess(), you're setting the access variable but never actually returning the value. Try this revised version.
const Discord = require('discord.js');
const { skynet: bot } = require('./bot');
const config = require('./config.json');
const { access: perms } = require('./permissions.json');
/**
* Return the access level of a member.
* #param {Discord.GuildMember} member
*/
function getAccess(member) {
if (!(member instanceof Discord.GuildMember)) return new TypeError('Expected a GuildMember.');
if (arrayHas(perms.six, member.user.id)) return 6;
const roles = member.roles;
for (const role of roles) {
if (arrayHas(perms.five, role.name)) return 5;
if (arrayHas(perms.four, role.name)) return 4;
if (arrayHas(perms.three, role.name)) return 3;
if (arrayHas(perms.two, role.name)) return 2;
if (arrayHas(perms.one, role.name)) return 1;
}
return 0;
}
Related
After calling all the data from my database, I would like to try and calculate the individual values of my array. I have made 2 users state as "banned"
//get all banned status for all users
res.data.data.forEach((dataItem, index) => {
console.log(`Banned ${index}`, dataItem.banned);
I would like to try and get the sum of "banned" and "not banned" which in this case is "banned 2" and "NotBanned 2"
tried this but dint work
for (const dataItem of res.data.data) {
let NotBanned = 0;
if(dataItem.banned === false){
NotBanned++;
console.log("Not Banned", NotBanned);
}
}
for (const dataItem of res.data.data) {
var BannedUsers = 0;
if(dataItem.banned === true){
BannedUsers++;
console.log("Not Banned",BannedUsers);
}
}
let
bannedUsers = 0,
unBannedUsers = 0;
const response = res.data.data
for(let users = 0; users < response.length; users ++ ) {
if(!response.banned) {
unBannedUsers += users;
}
else {
bannedUsers += users;
}
}
console.log(`Banned Users : ${bannedUsers} , UnBanned Users : ${unBannedUsers}` )
When I add a transaction in the function below, the child of the "guncelLig" is automatically deleted. When I remove the second transaction there is no problem, it works very well.
this code work correct :
for (let i = 0; i < users.length; i++) {
const userID = users[i].id;
database.ref().child("users").child("profilData").child(userID).child("guncelLig").transaction(function (value) {
if (value > 1) {
database.ref().child("users").child("profilData").child(userID).update({
"lastUpdate": toSwiftDate(),
});
return value - 1;
}
return value;
});
}
but when I add the new part to the code below, "guncelLig" is completely deleted from the firebase realtime databse:
for (let i = 0; i < users.length; i++) {
const userID = users[i].id;
database.ref().child("users").child("profilData").child(userID).child("guncelLig").transaction(function (value) {
if (value > 1) {
database.ref().child("users").child("profilData").child(userID).update({
"lastUpdate": toSwiftDate(),
});
/// NEW CODE ERROR SOURCHE
database.ref().child("users").child("profilData").child(userID).child("EnYukselLig").transaction(function (EnYukselLig) {
if (EnYukselLig > value - 1) {
return value - 1;
}
return EnYukselLig;
});
return value - 1; // arttır
}
return value; /// ALWAYS RETURN NULL
});
}
Where am I doing wrong? please help me
You should write your code as async/await. With await you can wait for the nested transaction to finish.
for (let i = 0; i < users.length; i++) {
const userID = users[i].id;
database
.ref()
.child("users")
.child("profilData")
.child(userID)
.child("guncelLig")
.transaction(async (value) => {
if (value > 1) {
await database
.ref()
.child("users")
.child("profilData")
.child(userID)
.update({
lastUpdate: toSwiftDate(),
});
/// NEW CODE ERROR SOURCHE
await database
.ref()
.child("users")
.child("profilData")
.child(userID)
.child("EnYukselLig")
.transaction(function (EnYukselLig) {
if (EnYukselLig > value - 1) {
return value - 1;
}
return EnYukselLig;
});
return value - 1; // arttır
}
// No handler if the value is NULL
return value; /// ALWAYS RETURN NULL
});
}
You also don't handle the case if value is already null.
It is not recommmended to nest transactions like that. Transacions by nature can run multiple times and there is no guaranty that they finish as expected depending on the amount of updates that happen on the same location.
I have found on the internet this interesting article about plugins in mongoose. From that site I got this code:
function HidePlugin(schema) {
var toHide = [];
schema.eachPath(function(pathname, schemaType) {
if (schemaType.options && schemaType.options.hide) {
toHide.push(pathname);
}
});
schema.options.toObject = schema.options.toObject || {};
schema.options.toObject.transform = function(doc, ret) {
// Loop over all fields to hide
toHide.forEach(function(pathname) {
// Break the path up by dots to find the actual
// object to delete
var sp = pathname.split('.');
var obj = ret;
for (var i = 0; i < sp.length - 1; ++i) {
if (!obj) {
return;
}
obj = obj[sp[i]];
}
// Delete the actual field
delete obj[sp[sp.length - 1]];
});
return ret;
};
}
The problem is that I use typescript together with node.js. The typescript compiler gives me errors because there are no explicit types. In fact, I do not know exactly what type I have to attribute to the variables in the code
I'm trying to create a simple chrome extension using the following google RSS reader sample,
http://code.google.com/chrome/extensions/samples.html#597015d3bcce3da693b02314afd607bec4f55291
I can add links in the pop-up window that open tabs, but not from the feeds themselves.
Looping through the items in the feed, grabbing title tags and link tags, I want the title to link the the appropriate sites
var entries = doc.getElementsByTagName('item');
var count = Math.min(entries.length, maxFeedItems);
for (var i = 0; i < count; i++) {
item = entries.item(i);
// Grab the title for the feed item.
var itemTitle = item.getElementsByTagName('title')[0];
if (itemTitle) {
itemTitle = itemTitle.textContent;
} else {
itemTitle = "Unknown title";
}
// Grab the link for this feed item
var itemLink = item.getElementsByTagName('link')[0];
if (itemLink) {
itemLink = itemLink.textContent;
} else {
itemLink = "Unknown link";
}
var title = document.createElement("a");
title.className = "item_title";
title.innerText = itemTitle; //display title in iframe
title.addEventListener("click", titleLink); // should open link when clicking on title, but does not.
}
// -------------------------------------------------------------------
// Show |url| in a new tab.
function showUrl(url) {
// Only allow http and https URLs.
if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
return;
}
chrome.tabs.create({url: url});
}
function moreStories(event) {
showUrl(moreStoriesUrl);
}
function titleLink(event) {
showUrl(itemLink);
}
Any thoughts on why this is not working.
If I replace title.addEventListener("click", titleLink); with title.addEventListener("click", moreStories); each title will link to moreStories, I cannot get each title to link to itemLink.
Thanks
Its a bit hard to answer your question without the whole code, but Ill give it a shot ;)
First up, titleLink() isnt going to work because itemLink isnt known. When you create title (the link) you should of attached it to that...say title.href=itemLink then in tiltleLinks you could access that href with showUrl(event.currentTarget.href)
Also did you fix the error in that example?...if not then change frameLoaded to....
function frameLoaded() {
var links = document.getElementsByTagName("A");
for (i = 0; i < links.length; i++) {
var clssName = links[i].className;
if (clssName != "item_title" && clssName != "open_box") {
links[i].addEventListener("click", showStory);
}
}
window.addEventListener("message", messageHandler);
}
If you still have probs could you attach the whole code so I can see what your doing and Ill give you a hand.
Thank you very much for your help.
code title.href=itemLink and code showUrl(event.currentTarget.href) was exactly what I needed.
For completeness, here is the full code,
<script id="iframe_script">
function reportHeight() {
var msg = JSON.stringify({type:"size", size:document.body.offsetHeight});
parent.postMessage(msg, "*");
}
function frameLoaded() {
var links = document.getElementsByTagName("A");
for (i = 0; i < links.length; i++) {
var class = links[i].className;
if (class != "item_title" && class != "open_box") {
links[i].addEventListener("click", showStory);
}
}
window.addEventListener("message", messageHandler);
}
function showStory(event) {
var href = event.currentTarget.href;
parent.postMessage(JSON.stringify({type:"show", url:href}), "*");
event.preventDefault();
}
function messageHandler(event) {
reportHeight();
}
</script>
<script>
// Feed URL.
var feedUrl = 'http://localhost/newsfeed.xml';
// The XMLHttpRequest object that tries to load and parse the feed.
var req;
function main() {
req = new XMLHttpRequest();
req.onload = handleResponse;
req.onerror = handleError;
req.open("GET", feedUrl, true);
req.send(null);
}
// Handles feed parsing errors.
function handleFeedParsingFailed(error) {
var feed = document.getElementById("feed");
feed.className = "error";
feed.innerText = "Error: " + error;
}
// Handles errors during the XMLHttpRequest.
function handleError() {
handleFeedParsingFailed('Failed to fetch RSS feed.');
}
// Handles parsing the feed data we got back from XMLHttpRequest.
function handleResponse() {
var doc = req.responseXML;
if (!doc) {
handleFeedParsingFailed("Not a valid feed.");
return;
}
buildPreview(doc);
}
// The maximum number of feed items to show in the preview.
var maxFeedItems = 10;
// Where the more stories link should navigate to.
var moreStoriesUrl;
function buildPreview(doc) {
// Get the link to the feed source.
var link = doc.getElementsByTagName("link");
var parentTag = link[0].parentNode.tagName;
if (parentTag != "item" && parentTag != "entry") {
moreStoriesUrl = link[0].textContent;
}
// Setup the title image.
var images = doc.getElementsByTagName("image");
var titleImg;
if (images.length != 0) {
var urls = images[0].getElementsByTagName("url");
if (urls.length != 0) {
titleImg = urls[0].textContent;
}
}
var img = document.getElementById("title");
// Listen for mouse and key events
if (titleImg) {
img.src = titleImg;
if (moreStoriesUrl) {
document.getElementById("title_a").addEventListener("click",moreStories);
document.getElementById("title_a").addEventListener("keydown",
function(event) {
if (event.keyCode == 13) {
moreStories(event);
}});
}
} else {
img.style.display = "none";
}
// Construct the iframe's HTML.
var iframe_src = "<!doctype html><html><head><script>" +
document.getElementById("iframe_script").textContent + "<" +
"/script></head><body onload='frameLoaded();' " +
"style='padding:0px;margin:0px;'>";
var feed = document.getElementById("feed");
// Set ARIA role indicating the feed element has a tree structure
feed.setAttribute("role", "tree");
var entries = doc.getElementsByTagName('item');
var count = Math.min(entries.length, maxFeedItems);
for (var i = 0; i < count; i++) {
item = entries.item(i);
// Grab the title for the feed item.
var itemTitle = item.getElementsByTagName('title')[0];
if (itemTitle) {
itemTitle = itemTitle.textContent;
} else {
itemTitle = "Unknown title";
}
// Grab the link for the feed item.
var itemLink = item.getElementsByTagName('link')[0];
if (itemLink) {
itemLink = itemLink.textContent;
} else {
itemLink = "Unknown link";
}
var item = document.createElement("div");
var title = document.createElement("a");
title.innerText = itemTitle; //display title in iframe
title.href=itemLink;
title.addEventListener("click", titleLink);
item.appendChild(title);
feed.appendChild(item);
}
if (moreStoriesUrl) {
var more = document.createElement("a");
more.className = "more";
more.innerText = "***Site Main Page*** \u00BB";
more.tabIndex = 0;
more.addEventListener("click", moreStories);
more.addEventListener("keydown", function(event) {
if (event.keyCode == 13) {
moreStories(event);
}});
feed.appendChild(more);
}
}
// -------------------------------------------------------------------
// Show |url| in a new tab.
function showUrl(url) {
// Only allow http and https URLs.
if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
return;
}
chrome.tabs.create({url: url});
}
// -------------------------------------------------------------------
function moreStories(event) {
showUrl(moreStoriesUrl);
}
function titleLink(event) {
showUrl(event.currentTarget.href);
}
function keyHandlerShowDesc(event) {
// Display content under heading when spacebar or right-arrow pressed
// Hide content when spacebar pressed again or left-arrow pressed
// Move to next heading when down-arrow pressed
// Move to previous heading when up-arrow pressed
if (event.keyCode == 32) {
showDesc(event);
} else if ((this.parentNode.className == "item opened") &&
(event.keyCode == 37)) {
showDesc(event);
} else if ((this.parentNode.className == "item") && (event.keyCode == 39)) {
showDesc(event);
} else if (event.keyCode == 40) {
if (this.parentNode.nextSibling) {
this.parentNode.nextSibling.children[1].focus();
}
} else if (event.keyCode == 38) {
if (this.parentNode.previousSibling) {
this.parentNode.previousSibling.children[1].focus();
}
}
}
function showDesc(event) {
var item = event.currentTarget.parentNode;
var items = document.getElementsByClassName("item");
for (var i = 0; i < items.length; i++) {
var iframe = items[i].getElementsByClassName("item_desc")[0];
if (items[i] == item && items[i].className == "item") {
items[i].className = "item opened";
iframe.contentWindow.postMessage("reportHeight", "*");
// Set the ARIA state indicating the tree item is currently expanded.
items[i].getElementsByClassName("item_title")[0].
setAttribute("aria-expanded", "true");
iframe.tabIndex = 0;
} else {
items[i].className = "item";
iframe.style.height = "0px";
// Set the ARIA state indicating the tree item is currently collapsed.
items[i].getElementsByClassName("item_title")[0].
setAttribute("aria-expanded", "false");
iframe.tabIndex = -1;
}
}
}
function iframeMessageHandler(e) {
// Only listen to messages from one of our own iframes.
var iframes = document.getElementsByTagName("IFRAME");
for (var i = 0; i < iframes.length; i++) {
if (iframes[i].contentWindow == e.source) {
var msg = JSON.parse(e.data);
if (msg) {
if (msg.type == "size") {
iframes[i].style.height = msg.size + "px";
}
else if (msg.type == "show") {
var url = msg.url;
if (url.indexOf("http://localhost/index.html") == 0) {
// If the URL is a redirect URL, strip of the destination and go to
// that directly. This is necessary because the Google news
// redirector blocks use of the redirects in this case.
var index = url.indexOf("&url=");
if (index >= 0) {
url = url.substring(index + 5);
index = url.indexOf("&");
if (index >= 0)
url = url.substring(0, index);
}
}
showUrl(url);
}
}
return;
}
}
}
window.addEventListener("message", iframeMessageHandler);
</script>
Thanks again for the help.
-Mike
I am looking to do this step: 'Creating a New FTP Site by Editing the IIS 7.0 Configuration Files' with a batch file and was wondering if anybody has done this already?
http://learn.iis.net/page.aspx/301/creating-a-new-ftp-site/
Try this. You need to reference the COM component "AppHostAdminLibrary"
using AppHostAdminLibrary;
...
public void AddFtp7Site(String siteName, String siteId, String siteRoot) {
String configPath;
String configSectionName;
var fNewSite = false;
var fNewApplication = false;
var fNewVDir = false;
//
// First setup the sites section
//
configPath = "MACHINE/WEBROOT/APPHOST";
configSectionName = "system.applicationHost/sites";
var adminManager = new AppHostAdminLibrary.AppHostWritableAdminManager();
adminManager.CommitPath = configPath;
try {
var sitesElement = adminManager.GetAdminSection(configSectionName, configPath);
IAppHostElement newSiteElement = null;
//
// check if site already exists
//
for (var i = 0; i < sitesElement.Collection.Count; i++) {
var siteElement = sitesElement.Collection[i];
if (siteElement.Properties["name"].Value.Equals(siteName) &&
siteElement.Properties["id"].Value.Equals(siteId)) {
newSiteElement = siteElement;
break;
}
}
if (newSiteElement == null) {
//
// Site doesn't exist yet. Add new site node
//
newSiteElement = sitesElement.Collection.CreateNewElement("");
newSiteElement.Properties["id"].Value = siteId;
newSiteElement.Properties["name"].Value = siteName;
fNewSite = true;
}
// setup bindings for the new site
var ftpBindingString = "*:21:";
var Bindings = newSiteElement.GetElementByName("bindings");
var BindingElement = Bindings.Collection.CreateNewElement("");
BindingElement.Properties["protocol"].Value = "ftp";
BindingElement.Properties["bindingInformation"].Value = ftpBindingString;
try {
Bindings.Collection.AddElement(BindingElement, 0);
}
catch (Exception ex) {
if (ex.Message != "") // ERROR_ALREADY_EXISTS ?
{
throw;
}
}
IAppHostElement newApplication = null;
//
// check if root application already exists
//
for (var i = 0; i < newSiteElement.Collection.Count; i++) {
var applicationElement = newSiteElement.Collection[i];
if (applicationElement.Properties["path"].Value.Equals("/")) {
newApplication = applicationElement;
break;
}
}
if (newApplication == null) {
newApplication = newSiteElement.Collection.CreateNewElement("application");
newApplication.Properties["path"].Value = "/";
fNewApplication = true;
}
IAppHostElement newVirtualDirectory = null;
//
// search for the root vdir
//
for (var i = 0; i < newApplication.Collection.Count; i++) {
var vdirElement = newApplication.Collection[i];
if (vdirElement.Properties["path"].Value.Equals("/")) {
newVirtualDirectory = vdirElement;
break;
}
}
if (newVirtualDirectory == null) {
newVirtualDirectory = newApplication.Collection.CreateNewElement("");
newVirtualDirectory.Properties["path"].Value = "/";
fNewVDir = true;
}
newVirtualDirectory.Properties["physicalPath"].Value = siteRoot;
if (fNewVDir) {
newApplication.Collection.AddElement(newVirtualDirectory, 0);
}
if (fNewApplication) {
newSiteElement.Collection.AddElement(newApplication, 0);
}
var ftpSiteSettings = newSiteElement.GetElementByName("ftpServer").GetElementByName("security").GetElementByName("authentication");
Console.WriteLine("Enable anonymous authentication");
var anonAuthSettings = ftpSiteSettings.GetElementByName("anonymousAuthentication");
anonAuthSettings.Properties["enabled"].Value = "true";
Console.WriteLine("Disable basic authentication");
var basicAuthSettings = ftpSiteSettings.GetElementByName("basicAuthentication");
basicAuthSettings.Properties["enabled"].Value = "false";
BindingElement.Properties["bindingInformation"].Value = "*:21:";
//
// Time to add new site element and commit changes
//
if (fNewSite) {
sitesElement.Collection.AddElement(newSiteElement, 0);
}
adminManager.CommitChanges();
}
catch (Exception ex) {
Console.WriteLine("Error occured in AddDefaultFtpSite: " + ex.Message);
}
//
// Add <authorization> section to allow everyone Read
//
Console.WriteLine("Enable everyone Read access");
try {
configPath = "MACHINE/WEBROOT/APPHOST/" + siteName;
configSectionName = "system.ftpServer/security/authorization";
var azSection = adminManager.GetAdminSection(configSectionName, configPath);
azSection.Collection.Clear();
var newAzElement = azSection.Collection.CreateNewElement("");
newAzElement.Properties["accessType"].Value = "Allow";
newAzElement.Properties["users"].Value = "*";
newAzElement.Properties["permissions"].Value = "Read";
azSection.Collection.AddElement(newAzElement, 0);
adminManager.CommitChanges();
}
catch (Exception ex) {
Console.WriteLine("Error occured while adding authorization section: " + ex.Message);
}
}
Does this help?:
http://blogs.iis.net/jaroslad/archive/2007/06/13/how-to-programatically-create-an-ftp7-site.aspx