Using script to fire Xcode bot - xcode

Is there a way to manually fire existing Xcode bots using shell scripts? I have a manual bot and I'd like to fire it based on certain custom logic criteria.

Yes.
You'll need to do a couple of things:
Firstly, I'm going to call your Xcode Server's IP address XCS_IP, usually localhost if you're on the machine where Xcode Server's running.
Find out the ID of the bot: in Terminal, run curl -k "https://XCS_IP:20343/api/bots". Copy the output to some editor and find the value for key _id for your bot, will be something like 6b3de48352a8126ce7e08ecf85093613. Let's call it BOT_ID.
Trigger an integration by running curl -k -X POST -u "username:password" "https://XCS_IP:20343/api/bots/BOT_ID/integrations" -i
Where username and password are credentials of a user that is allowed to create bots on the server, an admin will do.
If you're interested in more details, I have an app in Swift that uses that API and many more: https://github.com/czechboy0/Buildasaur/blob/master/BuildaCIServer/XcodeServer.swift#L324
And checkout my article on how to find Xcode Server's API "documentation": http://honzadvorsky.com/blog/2015/5/4/under-the-hood-of-xcode-server.
TL;DR? On your Mac, look at /Applications/Xcode.app/Contents/Developer/usr/share/xcs/xcsd/routes/routes.js, where you can find the available APIs.
Hope this helped.

Apple has added documentation for the Xcode server API that you can use to trigger bots.
https://developer.apple.com/library/tvos/documentation/Xcode/Conceptual/XcodeServerAPIReference/index.html#//apple_ref/doc/uid/TP40016472-CH1-SW1
Below is some example code on how you can make a python script that triggers a bot.
import requests
xcodeIP = '1.2.3.4.5'
def main():
botName = "name of bot"
runBot(botName)
def runBot(botName):
requests.post(xcodeIP + '/api/bots/' + getBot(botName)["_id"] + '/integrations', auth=('username', 'password'), verify=False)
def getBot(botName):
botIDRequest = requests.get(xcodeIP + '/api/bots', auth=('username', 'password'), verify=False)
bots = botIDRequest.json()["results"]
for bot in bots:
if bot["name"] == botName:
return bot
if __name__ == "__main__":
main()

Related

How to access Clockify API through Power Query

I am trying to get my time entries from Clockify API directly via Power Query to Excel. I use the following code in the Power Query:
= Web.Contents("https://api.clockify.me/api/workspaces/ID of my workspace/timeEntries/", [
Query=[ #"filter"="", #"orderBy"=""],
ApiKeyName="APIToken"
])
When I then try to run the code I am prompted to enter the Web API authentification, which delivers an error ("English translation: Authentification does not work. Try again") after I enter my correct Web API code see screenshot here
Does anyone have an idea how to solve this?
There are two things to keep in mind when making calls to REST-based APIs in Power Query/M:
When using the Web.Contents() function, it's best to pass your API key as a parameter within the request header itself. In your case X-Api-Key should equal to {your API key}.
Use anonymous access to connect to the API. Your screenshot suggests you're trying to connect using "Web API". Clear the value in the "Schlüssel" field and use "Anonym" instead.
Here's a simple example where I return the information about a workspace by workspace ID. (I've masked both my workspace ID and API key; replace these values with your workspace ID and API key.)
This works for me in both Excel and Power BI:
let
Source =
Web.Contents(
"https://api.clockify.me/api/workspaces/{your workspace ID}",
[
Headers=[
#"Content-Type"="application/json",
#"X-Api-Key"={your API key}
]
]
),
jsonResponse = Json.Document(Source)
in
jsonResponse
Doesn't it have to be X-Api-Key instead of ApiKeyName?

Which event type is triggered when a slack app is installed onto a workspace for the first time?

I'm trying to build an app that does something when it is first installed onto a workspace, eg: Ping every team member.
I couldn't find an event type that gets triggered upon app install:
https://api.slack.com/events
Is there a way to make this happen?
I think there might be a misunderstanding of the events concepts here. Events are always directly linked to one specific Slack app and needs to be processed by that very app. There is no such thing as "general" events for things happening on a workplace, like a new app being installed. Ergo there is no event for app installation.
Nevertheless you can implement the functionality you mentioned with Slack, e.g. pinging all team members once an app is first installed. All you need to do is include this function in the installation process of your Slack app and e.g. start pinging after the installation process is complete and the app verified that it was the first installation to this workspace. You do not need an event for that.
This is a partial answer because I was wondering the same thing and wanted to share what I found. On this oauth tutorial, it has the following code snippet:
app.get('/auth', function(req, res){
if (!req.query.code) { // access denied
return;
}
var data = {form: {
client_id: process.env.SLACK_CLIENT_ID,
client_secret: process.env.SLACK_CLIENT_SECRET,
code: req.query.code
}};
request.post('https://slack.com/api/oauth.access', data, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Get an auth token
let oauthToken = JSON.parse(body).access_token;
// OAuth done- redirect the user to wherever
res.redirect(__dirname + "/public/success.html");
}
})
});
I believe instead of the line res.redirect(__dirname + "/public/success.html"); at that point you can make a request to ping everyone or even call a function to do so directly there, and it will trigger immediately once the app has been installed.

How to create app with parse server?

In parse.com, when I want to create new app, I use:
curl -X POST \
-H "X-Parse-Email: <PARSE_ACCOUNT_EMAIL>" \
-H "X-Parse-Password: <PARSE_ACCOUNT_PASSWORD>" \
-H "Content-Type: application/json" \
-d '{"appName":"my new app","clientClassCreationEnabled":false}' \
https://api.parse.com/1/apps
But when I deployed Parse server to Heroku and Digital Ocean, I didn't know to create new app, because my server doesn't have PARSE_ACCOUNT_EMAIL and PARSE_ACCOUNT_PASSWORD. When I deployed parse dashboard, it didn't have "Create a new app" like Parse.com.
How can I create new app with my self-hosted Parse server?
The self hosted parse servers can only handle one app per server, at least for now.
This means that you will have to use several installations of Parse, one app per installation using multiple servers or multiple instances of parse on the same server but configure each server to use different ports.
To answer you question: No you do not need to use parse.com to create new apps.
To create a new app you set the appID and password in the parse config/start file on your digital ocean or other hosted server.
The appID and password can be anything that you make up, it does not need to be from parse.com.
Below is an example of the environment settings in a startup file:
**Example file: ~/parse-server-example/my_app.js**
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
// Configure the Parse API
var api = new ParseServer({
databaseURI: 'mongodb://localhost:27017/dev',
cloud: __dirname + '/cloud/main.js',
appId: 'myOtherAppId',
masterKey: 'myMasterKey'
});
var app = express();
// Serve the Parse API on the /parse URL prefix
app.use('/myparseapp', api);
// Listen for connections on port 1337
var port = 9999;
app.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
Then run the file with:
node my_app.js
You can read more here: Parse Server at Digital Ocean
There is an open issue for that: https://github.com/ParsePlatform/parse-dashboard/issues/188
For the moment, I just use parse's hosted dashboard to create new apps. They say on January 28th, calls to their API will cease to function. They don't say that the hosted dashboard will be going away. I imagine that, if they don't get it into the self-hosted version, you'll still be able to create new apps within the hosted dashboard.
In any case, for now what I am doing is creating the app as I normally would in the hosted dashboard. I then run the migration tool at app > app settings > general > Migrate to external database option. You have to add at least one class to the database in order for the migration tool to work. Basically, the migration tool will fail with some ambiguous error message if it's a completely fresh app with a clean database.
Once the migration is done and read/writes are hooked up to my self-hosted Parse Server, I then providing the app's keys, etc in the parse-dashboard-config.json file of my self-hosted Parse Dashboard. You can add multiple apps to this config file, thus manage all of your apps from a single self-hosted Parse Dashboard.
Here's an example of that config file with two apps:
{
"apps": [
{
"serverURL": "https://my-parse-server-1.herokuapp.com/parse",
"appId": "b44gL7uAB1z...lwUJneaoKdX9",
"masterKey": "HrSqFbH...hfiwuCCOLDvHF",
"appName": "parse-server-1"
},
{
"serverURL": "https://my-parse-server-2.herokuapp.com/parse",
"appId": "b44gL7uAB1z...lwUJneaoKdX9",
"masterKey": "HrSqFbH...hfiwuCCOLDvHF",
"appName": "parse-server-2"
}
],
"users": [
{
"user":"admin",
"pass":"somePasswordHere"
}
]
}
This seems to be the only way currently to create apps that you can connect to your self-hosted Parse Dashboard.
It's also important to note that, at the moment, it appears as though the self-hosted Parse Server package only supports a single app. I have no idea if there are any plans to support multiple apps as they have done with Parse Dashboard.
And finally, you can use the Parse Command Line tool to create new apps as well: https://parse.com/docs/cloudcode/guide#command-line-creating-a-parse-app
They also have some interesting integrations with Heroku which facilitate the entire process. That might be worth looking into. You could create a simple Node app yourself with a GUI for creating new Parse apps. In this case, you would create a simple form, that when submitted is validated and then executes the command line methods to create a new app with the ShellJS node package. You could even modify the Parse Dashboard package to include this feature yourself within the self-hosted Dashboard.

"Insufficient permissions" on google calendar api's acl.list

I'm getting Insufficient permissions when trying to call the acl.list method of the google calendar api via python.
service.acl().list(calendarId='primary').execute();
*** HttpError: <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/acl?alt=json returned "Insufficient Permission">
I'm using the scope 'https://www.googleapis.com/auth/calendar' as recommended in the documentation. Additionally, other API methods do work, for example service.calendarList
service.calendarList().list(pageToken=page_token).execute()
What am I missing?
Here is the code I'm using based almost entirely on the sample they provide:
import sys
from oauth2client import client
from googleapiclient import sample_tools
def main(argv):
# Authenticate and construct service.
# import pdb;pdb.set_trace()
service, flags = sample_tools.init(
argv, 'calendar', 'v3', __doc__, __file__,
# scope='https://www.googleapis.com/auth/calendar.readonly')
scope='https://www.googleapis.com/auth/calendar')
try:
page_token = None
while True:
calendar_list = service.calendarList().list(pageToken=page_token).execute()
for calendar_list_entry in calendar_list['items']:
print calendar_list_entry['summary']
page_token = calendar_list.get('nextPageToken')
service.acl().list(calendarId='primary').execute();
if not page_token:
break
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run'
'the application to re-authorize.')
if __name__ == '__main__':
main(sys.argv)
You might have to delete existing credentials, in the form of .json files. I had a similar "Insufficient permissions" problem, and I had to delete stored credentials. I had the additional problem that because of trying out some of Google's scripts in their tutorials, unknowingly I had credentials stored in a hidden .credentials folder in my home directory (users/home). Since they were hidden, I had to look for them through Terminal (on Mac), and delete them there. Once deleted, the problem was solved, since I could create new and proper credentials, suitable for the scope of my new script.
Something is wrong with your authentication. Insufficent permissions means that you don't have access.
I can verify that the scope https://www.googleapis.com/auth/calendar is enough to display ACL.list on the primary calendar.
You have to find the location of "calendar-dotnet-quickstart.json" file and delete it. I used .NET example and I have to debug the following code the find exact location.
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json");
Then change scope as bellow and rebuild the solution.
string[] scopes = { CalendarService.Scope.Calendar};
You will notice that google will ask to confirm the access again.

Programmatically changing wireless router settings - Netgear ideally

Is it possible to programmatically change settings on a Netgear wireless router using C#? I have settings that I change often and I would like to create my own interface for making those changes. Currently I navigate to the admin web page (10.0.0.1) and it prompts me for a username and password. After I authenticate I can use the web interface to change the router's configuration.
If this isn't possible with Netgear, do any outher wireless routers have an API for developers?
There aren't any APIs out there to do this, but you can write something to make HTTP requests to the router to simulate the webUI being used.
I'm guessing most consumer routers are probably pretty simple to talk to. Authentication is probably nothing more than basic realm.
Selenium offers a firefox plugin that lets you record manual interactions with your browser. And then you can export the steps to python, ruby, java or c#. It worked for me to programmatically adjust my router settings to turn off wifi. Clicking on the elements while recording identifies everything you need.
This code works on an Actiontec MI424WR (FIOS)
Edit the code to add your username, password, and router address.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
class Routr(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "http://routerip_or_address"
self.verificationErrors = []
self.accept_next_alert = True
def test_routr(self):
driver = self.driver
driver.get(self.base_url + "/")
driver.find_element_by_name("user_name").clear()
driver.find_element_by_name("user_name").send_keys("your_username")
driver.find_element_by_id("pass2").clear()
driver.find_element_by_id("pass2").send_keys("enter_your_password_here")
driver.find_element_by_link_text("OK").click()
driver.find_element_by_link_text("Change Wireless Settings").click()
driver.find_element_by_id("ws_off").click()
driver.find_element_by_link_text("Apply").click()
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException, e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException, e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
If this is just a few things you want to change programmatically, simulating HTTP requests should be simple enough. Another option would be to install DD-WRT in your router, basically transforming it into a small Linux installation that allows full programmatic configuration through SSH using standard Linux commands.
I'm unaware of any consumer-grade routers that have an API like that, but you could always build something that (ab)uses the Web interface to do what you want, using something like selenium-rc or watir
MiktoTik sells customer grade routers that allow ssh configuration (mind that they use ssh, but not bash inside ssh). You can even roll your own PHP REST API for router (not that I like PHP, but people are doing it).
I'm not familiar with this router, but I have done similar stuff programmatically via a telnet connection the router with Python.
There's a cood telnet lib for C#:
http://www.codeproject.com/KB/IP/MinimalisticTelnet.aspx
There is a python based Github repo here that describes a SOAP based API. I've used it to program a device schedule for my kids devices. Not willing to pay Disney for Circle. Works great. There's also a js version here.

Resources