Display and update applescript output in backgroun

2019-03-31 05:43发布

问题:

I have a short and sweet program that outputs my internal and external ip in applescript.

Here it is the Applescript code:

set inIP to IPv4 address of (get system info)
set exIP to (do shell script "curl ipecho.net/plain")
display dialog "Internal: " & inIP & "
External: " & exIP

I would like it to constantly update in the background and preferably not in a display dialog function as it does at the moment.

I do not want a display dialog constantly popping up so I am looking for example, displaying the IPs in the menu bar.

I do not know if this is possible to do with Applescript

回答1:

As from 10.10 (i Think) you can create real application using ApplescriptOBJC directly in Script Editor.

I have not really tried it before but once you get going it is easier than I expected.

Paste this code in a new Script Editor Applescript document.

Save it as a Stay open Application using the Save as… menu option.

Then run the app as a normal application.

Using the OP's original applescript code

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property StatusItem : missing value

-- check we are running in foreground - YOU MUST RUN AS APPLICATION. to be thread safe and not crash
if not (current application's NSThread's isMainThread()) as boolean then
    display alert "This script must be run from the main thread." buttons {"Cancel"} as critical
    error number -128
end if

-- create an NSStatusBar
on makeStatusBar()
    set bar to current application's NSStatusBar's systemStatusBar

    set StatusItem to bar's statusItemWithLength:-1.0

    -- set up the initial NSStatusBars title
    StatusItem's setTitle:"IP"
end makeStatusBar

-- update statusBar
on displayIP(theDisplay)
    StatusItem's setTitle:theDisplay
end displayIP

--repeat run  update code
on idle

    --get the IPs
    set inIP to IPv4 address of (get system info)
    set exIP to (do shell script "curl ipecho.net/plain")

    set theDisplay to "Internal: " & inIP & " External: " & exIP

    my displayIP(theDisplay)
    return 30 -- run every 30 seconds

end idle
-- call to create initial NSStatusBar
my makeStatusBar()

The app is set to run every 30 seconds. It will update a status bar menu in the menu bar with your ips.

I have not put any error checking in and leave that to you.

Also remember if you want to run the code while in Script Editor then make sure you use "Run Application".


Update:1 I have changed the internal IP address code to use NShost which is quicker and probably more reliable than the "get system info"

Update:2

Update the external code to use a NSURL request rather than the Original Curl do shell script command.

This allows for easier error checks if the is a failure in obtaining the external ip address due to no network connection...etc.

Curl will return a whole log of info as to why it failed and be IMHO a pain.

Updated applescript code

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property StatusItem : missing value

-- check we are running in foreground - YOU MUST RUN AS APPLICATION. to be thread safe and not crash
if not (current application's NSThread's isMainThread()) as boolean then
    display alert "This script must be run from the main thread." buttons {"Cancel"} as critical
    error number -128
end if

-- create an NSStatusBar
on makeStatusBar()
    set bar to current application's NSStatusBar's systemStatusBar

    set StatusItem to bar's statusItemWithLength:-1.0

    -- set up the initial NSStatusBars title
    StatusItem's setTitle:"IP"
end makeStatusBar

-- update statusBar
on displayIP(theDisplay)
    StatusItem's setTitle:theDisplay
end displayIP

--repeat run  update code
on idle

    --get the IPs

    set stringAddress to ""
    --use NSHost to get the Internal IP address 
    set inIPAddresses to current application's NSHost's currentHost's addresses

    --work through each item to find the IP
    repeat with i from 1 to number of items in inIPAddresses
        set anAddress to (current application's NSString's stringWithString:(item i of inIPAddresses))
        set ipCheck to (anAddress's componentsSeparatedByString:".")
        set the Counter to (count of ipCheck)

        if (anAddress as string) does not start with "127" then
            if Counter is equal to 4 then
                set stringAddress to anAddress
                -- found a match lets exit the repeat
                exit repeat
            end if
        else
            set stringAddress to "Not available"
        end if
    end repeat

    -- Get extenal IP

    set anError to missing value
    set iPURL to (current application's NSURL's URLWithString:"http://ipecho.net/plain")

    set NSUTF8StringEncoding to 4
    set exIP to (current application's NSString's stringWithContentsOfURL:iPURL encoding:NSUTF8StringEncoding |error|:anError) as string
    if exIP contains missing value then
        set exIP to "Not available"
    end if



    set theDisplay to "Intl: " & stringAddress & " Extnl: " & exIP

    --call to update statusBar
    my displayIP(theDisplay)

    return 30 -- run every 30 seconds

end idle
-- call to create initial NSStatusBar
my makeStatusBar()

UPDATE 3

This one will do as the OP asked in the comments.

It now has a drop down menu with two options External or Internal.

Select one or the other menu item will change the status bar to show the chosen IP.

This last one was thrown together quickly so it is not pretty. :-)

( UPDATE 4 It also persists the selection on quitting the app and relaunching. )


New code:

  use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property StatusItem : missing value
property selectedMenu : "" -- each menu action will set this to a number, this will determin which IP is shown

property theDisplay : ""
property defaults : class "NSUserDefaults"

-- check we are running in foreground - YOU MUST RUN AS APPLICATION. to be thread safe and not crash
if not (current application's NSThread's isMainThread()) as boolean then
    display alert "This script must be run from the main thread." buttons {"Cancel"} as critical
    error number -128
end if

-- create an NSStatusBar
on makeStatusBar()
    set bar to current application's NSStatusBar's systemStatusBar

    set StatusItem to bar's statusItemWithLength:-1.0

    -- set up the initial NSStatusBars title
    StatusItem's setTitle:"IP"
    set newMenu to current application's NSMenu's alloc()'s initWithTitle:"Custom"
    set internalMenuItem to current application's NSMenuItem's alloc()'s initWithTitle:"Internal" action:"showInternal:" keyEquivalent:""
    set externalMenuItem to current application's NSMenuItem's alloc()'s initWithTitle:"External" action:"showIExternal:" keyEquivalent:""

    StatusItem's setMenu:newMenu
    newMenu's addItem:internalMenuItem
    newMenu's addItem:externalMenuItem
    internalMenuItem's setTarget:me
    externalMenuItem's setTarget:me
end makeStatusBar

--Show Internal ip Action
on showInternal:sender


    defaults's setObject:"1" forKey:"selectedMenu"
    my runTheCode()
end showInternal:

--Show External ip Action
on showIExternal:sender


    defaults's setObject:"2" forKey:"selectedMenu"
    my runTheCode()
end showIExternal:

-- update statusBar
on displayIP(theDisplay)
    StatusItem's setTitle:theDisplay
end displayIP

on runTheCode()

    set stringAddress to ""
    --use NSHost to get the Internal IP address 
    set inIPAddresses to current application's NSHost's currentHost's addresses

    --work through each item to find the IP
    repeat with i from 1 to number of items in inIPAddresses
        set anAddress to (current application's NSString's stringWithString:(item i of inIPAddresses))
        set ipCheck to (anAddress's componentsSeparatedByString:".")
        set the Counter to (count of ipCheck)

        if (anAddress as string) does not start with "127" then
            if Counter is equal to 4 then
                set stringAddress to anAddress
                -- found a match lets exit the repeat
                exit repeat
            end if
        else
            set stringAddress to "Not available"
        end if
    end repeat

    -- Get extenal IP

    set anError to missing value
    set iPURL to (current application's NSURL's URLWithString:"http://ipecho.net/plain")

    set NSUTF8StringEncoding to 4
    set exIP to (current application's NSString's stringWithContentsOfURL:iPURL encoding:NSUTF8StringEncoding |error|:anError) as string
    if exIP contains missing value then
        set exIP to "Not available"
    end if

    set selectedMenu to (defaults's stringForKey:"selectedMenu") as string
    if selectedMenu is "" or selectedMenu contains missing value then
        set selectedMenu to "1"
    end if

    if selectedMenu is "1" then
        set theDisplay to "Intl: " & stringAddress
    else if selectedMenu is "2" then
        set theDisplay to " Extnl: " & exIP
    end if

    --call to update statusBar
    my displayIP(theDisplay)


end runTheCode

--repeat run  update code
on idle

    my runTheCode()
    --my displayIP(theDisplay)

    return 30 -- run every 30 seconds

end idle
-- call to create initial NSStatusBar
set defaults to current application's NSUserDefaults's standardUserDefaults
my makeStatusBar()