Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

月: 2018年3月

光学ドライブ情報の取得

Posted on 3月 10, 2018 by Takaaki Naganoya

AppleScript名:光学ドライブ情報の取得.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/03/10
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions

set dInfoList to getOpticalDrivesInfo() of me
–> {{driveNum:"1", vendorName:"BUFFALO", productName:"Optical Drive", supportLevel:"Unsupported", revisionNo:"BFT6", busName:"USB", suppoortLevel:"Unsupported"}, {driveNum:"2", vendorName:"MATSHITA", productName:"BD-MLT UJ240AS", supportLevel:"Unsupported", revisionNo:"1.00", busName:"USB", suppoortLevel:"Unsupported"}}

–光学ドライブの情報を返す
on getOpticalDrivesInfo()
  set dList to paragraphs of (do shell script "drutil list")
  
set d2List to removeItemFromList(dList, "") of me
  
  
if length of d2List = 1 then return false –No Optical Drive
  
  
set d2List to rest of d2List –skip first header row
  
  
set dMainList to {}
  
repeat with i in d2List
    set tmpA to (current application’s NSString’s stringWithString:i)
    
set tmpB to (tmpA’s componentsSeparatedByString:" ") as list –parse string by space character
    
set tmpC to removeItemFromList(tmpB, "") of me –remove empty item from list
    
    
set dNum to first item of tmpC
    
set aVendor to second item of tmpC
    
set supLevel to last item of tmpC
    
set busStr to item -2 of tmpC
    
set revStr to item -3 of tmpC
    
    
–Product Nameのlist itemをスペースでつないで文字列化
    
set prodName1 to items 3 thru -4 of tmpC
    
set prodName2 to retStrFromArrayWithDelimiter(prodName1, " ") of me
    
    
set the end of dMainList to {driveNum:dNum, vendorName:aVendor, productName:prodName2, supportLevel:supLevel, revisionNo:revStr, busName:busStr, suppoortLevel:supLevel}
  end repeat
  
  
return dMainList
end getOpticalDrivesInfo

–1D Listから指定内容の要素をすべて削除する
on removeItemFromList(aTargList, aTargValue)
  set anArray to current application’s NSMutableArray’s arrayWithArray:aTargList
  
repeat
    set aInd to anArray’s indexOfObject:aTargValue
    
–macOS 10.12〜10.13.0までのNSNotFoundの値定義の間違いというAppleの恥ずかしいバグに対処
    
if aInd = current application’s NSNotFound or (aInd as real > 9.99999999E+8) then exit repeat
    
anArray’s removeObjectAtIndex:aInd
  end repeat
  
return anArray as list
end removeItemFromList

–リストを指定デリミタをはさんでテキスト化
on retStrFromArrayWithDelimiter(aList, aDelim)
  set anArray to current application’s NSArray’s arrayWithArray:aList
  
set aRes to anArray’s componentsJoinedByString:aDelim
  
return aRes as text
end retStrFromArrayWithDelimiter

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

使用メモリーの状況を取得

Posted on 3月 10, 2018 by Takaaki Naganoya
AppleScript名:使用メモリーの状況を取得
— Created 2017-12-17 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set mRes to retMemoryUsage() of me
–> {usedMem:7928, wiredMem:1763, unusedMem:257}

on retMemoryUsage()
  set memRes to do shell script "top -l 1 | head -10 | grep ’PhysMem’"
  
set aRes to (parseStrFromTo(memRes, " ", "M") of me)
  
  
set bList to {}
  
repeat with i in aRes
    set mRes to returnNumberOnly(i) of me
    
set the end of bList to mRes
  end repeat
  
  
set usedNum to contents of first item of bList
  
set wiredNum to contents of second item of bList
  
set unusedNum to contents of third item of bList
  
return {usedMem:usedNum as integer, wiredMem:wiredNum as integer, unusedMem:unusedNum as integer}
end retMemoryUsage

on parseStrFromTo(aParamStr, fromStr, toStr)
  set theScanner to current application’s NSScanner’s scannerWithString:aParamStr
  
set anArray to current application’s NSMutableArray’s array()
  
  
repeat until (theScanner’s isAtEnd as boolean)
    — terminate check, return the result (aDict) to caller
    
set {theResult, theKey} to theScanner’s scanUpToString:fromStr intoString:(reference)
    
    
— skip over separator
    
theScanner’s scanString:fromStr intoString:(missing value)
    
set {theResult, theValue} to theScanner’s scanUpToString:toStr intoString:(reference)
    
if theValue is missing value then set theValue to "" –>追加
    
    
— skip over separator
    
theScanner’s scanString:toStr intoString:(missing value)
    
    
anArray’s addObject:theValue
  end repeat
  
  
return anArray as list
end parseStrFromTo

on returnNumberOnly(aStr)
  set anNSString to current application’s NSString’s stringWithString:aStr
  
set anNSString to anNSString’s stringByReplacingOccurrencesOfString:"[^0-9]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, anNSString’s |length|()}
  
return anNSString as text
end returnNumberOnly

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ディスク使用状況を取得

Posted on 3月 9, 2018 by Takaaki Naganoya
AppleScript名:ディスク使用状況を取得
— Created 2017-12-17 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set dRes to diskUsage() of me
–> {readSector:8557760, readSize:"152G", writeSecotr:2601227, writeSize:"100G"}

on diskUsage()
  set dRes to (do shell script "top -l 1 | head -10 | grep ’Disks:’")
  
set dList to words of dRes
  
set readSectorNum to (contents of item 2 of dList) as integer
  
set readSizeNum to contents of item 3 of dList
  
set writeSectorNum to (contents of item 5 of dList) as integer
  
set writeSizeNum to contents of item 6 of dList
  
return {readSector:readSectorNum, readSize:readSizeNum, writeSecotr:writeSectorNum, writeSize:writeSizeNum}
end diskUsage

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ネットワーク使用状況を取得

Posted on 3月 9, 2018 by Takaaki Naganoya
AppleScript名:ネットワーク使用状況を取得
— Created 2017-12-17 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set nRes to networkUsage() of me
–> {inPacket:4904085, inSize:"5444M", outPacket:3426539, outSize:"396M"}

on networkUsage()
  set nRes to (do shell script "top -l 1 | head -10 | grep ’Networks: packets:’")
  
set nList to words of nRes
  
set inPackNum to (contents of item 3 of nList) as integer
  
set inSizeNum to (contents of item 4 of nList)
  
set outPackNum to (contents of item 6 of nList) as integer
  
set outSizeNum to (contents of item 7 of nList)
  
return {inPacket:inPackNum, inSize:inSizeNum, outPacket:outPackNum, outSize:outSizeNum}
end networkUsage

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

get battery info v2

Posted on 3月 9, 2018 by Takaaki Naganoya

バッテリー関連の情報を取得するAppleScriptです。

ioregコマンドなどでハードウェア周りの情報を取得する方法は昔から知られており、有益な情報を利用できます。

本ScriptはCocoaの機能も使っておらず、割と古めな構造のものですが、安定して動作しているので使い続けています。

もともと、本Scriptのファイル名は「バッテリ情報を取得.scpt」というものでしたが、「バッテリ情報を取得 v2.scpt」にFinder上でリネームしようとしたら、「ファイル名が長すぎるか、句読点を含まないファイル名に変更してくれ」というエラーをmacOS 10.12および10.13のFinderが出力して、仕方なく英語のファイル名にリネームしました。

# 10.14.6でも10.15.1でも発生しています

macOSのどこのバージョンだかわからないのですが、おそらくファイル名の入力時に001Dのような不可視キャラクタが混入し、Finder上でリネームできなくなるようです。日本語環境でのみ発生する問題と思われます。

AppleScript名:get battery info v2
set bInfo to getBatteryInfo() of batteryKit
–> {CurrentCapacity:5129, MaxCapacity:5265, DesignCapacity:8460, CycleCount:478}

script batteryKit
  on getBatteryInfo()
    –ハードウェアの識別文字列を取得
    
set machineType to do shell script "sysctl -n hw.model"
    
    
–MacBook Proを検出したら、あるいは結果にMacBookの文字列が入っていなかったら終了
    
if machineType does not contain "MacBook" then
      return {CurrentCapacity:0, MaxCapacity:0, DesignCapacity:0}
    end if
    
    
–MacBookだけ処理続行
    
    
–ハードウェア情報を取得
    
set batCom to "ioreg -p IOService -n AppleSmartBattery -w 0"
    
set a to do shell script batCom
    
set aList to every paragraph of a
    
    
set itemCount to 1
    
set hitF to false
    
repeat with i in aList
      set j to contents of i
      
if j contains "AppleSmartBattery <class AppleSmartBattery" then
        set resList to items (itemCount + 2) thru (itemCount + 29) of aList
        
set hitF to true
        
exit repeat
      end if
      
set itemCount to itemCount + 1
    end repeat
    
if hitF = false then return
    
    
    
set findAttrList to {"CurrentCapacity", "MaxCapacity", "DesignCapacity", "CycleCount"}
    
set hitList to {}
    
repeat with i in findAttrList
      set j to string id 34 & contents of i & string id 34
      
      
repeat with ii in resList
        set jj to contents of ii
        
if jj contains j then
          set the end of hitList to jj
          
exit repeat
        end if
      end repeat
    end repeat
    
    
    
–現在のバッテリーの容量を取得
    
set curCap to parseAfterSpecifiedChar("=", contents of item 1 of hitList) of me
    
set curCap to curCap as number
    
    
–バッテリーの最大容量を取得
    
set maxCap to parseAfterSpecifiedChar("=", contents of item 2 of hitList) of me
    
set maxCap to maxCap as number
    
    
–バッテリーの最大容量を取得
    
set designCap to parseAfterSpecifiedChar("=", contents of item 3 of hitList) of me
    
set designCap to designCap as number
    
    
–バッテリーの充放電回数を取得
    
set cCount to parseAfterSpecifiedChar("=", contents of item 4 of hitList) of me
    
set cCount to cCount as number
    
    
return {CurrentCapacity:curCap, MaxCapacity:maxCap, DesignCapacity:designCap, CycleCount:cCount}
    
  end getBatteryInfo
  
  
  
–対象文字列(aData)の中で、aCharの文字以降を取得
  
on parseAfterSpecifiedChar(aChar, aData)
    set aPos to offset of aChar in aData
    
set resText to text (aPos + (length of aChar)) thru -1 of aData
    
return resText
  end parseAfterSpecifiedChar
end script

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定アプリケーションのヘルプブック内の指定アンカーを表示する

Posted on 3月 8, 2018 by Takaaki Naganoya

指定名称のアプリケーションのヘルプブック内で指定アンカーを表示するAppleScriptです。

HelpBookを表示するOS標準搭載アプリケーション「HelpViewer」は一応AppleScript対応のスクリプタブルなアプリケーションなので、AppleScriptからコントロールできるのですが、経験上あまり信頼性がない(コマンドを無視して、表示しないことがある)ので、Cocoa経由でアンカー指定表示を行わせてみました。

Cocoa経由でもすぐに応答は返ってこないのですが、(HelpViewerの起動を含めて)数秒待たされて結果が表示される感じです。

HelpBookは、いわば「フローティング表示する、おそいWebブラウザ」で、かつてはWebコンテンツ内からAppleScriptの実行も指定できたため、一時期「Mac OS Xで有名なセキュリティーホール」として注目を集めました。URLイベント経由でScriptの実行を指定できてしまうとか、便利ではあったもののセキュリティーホールと言われればセキュリティホールです(注:すぐにふさがれました & この前後からローカルでのURLプロトコルの監視がきつくなりました)。

AppleScript名:指定アプリケーションのヘルプブック内の指定アンカーを表示する
— Created 2017-04-18 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set anAppName to "Script Editor"
set aTargAnchor to "scpedt1126" —-https://help.apple.com/scripteditor/mac/10.12/index.html?localePath=ja.lproj#/scpedt1126
set hRes to openHelpBook(anAppName, aTargAnchor) of me

–指定アプリケーションのヘルプブックで、指定アンカーを表示する
on openHelpBook(anAppName, aTargAnchor)
  set locBookName to getHelpBook(anAppName) of me
  
if locBookName = false then return false
  
current application’s NSHelpManager’s sharedHelpManager()’s openHelpAnchor:aTargAnchor inBook:locBookName
end openHelpBook

–指定アプリケーションのヘルプブック名称を取得する
on getHelpBook(anAppName)
  set aWorkspace to current application’s NSWorkspace’s sharedWorkspace()
  
set appPath to aWorkspace’s fullPathForApplication:anAppName
  
if appPath is equal to missing value then return false
  
  
set locBookName to (current application’s NSBundle’s bundleWithPath:appPath)’s objectForInfoDictionaryKey:"CFBundleHelpBookName"
  
if locBookName is equal to missing value then return false
  
–> "com.apple.ScriptEditor.help"
  
return locBookName
end getHelpBook

★Click Here to Open This Script 

AppleScript名:help_sample
tell application "HelpViewer"
  activate
  
try
    lookup anchor "scpedt1126" in book "com.apple.ScriptEditor.help"
  end try
end tell

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy HelpViewer | Leave a comment

指定アプリケーションのヘルプブック内で指定キーワードを検索する

Posted on 3月 8, 2018 by Takaaki Naganoya

指定名称のアプリケーションのヘルプブック内で指定キーワードを検索するAppleScriptです。

HelpBookを表示するOS標準搭載アプリケーション「HelpViewer」は一応AppleScript対応のスクリプタブルなアプリケーションなので、AppleScriptからコントロールできるのですが、経験上あまり信頼性がない(コマンドを無視して、表示しないことがある)ので、Cocoa経由で検索・表示を行わせてみました。

Cocoa経由でもすぐに応答は返ってこないのですが、(HelpViewerの起動を含めて)数秒待たされて結果が表示される感じです。

AppleScript名:指定アプリケーションのヘルプブック内で指定キーワードを検索する
— Created 2017-04-18 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set anAppName to "Script Editor"
set aTargString to "用語説明" –"Script Dictionary" in Japanese
set hRes to searchHelpBook(anAppName, aTargString) of me

–指定アプリケーションのヘルプブックで、指定アンカーを表示する
on searchHelpBook(anAppName, aTargString)
  set locBookName to getHelpBook(anAppName) of me
  
if locBookName = false then return false
  
current application’s NSHelpManager’s sharedHelpManager()’s findString:aTargString inBook:locBookName
end searchHelpBook

–指定アプリケーションのヘルプブック名称を取得する
on getHelpBook(anAppName)
  set aWorkspace to current application’s NSWorkspace’s sharedWorkspace()
  
set appPath to aWorkspace’s fullPathForApplication:anAppName
  
if appPath is equal to missing value then return false
  
  
set locBookName to (current application’s NSBundle’s bundleWithPath:appPath)’s objectForInfoDictionaryKey:"CFBundleHelpBookName"
  
if locBookName is equal to missing value then return false
  
–> "com.apple.ScriptEditor.help"
  
return locBookName
end getHelpBook

★Click Here to Open This Script 

▼AppleScript経由でHelpViewerにコマンドを発行してキーワード検索させたところ。検索が実行されない。

AppleScript名:HelpViewerで検索する?(コマンドを実行しても検索結果が表示されない)
tell application "HelpViewer"
  activate
  
search looking for "用語説明"
end tell

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy HelpViewer | Leave a comment

ASOCでハンドラの間接呼び出し v3b

Posted on 3月 7, 2018 by Takaaki Naganoya

パラメータ付きのハンドラの存在確認を行い、間接的に呼び出しを行うAppleScriptです。

ハンドラの間接呼び出しについては、最近研究を重ねておりました。過去の事例をまとめ、ノウハウの方向性を分析。

過去の事例はPure AppleScriptについてのものであり、今日Cocoaの機能を呼び出すAppleScriptObjCの環境で使えないものを紹介しても仕方がありません。もはや、Cocoaの機能呼び出しとAppleScriptは不可分のレベルです。

そんなわけで、AppleScriptObjC環境でのハンドラの間接呼び出しについて試行錯誤と検討を重ね、ハンドラの存在確認とパラメータつきハンドラの間接呼び出しができるようになってきました。

AppleScript名:ASOCでハンドラの間接呼び出し v3b
–By @badcharanさん
use framework "Foundation"
use scripting additions

set nameOfTargetHandler to "aHandler:"
set aParamObj to {1, 2, 3}

set existsHandler to (me’s respondsToSelector:nameOfTargetHandler) as boolean
if existsHandler = true then
  set aRes to (my performSelector:nameOfTargetHandler withObject:aParamObj) as list of string or string
else
  error "The Handler \"" & nameOfTargetHandler & "\" is not present in this Script."
end if

return aRes

on x()
  return "hello"
end x

on aHandler:(aParam as list of string or string)
  return length of aParam
end aHandler:

★Click Here to Open This Script 

「as anything」がmacOS 10.13までは「as list ot list of string」などと解釈されていましたが、macOS 10.14からは「as anything」(Script Editor)あるいは「as any」(Script Debugger)と解釈されるようになりました。このあたり、足並み揃えてほしいところですが……

とりあえず、macOS 10.14移行の環境(Script Editor)で動く(正しく解釈される)ように少し書き換えてみました。

AppleScript名:ASOCでハンドラの間接呼び出し v3c.scpt
–By @badcharanさん
use framework "Foundation"
use scripting additions

set nameOfTargetHandler to "aHandler:"
set aParamObj to {1, 2, 3}

set existsHandler to (me’s respondsToSelector:nameOfTargetHandler) as boolean
if existsHandler = true then
  set aRes to (my performSelector:nameOfTargetHandler withObject:aParamObj) as anything –Script Editor, "any" for Script Debugger
else
  error "The Handler \"" & nameOfTargetHandler & "\" is not present in this Script."
end if

return aRes

on x()
  return "hello"
end x

on aHandler:(aParam as anything) –Script Editor, "any" for Script Debugger
  return length of aParam
end aHandler:

★Click Here to Open This Script 

Posted in 未分類 | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

AppleScriptの構文色分けカラーフォーマットをplistから読み込む

Posted on 3月 7, 2018 by Takaaki Naganoya

AppleScriptの構文色分けフォーマットをplistから読み込むAppleScriptです。

ただし、本Scriptで取得した色情報はスクリプトエディタ上で設定した内容と若干RGB値が異なるため、色情報をもとに構文要素を判定するような処理に本Scriptをそのまま用いることは推奨しません。

AppleScript名:AppleScriptの構文色分けカラーフォーマットをplistから読み込む
— Created 2013-11-11 by Shane Stanley
— Changed 2014-12-14 by Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set cList to getAppleScriptSourceColors() of me
–> {​​​​​{​​​​​​​redValue:37265, ​​​​​​​greenValue:10280, ​​​​​​​blueValue:37008, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:15672, ​​​​​​​greenValue:3071, ​​​​​​​blueValue:15832, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:3598, ​​​​​​​greenValue:15934, ​​​​​​​blueValue:64507, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:30840, ​​​​​​​greenValue:13364, ​​​​​​​blueValue:52171, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:64764, ​​​​​​​greenValue:10794, ​​​​​​​blueValue:7196, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:0, ​​​​​​​greenValue:0, ​​​​​​​blueValue:0, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:37265, ​​​​​​​greenValue:21074, ​​​​​​​blueValue:4369, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:0, ​​​​​​​greenValue:0, ​​​​​​​blueValue:0, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:10023, ​​​​​​​greenValue:51657, ​​​​​​​blueValue:51657, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:3855, ​​​​​​​greenValue:15934, ​​​​​​​blueValue:64507, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:7967, ​​​​​​​greenValue:46774, ​​​​​​​blueValue:64764, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:33153, ​​​​​​​greenValue:14906, ​​​​​​​blueValue:55769, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:23901, ​​​​​​​greenValue:13878, ​​​​​​​blueValue:37522, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:47484, ​​​​​​​greenValue:3164, ​​​​​​​blueValue:32926, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:6491, ​​​​​​​greenValue:47213, ​​​​​​​blueValue:32320, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:40001, ​​​​​​​greenValue:37149, ​​​​​​​blueValue:1331, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:20379, ​​​​​​​greenValue:0, ​​​​​​​blueValue:35059, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:4539, ​​​​​​​greenValue:35536, ​​​​​​​blueValue:35798, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}​​​}

–AppleScriptの構文色分けのカラー値をRGBで取得する
on getAppleScriptSourceColors()
  
  
— get the info as a dictionary
  
set thePath to current application’s NSString’s stringWithString:"~/Library/Preferences/com.apple.applescript.plist"
  
set thePath to thePath’s stringByExpandingTildeInPath()
  
set theInfo to current application’s NSDictionary’s dictionaryWithContentsOfFile:thePath
  
  
— extract relevant part and loop through
  
set theArray to (theInfo’s valueForKey:"AppleScriptSourceAttributes") as list
  
  
set colList to {}
  
  
repeat with i from 1 to count of theArray
    set anEntry to item i of theArray
    
log anEntry
    
    
set colorData to NSColor of anEntry
    
set theColor to (current application’s NSUnarchiver’s unarchiveObjectWithData:colorData)
    
    
set {rVal, gVal, bVal} to retColListFromNSColor(theColor, 65535) of me
    
    
set fontData to NSFont of anEntry
    
set theFont to (current application’s NSUnarchiver’s unarchiveObjectWithData:fontData)
    
    
set aFontName to theFont’s displayName() as text
    
set aFontSize to theFont’s pointSize()
    
    
set aColRec to {redValue:rVal, greenValue:gVal, blueValue:bVal, fontName:aFontName, fontSize:aFontSize}
    
    
set the end of colList to aColRec
  end repeat
  
  
return colList
end getAppleScriptSourceColors

–NSColorからRGBの値を取り出す
on retColListFromNSColor(aCol, aMAX as integer)
  set aRed to round ((aCol’s redComponent()) * aMAX) rounding as taught in school
  
set aGreen to round ((aCol’s greenComponent()) * aMAX) rounding as taught in school
  
set aBlue to round ((aCol’s blueComponent()) * aMAX) rounding as taught in school
  
  
if aRed > aMAX then set aRed to aMAX
  
if aGreen > aMAX then set aGreen to aMAX
  
if aBlue > aMAX then set aBlue to aMAX
  
  
return {aRed, aGreen, aBlue}
end retColListFromNSColor

★Click Here to Open This Script 

Posted in Color OSA System | Tagged 10.11savvy 10.12savvy 10.13savvy Script Editor | 3 Comments

指定パスのAppleScript書類がコンパイル済みかどうかチェック

Posted on 3月 7, 2018 by Takaaki Naganoya
AppleScript名:指定パスのAppleScript書類がコンパイル済みかどうかチェック
— Created 2014-12-16 by Takaaki Naganoya
— 2014 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "OSAKit"

property |NSURL| : a reference to current application’s |NSURL|
property OSAScript : a reference to current application’s OSAScript

–指定AppleScriptがコンパイルずみ(中間コードへの翻訳の意)かどうかをしらべる
set a to (choose file of type {"com.apple.applescript.script-bundle", "com.apple.applescript.script", "com.apple.applescript.text"})
set asRes to chkAScompiled(a) as list of string or string
–> true or false

–指定のAppleScriptファイルがコンパイル(構文確認+中間言語化)ずみかどうかを取得する
on chkAScompiled(anAlias as {alias, string})
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of anAlias)
  
set asO to OSAScript’s alloc()’s initWithContentsOfURL:aURL |error|:(missing value)
  
  
try
    set compF to asO’s isCompiled() as boolean
    
return compF
  on error
    return false
  end try
end chkAScompiled

★Click Here to Open This Script 

Posted in Color OSA System | Tagged 10.11savvy 10.12savvy 10.13savvy Script Editor | Leave a comment

nameを指定してOSA言語のインスタンスを生成する

Posted on 3月 6, 2018 by Takaaki Naganoya

name(名称)を指定してOSA言語のインスタンスを生成するテストを行うAppleScriptです。

このあたりの話は、スクリプトエディタ上では直接取得できますし、コマンドラインからだとosalangコマンドを実行すれば名称一覧を取得できます。Cocoa経由でどの程度の情報が取得できるのか、ちょっと試してながらく放置したままになっていました。

再度、OSAKit系の情報を探してみても……見当たらない(ーー;

以前にAppleEvent Managerのドキュメントをまるごとオフラインにしていた前科があるので、担当に「(オフラインになっていて)見えないんだけど?」と確認したところ………

 「何が見えないんだ? 最初からそんなもんないぞ。これまでにドキュメントを作ったこともない」

と言われる始末。余計悪いわ(ーー;;;

というわけで、Web上にドキュメントが掲載されていないOSAKit系の情報については、Xcode上から、以下のように操作してヘッダーファイルの内容を確認することが必要なようです。

AppleScript名:nameを指定してOSA言語のインスタンスを生成する
— Created 2018-03-05 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "OSAKit"

property OSALanguage : a reference to current application’s OSALanguage
property OSALanguageInstance : a reference to current application’s OSALanguageInstance

set anOSALanguageInstance to OSALanguageInstance’s languageInstanceWithLanguage:(OSALanguage’s defaultLanguage())
set aLanguage to anOSALanguageInstance’s |language|()’s |name|() as string
–> "AppleScript"

set bLanguage to OSALanguage’s languageForName:"AppleScript"
set bName to bLanguage’s |name|() as string
–> "AppleScript"

set cLanguage to OSALanguage’s languageForName:"JavaScript"
set cName to cLanguage’s |name|() as string
–> "JavaScript"

set langArray to (OSALanguage’s availableLanguages()’s valueForKeyPath:"name") as list
–> {"AppleScript", "JavaScript"}

★Click Here to Open This Script 

Posted in Color OSA System | Tagged 10.11savvy 10.12savvy 10.13savvy Script Editor | Leave a comment

Script Editorをコントロールして各構文要素の色情報を取得する v5

Posted on 3月 5, 2018 by Takaaki Naganoya

Script Editorをコントロールして、AppleScriptの各構文要素の色情報を取得するAppleScriptです。

AppleScriptの構文要素の色分けを取得するのに、当初はplistファイルから読み込んでいたのですが、途中から(Mac OS X 10.5あたり?)plistファイルのフォーマットがテキスト形式からバイナリ形式に変更になり、AppleScriptから読み込んでも判定できない内容になりました(Cocoaの機能を使うと読み取れるのですが)。

そこで、「プログラム的には意味はないが、対象の構文要素が入っているテキスト」でAppleScriptを新規ドキュメントを作成してコンパイル(構文確認)を実行。新規ドキュメントからリッチテキストとして書式情報を取得し、想定した文字の位置から指定構文要素に対応する色情報を取得します。

plistの保存形式が途中で変更されたのとは別に、書式つきテキスト(attribute runs)の挙動もOSバージョンによって微妙に変わってきました。

同じデータを与えても、書式の区切りが微妙に変わって、書式(色)情報を固定の箇所から読み取っていてはそのようなOSバージョン変更に伴う挙動の微妙な変更に対応し切れませんでした。そのため、文字列をサーチして毎回動的にデータ位置を検出するように書き換えた経緯があります。

本ルーチンは、変数名のリネーム用に作成したので構文要素確認用のダミーテキストは最低限のものだけを含んでいますが、その気になればすべての構文要素の色情報を取得可能です。

これとは別に、Cocoaの機能を用いてplistから構文書式情報を取得するAppleScriptも存在するものの、計算して微妙に色情報が合わないので、9年前に作成した本ルーチンを使い続けています(当時)。

→ さすがに重要なルーチンなので、Cocoa系の機能を使って処理するように書き換えました。いまはCocoa系ルーチンを使っています

AppleScript名:Script Editorをコントロールして各構文要素の色情報を取得する v5
— Created 2009-06-01 by Takaaki Naganoya
— 2009-2018 Piyomaru Software

set scList to getRexicalColorOfScriptEditor() of me
–> {{32053, 4213, 32213}, {15672, 3071, 15831}, {2841, 6963, 64125}, {8259, 42547, 64473}, {0, 0, 0}, {32202, 16452, 3889}}
–色書式データ。先頭から順番に、、、
–新規テキスト, 演算子など, スクリプティング予約語, コマンド名, 値(数値、データ), 変数およびサブルーチン名

–スクリプトエディタの各構文要素の指定色を返す
–v5の変更点:Leopard以降のStyle runsの挙動変化(スペースを分離する/しない)に対応し、動的にサンプル文を走査するようにした
–v4の変更点:構文要素検出時のテンポラリウィンドウ作成時にScript Editorを隠す
–v3の変更点:重複時のエラー検出を追加
on getRexicalColorOfScriptEditor()
  set aRes to setVisibleOfSpecifiedProcess("Script Editor", false) of me
  
  
set rexList to {"+", "set", "application", "Comment", "1", "a"} –文中から検索するテキスト要素
  
set colList to {} –色情報を入れるリスト
  
  
  
tell application "Script Editor"
    
    
set aDoc to make new document
    
tell front document
      set aName to name
      
–end tell
      
      
–tell document aName
      
–未コンパイル時のテキストを取得
      
set contents to "aaaaa"
      
set rexItem1 to (color of attribute runs)
      
set rexItem1 to contents of (item 1 of rexItem1)
      
      
set colList to {rexItem1}
      
      
      
–各種構文要素を含む文字を入れる
      
set contents to "1 + 1
set a to \"abc\"
tell application \"Finder\"
end tell
–Comment
"

      –追加する場合には、テキストを後ろに追加すること
      
      
try
        compile
      on error
        close without saving
        
return false
      end try
      
      
set rex1 to attribute runs
      
set rex2 to color of attribute runs
      
      
repeat with i in rexList
        set j to contents of i
        
set rC to 1
        
repeat with ii in rex1
          set jj to contents of ii
          
set jj to replaceText(jj, " ", "") of me –スペースを削除する
          
if j = jj then
            set the end of colList to contents of item rC of rex2
            
exit repeat –抜けていた
          end if
          
set rC to rC + 1
        end repeat
      end repeat
      
      
close without saving
    end tell
    
  end tell
  
  
–Script Editorの再表示
  
set aRes to setVisibleOfSpecifiedProcess("Script Editor", true) of me
  
  
–要素の重複検出
  
set aRes to detectDuplicationSimple(colList) of me
  
if aRes = false then
    return false
  else
    return colList
  end if
  
end getRexicalColorOfScriptEditor

–リスト中の重複検出
on detectDuplicationSimple(cList)
  copy cList to ccList
  
  
set j to length of ccList
  
  
repeat with i from 2 to j
    set first_item to item 1 of ccList
    
set ccList to rest of ccList
    
if first_item is in ccList then
      return false
    end if
  end repeat
  
  
return true
end detectDuplicationSimple

–指定プロセスの可視/不可視切り替え
on setVisibleOfSpecifiedProcess(aProc, aBoolean)
  tell application "System Events"
    if exists process aProc then
      set visible of process aProc to aBoolean
      
set resF to true
    else
      set resF to false
    end if
  end tell
  
return resF
end setVisibleOfSpecifiedProcess

–任意のデータから特定の文字列を置換
on replaceText(origData, origText, repText)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to {origText}
  
set origData to text items of origData
  
set AppleScript’s text item delimiters to {repText}
  
set origData to origData as text
  
set AppleScript’s text item delimiters to curDelim
  
return origData
end replaceText

★Click Here to Open This Script 

Posted in Color OSA System | Tagged 10.11savvy 10.12savvy 10.13savvy Script Editor | 1 Comment

Script Debugger 7が登場。試用期間が切れても機能制限つきLiteモードで動作

Posted on 3月 5, 2018 by Takaaki Naganoya

Late Night SoftwareからScript Debuggerの最新バージョン、Script Debugger 7がリリースされました。macOS 10.11以降のOSが対象です。価格は99ドルで、ボリュームディスカウントも用意されています。

Script DebuggerはClassic Mac OSの時代からサードパーティのAppleScript統合開発環境として続いてきたソフトウェアです。AppleScriptのプログラムの開発、実行およびデバッグのための強力な機能を提供します。

v6:AppleScriptObjCに対応
v5:エディタ部分をフル書き換え


▲Script Debugger 7


▲Script Debugger 3 + Classic Mac OS 8.6(SheepShaver)

AppleScript統合開発環境の決定版

「デバッガ」の名のとおり、AppleScriptに対して変数内容のリアルタイムモニタリング、ブレークポイントの設定、ステップ実行などの機能を提供します。

さらに、対象アプリケーションの各オブジェクトの属性値情報をリアルタイムでモニタリングする機能を提供しており、初見のGUIアプリケーションであっても、Script Debuggerのこの機能を用いれば、とくに迷うことなく目的の属性値情報にたどり着くことが可能です。

初心者にこそ使ってほしいソフトウェア

こうした機能は、(上級者はもちろんのこと)初心者にこそ有用なもので、自分もたまたまAppleScript入門時にScript Debuggerに出会い(バージョン2か3の頃に)、たいへんに助けられました。FileMaker Proのデータベースからカテゴリごとにデータを抽出してHTMLコンテンツを生成するAppleScriptを、AppleScriptを使い始めて1週間ぐらいで作れるようになったのは、(海外のMailing Listで教えてもらいつつ)Script Debuggerがあったからです。

名前が仰々しいので「むずかしいソフトウェア」と思われがちで、それがScript入門者にとってもメーカーにとってもたいへんに不幸なことだと思っていました。初心者が使うと便利でわかりやすいのに、初心者が「むずかしそう」と敬遠してしまうのは、残念なことです。

一般的なレベルの「AppleScript入門者」にScript Debuggerの機能を2〜3週間で理解しろといっても無理なようなので、もう少し「何か」があれば入門者もより理解が深まり、Script Debuggerの恩恵を授かることができるのに、と思っておりました。

macOS 10.14以降で、サードパーティFramework呼び出しScriptに必須

Apple純正のCocoa Frameworkにくわえ、サードパーティのFrameworkをAppleScriptから呼び出して利用することが、macOS 10.10以降で一般的になってきました、ところが、macOS 10.14以降ではmacOSのセキュリティ機能が強化され、ユーザーフォルダに存在するFrameworkを呼び出して実行することができなくなりました(SIPを解除するとこの制限はなくなります)。

Script Debuggerは、このmacOS 10.14以降の環境で、github上で公開されているオープンソースのFrameworkをビルドして呼び出したいような場合に、SIPを解除せずともFramework呼び出しが行える環境です。

また、macOS 10.15でAppleScriptアプレットにFrameworkを同梱して呼び出すようなやり方がSIPによって禁止されましたが、これもScript Debuggerのアプレット書き出し(Enhanced)を利用することで、Frameworkを同梱して実行できるAppleScriptアプレットを作成できます。

3週間の試用期間を過ぎてもLiteモードで機能制限版として使用可能

そこに、今回のScript Debugger 7で「Liteモード」が用意されました。使用期限が切れても、機能制限版のScript Debuggerとして動作するモードです。このLiteモードの状態でもApple純正のスクリプトエディタよりも高機能です(AppleScript書類の書式にアクセスできない以外は)。

ちなみに、Xcode上でGUIベースのアプリケーションをAppleScriptで組もうとしたときに、Script Debuggerなどのまともな外部AppleScriptエディタは必須のものです。

Posted in How To Tools | Tagged Script Debugger | Leave a comment

旅行系サイトごちゃまぜフィード

Posted on 3月 3, 2018 by Takaaki Naganoya

ApitoreのREST API「旅行系サイト ごちゃまぜフィード」を呼び出して、さまざまな旅行系サイトのNews Feedを一括で取得するAppleScriptです。

# Apitoreは2019年5月31日をもってサービスを終了

「旅行系サイト ごちゃまぜフィード」は、30分に1回の頻度でRSSの更新を確認にいきます。REST APIで最新情報が取得できるオンラインクローラーです。

本AppleScript利用のためには、Apitoreにサインアップしてアカウントを作成し、新規プロジェクトを作成(Test AppleScriptとか)。そこに、本APIを利用できるように登録し、「アクセストークン」を取得する必要があります。

アクセストークンを取得せずに掲載状態のまま本AppleScriptを実行してもエラーになります。

取得したアクセストークンを本AppleScript中のretAccessToken()ハンドラ内に記載し、実行してください。

AppleScript名:旅行系サイトごちゃまぜフィード
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set allFeeds to {}

repeat with i from 1 to 100
  set {aRes, maxNum} to getAFeeds(i) of me
  
  
if aRes = false then exit repeat
  
set maxNum to maxNum as number
  
set allFeeds to allFeeds & aRes
  
if (maxNum div 10) ≤ i then
    exit repeat
  end if
end repeat

return allFeeds
–>  
(*
{​​​​​{​​​​​​​author:"", ​​​​​​​sourceTitle:"Compathy Magazine(コンパシーマガジン)", ​​​​​​​title:"【東京美食】 2017壽司必吃!東京壽司推薦攻略TOP18,日式壽司禮儀超強指南", ​​​​​​​link:"https://www.compathy.net/magazine/2017/03/29/tokyosushitop18/", ​​​​​​​pubDate:1.490783697E+12, ​​​​​​​description:"", ​​​​​​​sourceLink:"https://www.compathy.net/magazine"​​​​​},
*)

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/36/feeds/travel"
  
set accessToken to retAccessToken() of me —Access Token
  
set aRec to {access_token:accessToken, page:(aNum as string)}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESCode to (responseCode of aRes) as integer
  
if aRESCode is not equal to 200 then return {false, false}
  
  
set aRESTres to (json of aRes) as record
  
  
set sentiRes to entries of aRESTres
  
set allNum to num of aRESTres
  
  
return {sentiRes, allNum}
end getAFeeds

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  
  
set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"Test AppleScript (gzip)" forHTTPHeaderField:"User-Agent"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxXXXxxX-XxXx-XXXX-xXXX-XXxXXxxXxxXx" –API Tore Access Token
end retAccessToken

★Click Here to Open This Script 

Posted in JSON Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

証券情報サイト ごちゃまぜフィード

Posted on 3月 3, 2018 by Takaaki Naganoya

ApitoreのREST API「証券情報サイト ごちゃまぜフィード」を呼び出して、さまざまな証券情報サイトのNews Feedを一括で取得するAppleScriptです。

# Apitoreは2019年5月31日をもってサービスを終了

「証券情報サイト ごちゃまぜフィード」は、30分に1回の頻度でRSSの更新を確認にいきます。REST APIで最新情報が取得できるオンラインクローラーです。

本AppleScript利用のためには、Apitoreにサインアップしてアカウントを作成し、新規プロジェクトを作成(Test AppleScriptとか)。そこに、本APIを利用できるように登録し、「アクセストークン」を取得する必要があります。

アクセストークンを取得せずに掲載状態のまま本AppleScriptを実行してもエラーになります。

取得したアクセストークンを本AppleScript中のretAccessToken()ハンドラ内に記載し、実行してください。

AppleScript名:証券情報サイト ごちゃまぜフィード
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set allFeeds to {}

repeat with i from 1 to 100
  set {aRes, maxNum} to getAFeeds(i) of me
  
  
if aRes = false then exit repeat
  
set maxNum to maxNum as number
  
set allFeeds to allFeeds & aRes
  
if (maxNum div 10) ≤ i then
    exit repeat
  end if
end repeat

return allFeeds
–>  
(*
{​​​​​{​​​​​​​author:"日本インタビュ新聞 Media-IR", ​​​​​​​sourceTitle:"日本インタビュ新聞 株式投資情報", ​​​​​​​title:"アライドレシスホールディングスは「継続企業の前提に関する注記」の記載を解消", ​​​​​​​link:"http://kabu-ir.com/article/448533521.html", ​​​​​​​pubDate:1.490787369E+12, ​​​​​​​description:"■返済期日が延長され、当面の資金繰りの安定化が図られる見込み アライドテレシスホールディングス<6835>(東2)は29日、「継続企業の前提に関する注記」の記載を解消することを発表した。 同社グループは、平成28年12月期連結会計年度で営業利益5億72百万円、当期純利益1億11百万円を計上した。しかし、営業活動によるキャッシュフロー4億6百万円に対し、連結会計年度末における金融機関からの有利子負債残高が74億94百万円と多額であり、平成29年6月30日に期間満了となるシンジケ..", ​​​​​​​sourceLink:"http://kabu-ir.com/"​​​​​}, ​​​​​{​​​​​​​author:"日本インタビュ新聞 Media-IR", ​​​​​​​sourceTitle:"日本インタビュ新聞 株式投資情報", ​​​​​​​title:"ケイティケイは今17年8月期第2四半期と通期業績予想の利益面での上方修正を発表", ​​​​​​​
*)

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/31/feeds/certificate"
  
set accessToken to retAccessToken() of me —Access Token
  
set aRec to {access_token:accessToken, page:(aNum as string)}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESCode to (responseCode of aRes) as integer
  
if aRESCode is not equal to 200 then return {false, false}
  
  
set aRESTres to (json of aRes) as record
  
  
set sentiRes to entries of aRESTres
  
set allNum to num of aRESTres
  
log allNum
  
  
return {sentiRes, allNum}
end getAFeeds

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  
  
set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"Test AppleScript (gzip)" forHTTPHeaderField:"User-Agent"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) –as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxXXXxxX-XxXx-XXXX-xXXX-XXxXXxxXxxXx" –API Tore Access Token
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ブログごちゃまぜフィード

Posted on 3月 3, 2018 by Takaaki Naganoya

ApitoreのREST API「ブログ ごちゃまぜフィード」を呼び出して、さまざまな各個人ブログのNews Feedを一括で取得するAppleScriptです。

# Apitoreは2019年5月31日をもってサービスを終了

「ブログ ごちゃまぜフィード」は、30分に1回の頻度でRSSの更新を確認にいきます。REST APIで最新情報が取得できるオンラインクローラーです。

本AppleScript利用のためには、Apitoreにサインアップしてアカウントを作成し、新規プロジェクトを作成(Test AppleScriptとか)。そこに、本APIを利用できるように登録し、「アクセストークン」を取得する必要があります。

アクセストークンを取得せずに掲載状態のまま本AppleScriptを実行してもエラーになります。

取得したアクセストークンを本AppleScript中のretAccessToken()ハンドラ内に記載し、実行してください。

AppleScript名:ブログごちゃまぜフィード
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set allFeeds to {}

repeat with i from 1 to 100
  set {aRes, maxNum} to getAFeeds(i) of me
  
  
if aRes = false then exit repeat
  
set maxNum to maxNum as number
  
set allFeeds to allFeeds & aRes
  
if (maxNum div 10) ≤ i then
    exit repeat
  end if
end repeat

return allFeeds
–>  
(*
{​​​​​{​​​​​​​author:"", ​​​​​​​sourceTitle:"毎日新聞 – ニュース速報(総合)", ​​​​​​​title:"那須雪崩:NHK、被害者写真誤り訂正し謝罪", ​​​​​​​link:"http://rss.rssad.jp/rss/artclk/ZLcY1bpa2mkX/98f49f50f6a89c6d7da908d2f7e604f3?ul=IRi._czqYe8fmPstnpk5g5TZSqz2eXK2XhK5Wl.vDmACS2n47wDHuHkQCrQkxmzyg1uf0aUsQxz8MCNU7hjXjz7r54NW", ​​​​​​​pubDate:1.490796812E+12, ​​​​​​​description:"<p><img border=\"0\" width=\"1\" height=\"1\" src=\"http://rss.rssad.jp/rss/artimg/ZLcY1bpa2mkX/98f49f50f6a89c6d7da908d2f7e604f3\"/></p>", ​​​​​​​sourceLink:"http://mainichi.jp"​​​​​},
*)

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/30/feeds/blog"
  
set accessToken to retAccessToken() of me —Access Token
  
set aRec to {access_token:accessToken, page:(aNum as string)}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESCode to (responseCode of aRes) as integer
  
if aRESCode is not equal to 200 then return {false, false}
  
  
set aRESTres to (json of aRes) as record
  
  
set sentiRes to entries of aRESTres
  
set allNum to num of aRESTres
  
log allNum
  
  
return {sentiRes, allNum}
end getAFeeds

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  
  
set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"Test AppleScript (gzip)" forHTTPHeaderField:"User-Agent"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxXXXxxX-XxXx-XXXX-xXXX-XXxXXxxXxxXx" –API Tore Access Token
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

デザイン系 ごちゃまぜフィード

Posted on 3月 3, 2018 by Takaaki Naganoya

ApitoreのREST API「デザイン系 ごちゃまぜフィード」を呼び出して、さまざまなオシャレなインテリアとかデザインとかを扱うサイトが提供しているNews Feedを一括で取得するAppleScriptです。

# Apitoreは2019年5月31日をもってサービスを終了

「デザイン系 ごちゃまぜフィード」は、30分に1回の頻度でRSSの更新を確認にいきます。REST APIで最新情報が取得できるオンラインクローラーです。巡回先RSSは以下のとおりです。

・Gurafiku
・HITSPAPER
・K’conf Blog
・CASA BRUTUS
・100%LiFE

本AppleScript利用のためには、Apitoreにサインアップしてアカウントを作成し、新規プロジェクトを作成(Test AppleScriptとか)。そこに、本APIを利用できるように登録し、「アクセストークン」を取得する必要があります。

アクセストークンを取得せずに掲載状態のまま本AppleScriptを実行してもエラーになります。

取得したアクセストークンを本AppleScript中のretAccessToken()ハンドラ内に記載し、実行してください。

AppleScript名:デザイン系 ごちゃまぜフィード
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set allFeeds to {}

repeat with i from 1 to 100
  set {aRes, maxNum} to getAFeeds(i) of me
  
  
if aRes = false then exit repeat
  
set maxNum to maxNum as number
  
set allFeeds to allFeeds & aRes
  
if (maxNum div 10) ≤ i then
    exit repeat
  end if
end repeat

return allFeeds
–>  
(*
{​​​​​{​​​​​​​author:"日本インタビュ新聞 Media-IR", ​​​​​​​sourceTitle:"日本インタビュ新聞 株式投資情報", ​​​​​​​title:"アライドレシスホールディングスは「継続企業の前提に関する注記」の記載を解消", ​​​​​​​link:"http://kabu-ir.com/article/448533521.html", ​​​​​​​pubDate:1.490787369E+12, ​​​​​​​description:"■返済期日が延長され、当面の資金繰りの安定化が図られる見込み アライドテレシスホールディングス<6835>(東2)は29日、「継続企業の前提に関する注記」の記載を解消することを発表した。 同社グループは、平成28年12月期連結会計年度で営業利益5億72百万円、当期純利益1億11百万円を計上した。しかし、営業活動によるキャッシュフロー4億6百万円に対し、連結会計年度末における金融機関からの有利子負債残高が74億94百万円と多額であり、平成29年6月30日に期間満了となるシンジケ..", ​​​​​​​sourceLink:"http://kabu-ir.com/"​​​​​}, ​​​​​{​​​​​​​author:"日本インタビュ新聞 Media-IR", ​​​​​​​sourceTitle:"日本インタビュ新聞 株式投資情報", ​​​​​​​title:"ケイティケイは今17年8月期第2四半期と通期業績予想の利益面での上方修正を発表", ​​​​​​​
*)

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/32/feeds/design"
  
set accessToken to retAccessToken() of me —Access Token
  
set aRec to {access_token:accessToken, page:(aNum as string)}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESCode to (responseCode of aRes) as integer
  
if aRESCode is not equal to 200 then return {false, false}
  
  
set aRESTres to (json of aRes) as record
  
  
set sentiRes to entries of aRESTres
  
set allNum to num of aRESTres
  
log allNum
  
  
return {sentiRes, allNum}
end getAFeeds

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  
  
set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"Test AppleScript (gzip)" forHTTPHeaderField:"User-Agent"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxXXXxxX-XxXx-XXXX-xXXX-XXxXXxxXxxXx" –API Tore Access Token
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ゲーム情報サイト ごちゃまぜフィード

Posted on 3月 3, 2018 by Takaaki Naganoya

ApitoreのREST API「ゲーム情報サイト ごちゃまぜフィード」を呼び出して、さまざまなゲーム系サイトのNews Feedを一括で取得するAppleScriptです。

# Apitoreは2019年5月31日をもってサービスを終了

「ゲーム情報サイト ごちゃまぜフィード」は、30分に1回の頻度でRSSの更新を確認にいきます。REST APIで最新情報が取得できるオンラインクローラーです。以下のRSSをチェックしています。

・4Gamer.net 新着
・4Gamer.net 注目の記事のみ
・電撃オンライン
・doope!
・Game*Spark
・ゲームのはなし

本AppleScript利用のためには、Apitoreにサインアップしてアカウントを作成し、新規プロジェクトを作成(Test AppleScriptとか)。そこに、本APIを利用できるように登録し、「アクセストークン」を取得する必要があります。

アクセストークンを取得せずに掲載状態のまま本AppleScriptを実行してもエラーになります。

取得したアクセストークンを本AppleScript中のretAccessToken()ハンドラ内に記載し、実行してください。

AppleScript名:ゲーム情報サイト ごちゃまぜフィード
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set allFeeds to {}

repeat with i from 1 to 100
  set {aRes, maxNum} to getAFeeds(i) of me
  
  
if aRes = false then exit repeat
  
set maxNum to maxNum as number
  
set allFeeds to allFeeds & aRes
  
if (maxNum div 10) ≤ i then
    exit repeat
  end if
end repeat

return allFeeds
–>  
(*
​​​​​{​​​​​​​author:"okome", ​​​​​​​sourceTitle:"doope!", ​​​​​​​title:"Update:Bethesda Game Studiosが開発を手掛けたVaultシム「Fallout Shelter」がSteamに登場、リリースはまもなく", ​​​​​​​link:"http://doope.jp/2017/0363788.html", ​​​​​​​pubDate:1.490796335E+12, ​​​​​​​description:"UPDATE:3月29日23:05 新たにSteamにて本作の配信が開始されました。以下、更新前の本文となります。 今年2月にXbox OneとWin10向けのローンチを果たしたBethesda Game Studios [&#8230;]", ​​​​​​​sourceLink:"http://doope.jp"​​​​​}, ​​​​​{​​​​​​​author:"", ​​​​​​​sourceTitle:"電撃オンライン – 総合ゲーム情報サイト", ​​​​​​​title:"『9時間9人9の扉 善人シボウデス ダブルパック』PS4/PS Vita版の店舗別予約特典を紹介 ", ​​​​​​​link:"http://dengekionline.com/elem/000/001/493/1493825/", ​​​​​​​pubDate:1.490796071E+12, ​​​​​​​description:"<p>『ZERO ESCAPE 9時間9人9の扉 善人シボウデス ダブルパック』のPS4/PS Vita版の店舗別予約特典ではオリジナルステッカーなど登場しています。</p>", ​​​​​​​sourceLink:"http://dengekionline.com/"​​​​​}
*)

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/33/feeds/game"
  
set accessToken to retAccessToken() of me —Access Token
  
set aRec to {access_token:accessToken, page:(aNum as string)}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESCode to (responseCode of aRes) as integer
  
if aRESCode is not equal to 200 then return {false, false}
  
  
set aRESTres to (json of aRes) as record
  
  
set sentiRes to entries of aRESTres
  
set allNum to num of aRESTres
  
log allNum
  
  
return {sentiRes, allNum}
end getAFeeds

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  
  
set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"Test AppleScript (gzip)" forHTTPHeaderField:"User-Agent"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxXXXxxX-XxXx-XXXX-xXXX-XXxXXxxXxxXx" –API Tore Access Token
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ニュースサイト ごちゃまぜフィード

Posted on 3月 3, 2018 by Takaaki Naganoya

ApitoreのREST API「ニュースサイト ごちゃまぜフィード」を呼び出して、さまざまなテック系サイトのNews Feedを一括で取得するAppleScriptです。

# Apitoreは2019年5月31日をもってサービスを終了

「ニュースサイト ごちゃまぜフィード」は、30分に1回の頻度でRSSの更新を確認にいきます。REST APIで最新情報が取得できるオンラインクローラーです。以下のサイトのRSSを収集しています。

・Huffington Post Japan
・IBTimes エンタメ・スポーツ
・IBTimes グローバル
・IBTimes マーケット
・IBTimes ライフ
・IBTimes 企業
・IBTimes 経済
・IBTimes IT・サイエンス
・ダイヤモンド・オンライン
・ビジネスジャーナル
・東洋経済オンライン
・毎日新聞
・CNN

本AppleScript利用のためには、Apitoreにサインアップしてアカウントを作成し、新規プロジェクトを作成(Test AppleScriptとか)。そこに、本APIを利用できるように登録し、「アクセストークン」を取得する必要があります。

アクセストークンを取得せずに掲載状態のまま本AppleScriptを実行してもエラーになります。

取得したアクセストークンを本AppleScript中のretAccessToken()ハンドラ内に記載し、実行してください。

AppleScript名:ニュースサイト ごちゃまぜフィード
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

getNewsFeed() of me

on getNewsFeed()
  set allFeeds to {}
  
  
repeat with i from 1 to 100
    set {aRes, maxNum} to getAFeeds(i) of me
    
    
if aRes = false then exit repeat
    
set maxNum to maxNum as number
    
set allFeeds to allFeeds & aRes
    
if (maxNum div 10) ≤ i then
      exit repeat
    end if
  end repeat
  
  
return allFeeds
end getNewsFeed

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/34/feeds/news"
  
set accessToken to retAccessToken() of me —Access Token
  
set aRec to {access_token:accessToken, page:(aNum as string)}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESCode to (responseCode of aRes) as integer
  
if aRESCode is not equal to 200 then return {false, false}
  
  
set aRESTres to (json of aRes) as record
  
  
set sentiRes to entries of aRESTres
  
set allNum to num of aRESTres
  
–log allNum
  
  
return {sentiRes, allNum}
end getAFeeds

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  
  
set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"Test AppleScript (gzip)" forHTTPHeaderField:"User-Agent"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxXXXxxX-XxXx-XXXX-xXXX-XXxXXxxXxxXx" –API Tore Access Token
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

テックサイト ごちゃまぜフィード

Posted on 3月 3, 2018 by Takaaki Naganoya

ApitoreのREST API「テックサイト ごちゃまぜフィード」を呼び出して、さまざまなテック系サイトのNews Feedを一括で取得するAppleScriptです。

# Apitoreは2019年5月31日をもってサービスを終了

「テックサイト ごちゃまぜフィード」は、30分に1回の頻度でRSSの更新を確認にいきます。REST APIで最新情報が取得できるオンラインクローラーです。

本AppleScript利用のためには、Apitoreにサインアップしてアカウントを作成し、新規プロジェクトを作成(Test AppleScriptとか)。そこに、本APIを利用できるように登録し、「アクセストークン」を取得する必要があります。

アクセストークンを取得せずに掲載状態のまま本AppleScriptを実行してもエラーになります。

取得したアクセストークンを本AppleScript中のretAccessToken()ハンドラ内に記載し、実行してください。

AppleScript名:テックサイト ごちゃまぜフィード
— Created 2016-10-27 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set allFeeds to {}

repeat with i from 1 to 100
  set {aRes, maxNum} to getAFeeds(i) of me
  
  
if aRes = false then exit repeat
  
set maxNum to maxNum as number
  
set allFeeds to allFeeds & aRes
  
if (maxNum div 10) ≤ i then
    exit repeat
  end if
end repeat

return allFeeds
–>  
(*
{​​​​​{​​​​​​​author:"Ittousai", ​​​​​​​sourceTitle:"Engadget Japanese RSS Feed", ​​​​​​​title:" 速報:サムスンGalaxy S8発表イベント UNPACKED 2017 (ライブ更新ページ)
", ​​​​​​​link:"http://japanese.engadget.com/2017/03/29/galaxy-s8-unpacked-2017/", ​​​​​​​pubDate:1.49079606E+12, ​​​​​​​description:"<p> <img src=\"http://o.aolcdn.com/hss/storage/midas/a009a6b57896291f7e66fe091c6bdf94/205070326/unbox.png\" /> </p>", ​​​​​​​sourceLink:"http://japanese.engadget.com/rss.xml"​​​​​}, ​​​​​
*)

on getAFeeds(aNum)
  set reqURLStr to "https://api.apitore.com/api/35/feeds/tech"
  
set accessToken to retAccessToken() of me —Access Token
  
set aRec to {access_token:accessToken, page:(aNum as string)}
  
set aURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestGETAPIAndParseResults(aURL) of me
  
  
set aRESCode to (responseCode of aRes) as integer
  
if aRESCode is not equal to 200 then return {false, false}
  
  
set aRESTres to (json of aRes) as record
  
  
set sentiRes to entries of aRESTres
  
set allNum to num of aRESTres
  
log allNum
  
  
return {sentiRes, allNum}
end getAFeeds

–GET methodのREST APIを呼ぶ
on callRestGETAPIAndParseResults(aURL)
  
  
set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL)
  
  
aRequest’s setHTTPMethod:"GET"
  
aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  
aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"
  
aRequest’s setValue:"Test AppleScript (gzip)" forHTTPHeaderField:"User-Agent"
  
  
set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding)
  
  
set jsonString to current application’s NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code & Header
  
set dRes to contents of second item of resList
  
if dRes is not equal to missing value then
    set resCode to (dRes’s statusCode()) as number
    
set resHeaders to (dRes’s allHeaderFields()) as record
  else
    set resCode to 0
    
set resHeaders to {}
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestGETAPIAndParseResults

on retURLwithParams(aBaseURL, aRec)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) as text
  
  
return aURL
end retURLwithParams

on retAccessToken()
  return "xxXXXxxX-XxXx-XXXX-xXXX-XXxXXxxXxxXx" –API Tore Access Token
end retAccessToken

★Click Here to Open This Script 

Posted in Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Post navigation

  • Older posts
  • Newer posts

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • macOS 13, Ventura(継続更新)
  • アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js)v3
  • Xcode 14.2でAppleScript App Templateを復活させる
  • UI Browserがgithub上でソース公開され、オープンソースに
  • macOS 13 TTS Voice環境に変更
  • 2022年に書いた価値あるAppleScript
  • ChatGPTで文章のベクトル化(Embedding)
  • 新発売:AppleScriptからSiriを呼び出そう!
  • iWork 12.2がリリースされた
  • 従来と異なるmacOS 13の性格?
  • 新発売:CotEditor Scripting Book with AppleScript
  • macOS 13対応アップデート:AppleScript実践的テクニック集(1)GUI Scripting
  • AS関連データの取り扱いを容易にする(はずの)privateDataTypeLib
  • macOS 13でNSNotFoundバグふたたび
  • macOS 12.5.1、11.6.8でFinderのselectionでスクリーンショット画像をopenできない問題
  • ChatGPTでchatに対する応答文を取得
  • 新発売:iWork Scripting Book with AppleScript
  • Finderの隠し命令openVirtualLocationが発見される
  • macOS 13.1アップデートでスクリプトエディタの挙動がようやくまともに
  • あのコン過去ログビューワー(暫定版)

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1390) 10.14savvy (586) 10.15savvy (434) 11.0savvy (277) 12.0savvy (186) 13.0savvy (59) CotEditor (60) Finder (47) iTunes (19) Keynote (99) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (57) Pages (38) Safari (41) Script Editor (20) WKUserContentController (21) WKUserScript (20) WKUserScriptInjectionTimeAtDocumentEnd (18) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • drive
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC