0.4.0 • Published 6 years ago

unix-remotecontrol v0.4.0

Weekly downloads
2
License
ISC
Repository
github
Last release
6 years ago

Unix Remote Control (IOT)

NPM

Build Status npm npm GitHub release GitHub issues GitHub closed pull requests

Runs Scripts on Mac/Linux remotely.

Why :

I was setting up homebridge (iOS HomeKit Accesory Protocol) on my rasberryPi and after hooking up my IR Blaster, RF Transmitter and other wake-on-lan devices. I wanted my always-on OSX Laptop to also be remotely controlled by my iOS Device. So i ended up writing up a small plugin for Homebridge plugin.

I use this to play itunes, search google and bookmark search results, restart my system, get room temperature using MBP in-build Temp Sensor and adjust airconditioning accordingly, monitor my ec-2 instance stats, sync Spotify Playlist etc.

Homebridge Plugin => homebridge-unixcontrol

How it Works :

This library is directly injected into homebridge with a plugin wrapper => homebridge-unixcontrol

The plugin queries the system using HTTP API and run shell scripts. The shell requires sudo access to shutdown/reboot the system. More commands can be easily be injected. Feel free to PR.

You can ask Siri to execute commands :

Hey Siri, Shutdown my laptop

Hey Siri, play iTunes Playlist

Hey Siri, Good Morning ! // Plays Music, Backups OSX, Search for Google Alerts, Turns Off Air Conditioner

Hey Siri, Capture Laptop Webcam

Hey Siri, Who's using my laptop

Todo :

  • Add Linux Support
  • Add Windows Support
  • Refactor With Promises
  • Replace HTTP API with socket connection.
  • Implement a working Example
  • Security Concerns

Installation :

 $ npm install -g unix-remotecontrol

Starting Server :

 $ unixremote

Running Forever

 $ npm install -g forever
 $ git clone https://github.com/sahilchaddha/unix-remoteControl.git && cd unix-remoteControl
 $ forever start src/server.js

Configuration :

Configuration containing sudo password, port number, logLevel & sessionToken are stored in environment.js in root/src.

To Open Configuration for global module :

 $ unixremote --config

Sample Configuration :

//environment.js
var env = {
    port: '3000',
    pass: 'lol', //sudo password TODO: Secure
    logLevel: 'info',
    sessionToken: 'f64f2940-fae4-11e7-8c5f-ef356f279131'
}

module.exports = env

Config Parameters

FieldsDescription
portPort Number to run HTTP Server.
passSystem Sudo Password
logLevelLog Level (debug, info, error)
sessionTokenRandom Session Token for API Authentication.

NOTE: sessionToken needs to be set as Request Header token

Usage :

After Running the server, You can request

localhost:portNumber/commandType/command

e.g.

POST localhost:3000/power/shutdown
    {
        "time": 10
    }
curl --header "token: f64f2940-fae4-11e7-8c5f-ef356f27913" -X POST localhost:3000/power/logout

curl --header "token: f64f2940-fae4-11e7-8c5f-ef356f27913" "Content-Type: application/json" -X POST -d '{"time":10}' localhost:3000/power/restart 

curl --header "token: f64f2940-fae4-11e7-8c5f-ef356f27913" "Content-Type: application/json" -X POST -d '{"destination":"AppleMusic"}' localhost:3000/music/syncSpotify

Sample Scripts/Commands :

Power Command Type

Usage:-

localhost:3000/power/displaySleep

POST localhost:3000/power/restart
    {
        "time": 10
    }
CommandMethodDescriptionParamsSudo
/pingGETPings to get server state (on/off)Nonefalse
/haltPOSTShutdowns immediately & forcibly (Can cause data loss)Nonetrue
/shutdownPOSTShut downs the systemtime (minutes) : Delays Shutdown in minutestrue
/restartPOSTRestarts the systemtime (minutes) : Delays Shutdown in minutestrue
/logoutPOSTLogs Out the user (OSX Only)Nonefalse
/sleepPOSTTurns the System to SleepNonefalse
/displaySleepPOSTTurns the Display to SleepNonefalse
/cancelShutdownPOSTCancels Scheduled Shutdown/Restart TaskNonetrue

System Stats Command Type

Usage:-

localhost:3000/systemStats/temperature

localhost:3000/systemStats/ram

CommandMethodDescriptionParamsSudo
/temperatureGETReturns current Temperature of CPUNonefalse
/cpuLoadGETReturns current CPU LoadNonefalse
/ramGETReturns current Ram StatusNonefalse
/storageGETReturns current Storage StatsNonefalse
/batteryGETReturns current Battery InformationNonefalse

Browser Command Type

Usage:-

localhost:3000/browser/googleChromeReset

CommandMethodDescriptionParamsSudo
/googleChromeResetPOSTClear all data of google chrome and resetNonefalse
/safariClearHistoryPOSTClear histroy of safariNonefalse

NOTE: For safariClearHistory you will have to add terminal or whatever command line tool you are using should be added in System Preferences -> Security & Privacy -> Privacy -> Accessibility. When you run this command for the first time there will a prompt to add command line tool in Accessibility.

Wi-fi Command Type

Usage:-

localhost:3000/wifi/on

CommandMethodDescriptionParamsSudo
/statusGETReturns Wifi Enabled/Disabled Status (OS X Only)Nonefalse
/onPOSTTurn on wifi (OS X Only)Nonefalse
/offPOSTTurn off wifi (OS X Only)Nonefalse
/connectPOSTConnect to wifi (OS X Only)name: wifi name, password: wifi passwordfalse

Bluetooth Command Type

Usage:-

localhost:3000/bluetooth/status

CommandMethodDescriptionParamsSudo
/statusGETReturns Bluetooth Enabled/Disabled Status (OS X Only)Nonefalse
/onPOSTTurn on Bluetooth (OS X Only)Nonefalse
/offPOSTTurn off Bluetooth (OS X Only)Nonefalse
/showPairingAlertPOSTShow pairing alert or pair with any BLE enabled device (OS X Only)deviceName: Bluetooth name of device with percentage encodingfalse
/togglePOSTToggle device bluetooth connection (OS X Only)deviceName: Bluetooth name of device with percentage encodingfalse

NOTE: blueutil is added as a depedancy for Bluetooth Connections. It will be automatically installed during npm install. Its added as postInstall Script in package.json. If for some reason installation of blueutil fails, you can manually install blueutil brew install blueutil

System Spy Command Type

Usage:-

localhost:3000/systemSpy/screenshot

localhost:3000/systemSpy/camRecord

localhost:3000/systemSpy/alert
    {
        "message": "Heeeyyy !!! Hooooo !!!"
    }
localhost:3000/systemSpy/notify
    {
        "title": "heyyy",
        "message": "hooo"
    }
CommandMethodDescriptionParamsSudo
/screenshotPOSTScreenshots Current Screen, Saves & returns image (OSX Only)Nonefalse
/webcamCapturePOSTClicks Camera Still, Saves & returns image (OSX Only)Nonefalse
/screenRecordPOSTStarts Screen Recording (OSX Only)time (In Minutes): Start recording for specific time. Here time is optional if you want to run this command forever than do not pass any argumentsfalse
/camRecordPOSTStarts Camera Recording (OSX Only)time (In Minutes): Start recording for specific time. Here time is optional if you want to run this command forever than do not pass any argumentsfalse
/alertPOSTShows Alert to Usermessage: Message to Show Alertfalse
/notifyPOSTShows Notification to Usertitle: Title For Notification, message: Messagefalse
/isRecordingGETReturns Recording Status (OSX Only)type : screen or cam type of recordingfalse

Music Command Type

Usage:-

localhost:3000/music/itunesPlaylist

localhost:3000/music/setVolume
    {
        "volume": 10
    }
CommandMethodDescriptionParamsSudo
/youtubePlaylistPOSTOpens Youtube & Starts Playing Playlist defined in environment.js (OSX Only)Nonefalse
/itunesPlaylistPOSTOpens iTunes & Starts Playing Playlist defined in environment.js (OSX Only)Nonefalse
/setVolumePOSTSets New Volume (OSX Only)volume: volume to be set. Should be between 0 to 10false
/getVolumeGETReturns Current Volume (OSX Only)Nonefalse
/mutePOSTMutes the System (OSX Only)Nonefalse
/unmutePOSTUnMutes the System (OSX Only)Nonefalse
/isMutedGETReturns Mute Status (OSX Only)Nonefalse

Todo Scripts :

  • Remote System Backup
  • Remote System Format (Need extra OSX Device to test. :P )

Writing Custom Scripts :

Cloning the Repo :

 $ git clone https://github.com/sahilchaddha/unix-remoteControl.git && cd unix-remoteControl
 $ node src/server.js
 or
 $ npm start

Creating Your Router :

You can create your custom router inside Routes folder.

//DummyRouter.js
var router = require('express').Router() // Create New Router
var commandService = require('../Services/CommandService.js')

router.get('/hello', function (req, res) {
  res.send('Hello')
  // Run Your npm commands
  // or call Shell Scripts using Command Service

    commandService.execute('dummy', 'sayHello', options, function(){})
})

module.exports = router

Adding your Router to Valid Routes :

Add your custom router inside routes.js

var powerRouter = require('./Routes/PowerRouter.js')
var dummyRouter = require('./Routes/DummyRouter.js')

var routes = [
    {
        url: '/power',
        routerClass: powerRouter
    },
    {
        url: '/dummy',
        routerClass: dummyRouter
    }
]

module.exports = routes

Adding Your Shell Scripts :

You can use Command Service to execute commands :

To add Commands, you can inject your commands inside Commands/commands.js

var dummyCommands = {
    sayHello: {
        command: ['say', 'hello'],
        sudo: false // Set as true if command need sudo access
    }
}

module.exports = {
    // power: powerCommands,
    dummy: dummyCommands
}

Apple Scripts

Apple scripts in format .scpt are to be injected inside AppleScripts folder.

You can add command inside commands.js

var dummyCommands = {
    sayHello: {
        command: ['say', 'hello'],
        sudo: false // Set as true if command need sudo access
    },
    runAppleScript: {
        command: ['osascript', 'src/Commands/AppleScripts/dummyAS.scpt'],
        sudo: false
    }
}

module.exports = {
    // power: powerCommands,
    dummy: dummyCommands
}

Homebridge on Raspberry Pi :

Homebridge Configuration :

WIP

On Pi :

$ ssh pi@192.168.1.2 // Your Pi Local Address
$ npm install -g homebridge
$ npm install -g homebridge-unixcontrol

// Configure Homebridge config.json

On Unix System (For Remote Access) :

$ npm install -g unix-remotecontrol
$ unixremote --config //Setup Your Configuration
$ unixremote

Credits :

Sahil Chaddha (mail@sahilchaddha.com)

Sumit Chudasama (imsrc21@gmail.com)

Reference :