AppleScript HTML

URLのHTMLを取得してリンクを収集する


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
(*
com.cocolog-nifty.quicktimer.icefloe
外部リンクのみ収集
*)
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application

property refNSNotFound : a reference to 9.22337203685477E+18 + 5807

#パスにこの文字を含むURL以外を収集
set strDirString to ("timetable") as text


########################
## クリップボードの中身取り出し
########################
###初期化
set ocidPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to ocidPasteboard's types
###テキストがあれば
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  ###値を格納する
  tell application "Finder"
    set strReadString to (the clipboard as text) as text
  end tell
  ###Finderでエラーしたら
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
log "テキストなし"
    set strReadString to "1" as text
  end if
end if
##############################
#####ダイアログ
##############################
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder"
activate
  end tell
else
  tell current application
activate
  end tell
end if
set strMes to ("WEBサイトのURLを入力") as text
set aliasIconPath to POSIX file "/System/Applications/Calculator.app/Contents/Resources/AppIcon.icns" as alias
try
  set recordResult to (display dialog strMes with title "入力してください" default answer strReadString buttons {"OK", "キャンセル"} default button "OK" with icon aliasIconPath giving up after 20 without hidden answer) as record
on error
log "エラーしました"
return
end try

if "OK" is equal to (button returned of recordResult) then
  set strReturnedText to (text returned of recordResult) as text
else if (gave up of recordResult) is true then
return "時間切れです"
else
return "キャンセル"
end if
##############################
#####戻り値整形
##############################
set ocidResponseText to (refMe's NSString's stringWithString:(strReturnedText))
###タブと改行を除去しておく
set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
ocidTextM's appendString:(ocidResponseText)
##改行除去
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\n") withString:("")
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\r") withString:("")
##タブ除去
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\t") withString:("")
####戻り値を半角にする
set ocidNSStringTransform to (refMe's NSStringTransformFullwidthToHalfwidth)
set ocidTextM to (ocidTextM's stringByApplyingTransform:ocidNSStringTransform |reverse|:false)
set strURL to ocidTextM as text

###### NSURLに
set ocidURLString to refMe's NSString's stringWithString:(strURL)
set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidURLString)
set ocidHostName to ocidURL's |host|()
set ocidScheme to ocidURL's |scheme|()
set ocidURLComponents to refMe's NSURLComponents's alloc()'s init()
ocidURLComponents's setScheme:(ocidScheme)
ocidURLComponents's setHost:(ocidHostName)
###URLの内容を取得
set ocidOption to (refMe's NSDataReadingMappedIfSafe)
set listData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error|:(reference)
set ocidData to (item 1 of listData)
###テキストにして
set ocidHTML to refMe's NSString's alloc()'s initWithData:(ocidData) encoding:(refMe's NSUTF8StringEncoding)
###ある程度の整形
#set ocidHTML to (ocidHTML's stringByReplacingOccurrencesOfString:("\r\n") withString:("\n"))
set ocidHTML to (ocidHTML's stringByReplacingOccurrencesOfString:("\r") withString:(""))
set ocidHTML to (ocidHTML's stringByReplacingOccurrencesOfString:("\n") withString:(""))
set ocidHTML to (ocidHTML's stringByReplacingOccurrencesOfString:("\t") withString:(""))
set ocidHTML to (ocidHTML's stringByReplacingOccurrencesOfString:("\"></a>") withString:("\" /></a>"))
#set ocidHTML to (ocidHTML's stringByReplacingOccurrencesOfString:("><") withString:(">\n<"))
set ocidHTML to (ocidHTML's stringByReplacingOccurrencesOfString:("</a>") withString:("</a>\n"))
set ocidHTML to (ocidHTML's stringByReplacingOccurrencesOfString:("<a") withString:("\n<a"))
set ocidHTML to (ocidHTML's stringByReplacingOccurrencesOfString:("&") withString:("&amp;"))
##改行毎のARRAYにして
set ocidHTMLArray to ocidHTML's componentsSeparatedByString:("\n")
##URL格納用のDICT
set ocidURLDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
##処理
repeat with itemArray in ocidHTMLArray
  #aタグのみ処理
  set ocidRange to (itemArray's rangeOfString:("<a"))
  if (ocidRange's location()) ≠ refNSNotFound then
    try
      #aタグの内容をエレメントに格納
      set listAElement to (refMe's NSXMLElement's alloc()'s initWithXMLString:(itemArray) |error|:(reference))
      set ocidAelement to (item 1 of listAElement)
      #URLを取得
      set ocidValue to (ocidAelement's attributeForName:("href"))'s stringValue
      #対象のパス名が含まれているか?
      set ocidRange to (ocidValue's rangeOfString:(strDirString))
      if (ocidRange's location()) ≠ refNSNotFound then
        set ocidKeyName to ocidAelement's stringValue()
        #相対パス記述の場合にベースURLを付与
        if (ocidValue as text) starts with "/" then
(ocidURLComponents's setPath:(ocidValue))
          set ocidValue to (ocidURLComponents's |URL|)'s absoluteString()
        end if
        #格納用のDICTに格納していく
(ocidURLDict's setValue:(ocidValue) forKey:(ocidKeyName))
      end if
    on error
log ("hrefアトリヴュートが無いか?エレメント構造にエラーがあります: " & itemArray) as text
    end try
  end if
  
end repeat
###ここまでの内容
log ocidURLDict as record
####タブ区切りで保存
#キーの取得
set ocdiAllKeys to ocidURLDict's allKeys()
#格納用のテキスト
set ocidSaveString to refMe's NSMutableString's alloc()'s initWithCapacity:0
#DICTキーの数だけ処理
repeat with itemKey in ocdiAllKeys
  #キー名で値を取り出して
  set ocidValue to (ocidURLDict's valueForKey:(itemKey))
  #キー名をテキストに追加
(ocidSaveString's appendString:(itemKey))
  #区切り文字タブ
(ocidSaveString's appendString:("\t"))
  #取得したURLを追加
(ocidSaveString's appendString:(ocidValue))
  #改行
(ocidSaveString's appendString:("\n"))
end repeat

###ここまでの内容
log ocidSaveString as text

###保存
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidDirURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDocumentDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDocumentPathURL to ocidDirURLsArray's firstObject()
set ocidSaveDirPathURL to ocidDocumentPathURL's URLByAppendingPathComponent:("URL") isDirectory:(true)
set ocidSaveSubDirPathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidHostName) isDirectory:(true)
set aliasSaveSubDirPath to (ocidSaveSubDirPathURL's absoluteURL()) as alias
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveSubDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
#ファイル名日付
set strDateNo to doGetDateNo("yyyyMMdd_HHmmss")
set ocidSaveBaseFilePathURL to ocidSaveSubDirPathURL's URLByAppendingPathComponent:(strDateNo) isDirectory:(false)
set ocidSaveFilePathURL to ocidSaveBaseFilePathURL's URLByAppendingPathExtension:("tsv")
#UTF8で保存
set listDone to ocidSaveString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
if (item 1 of listDone) is false then
log ((item 2 of listDone)'s localizedDescription()) as text
return "保存に失敗しました"
end if
set aliasSaveFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
#保存先を開く
tell application "Finder"
open location aliasSaveSubDirPath
select aliasSaveFilePath
end tell
##############################
### 今の日付日間 テキスト
##############################
to doGetDateNo(argDateFormat)
  ####日付情報の取得
  set ocidDate to current application's NSDate's |date|()
  ###日付のフォーマットを定義
  set ocidNSDateFormatter to current application's NSDateFormatter's alloc()'s init()
ocidNSDateFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
  set ocidTimeZone to refMe's NSTimeZone's alloc()'s initWithName:"Asia/Tokyo"
ocidNSDateFormatter's setTimeZone:(ocidTimeZone)
ocidNSDateFormatter's setDateFormat:(argDateFormat)
  set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
  set strDateAndTime to ocidDateAndTime as text
return strDateAndTime
end doGetDateNo

|

[XML]CDATA(HTML化済みのテキスト)を追加する


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use framework "Foundation"
use AppleScript version "2.8"
use scripting additions

property refMe : a reference to current application


set strHTMLtext to ("美しい日本語の\nオープンタイプフォント")
set ocidHTMLtext to refMe's NSString's stringWithString:(strHTMLtext)
set ocidHTML to (ocidHTMLtext's stringByReplacingOccurrencesOfString:("\n") withString:("<br />"))
log ocidHTML as text
--> 美しい日本語の<br />オープンタイプフォント

###XML初期化
set ocidXMLDoc to refMe's NSXMLDocument's alloc()'s init()
ocidXMLDoc's setDocumentContentKind:(refMe's NSXMLDocumentHTMLKind)
set ocidDTD to refMe's NSXMLDTD's alloc()'s init()
###DTD追加
ocidDTD's setName:("html")
ocidXMLDoc's setDTD:(ocidDTD)
###このエレメントがルート
set ocidRootElement to refMe's NSXMLElement's elementWithName:("html")
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("lang") stringValue:("ja")
ocidRootElement's addAttribute:(ocidAddNode)
###ヘッド
set ocidHeadElement to refMe's NSXMLElement's elementWithName:("head")
set ocidAddElement to refMe's NSXMLElement's elementWithName:("title")
ocidAddElement's setStringValue:("CDATAをXMLにテキスト追加する")
ocidHeadElement's addChild:(ocidAddElement)
# http-equiv
set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Type")
ocidAddElement's addAttribute:(ocidAddNode)
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/html; charset=UTF-8")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
ocidRootElement's addChild:(ocidHeadElement)
###ボディエレメント
set ocidBodyElement to refMe's NSXMLElement's elementWithName:("body")

###########
#本処理
# NODEをCDATAとして新規作成
set ocidAddNode to (refMe's NSXMLNode's alloc()'s initWithKind:(refMe's NSXMLTextKind) options:(refMe's NSXMLNodeIsCDATA))
#NODEにテキストとしてHTMLを追加
(ocidAddNode's setStringValue:(ocidHTML))
#テキストを追加したCDATA用のノードをボディにセット
(ocidBodyElement's addChild:(ocidAddNode))


###ボディをROOTに追加
ocidRootElement's addChild:(ocidBodyElement)
###ROOTをXMLに追加
ocidXMLDoc's setRootElement:(ocidRootElement)
###テキストにする
set ocidXMLdata to ocidXMLDoc's XMLStringWithOptions:(refMe's NSXMLNodePrettyPrint)

log ocidXMLdata as text

(*<!DOCTYPE html>

<html lang="ja">
<head>
<title>CDATAをXMLにテキスト追加する</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body><![CDATA[美しい日本語の<br />オープンタイプフォント]]></body>
</html>*)

|

画像が入っているフォルダからHTMLを生成する


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKIt"
use framework "UniformTypeIdentifiers"
use scripting additions

property refMe : a reference to current application
property strBundleID : "com.apple.Preview"

###Wクリックで起動した場合
on run
  set aliasDefaultLocation to (path to desktop from user domain) as alias
  set strPromptText to "画像が入ったフォルダをえらんでください"
  set strMesText to "画像が入ったフォルダをえらんでください"
  try
    set aliasFolderPath to (choose folder strMesText with prompt strPromptText default location aliasDefaultLocation with invisibles and showing package contents without multiple selections allowed) as alias
  on error
log "エラーしました"
return "エラーしました"
  end try
  
open aliasFolderPath
end run

###ドロップで起動した場合
on open aliasFolderPath
  ####################################
  ####フォルタ以外は処理しない
  set strDirPath to (POSIX path of aliasFolderPath) as text
  set ocidDirPathStr to (refMe's NSString's stringWithString:(strDirPath))
  set ocidDirPath to ocidDirPathStr's stringByStandardizingPath()
  set ocidDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidDirPath) isDirectory:true)
  set listBoole to (ocidDirPathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsDirectoryKey) |error|:(reference))
  set boolIsDir to (item 2 of listBoole) as boolean
  if boolIsDir is true then
log "フォルダなので処理開始"
  else
return "フォルダ以外は処理しない"
  end if
  
  
  ################################
  ##【本処理】フォルダの数だけ繰り返し
  ################################
  ###enumeratorAtURL用のBoolean用
  set ocidFalse to (refMe's NSNumber's numberWithBool:false)
  set ocidTrue to (refMe's NSNumber's numberWithBool:true)
  
  ###ファイルURLのみを格納するリスト
  set ocidFilePathURLAllArray to (refMe's NSMutableArray's alloc()'s initWithCapacity:0)
  ##################################
  #ファイルURLの収集
  ##プロパティ
  set ocidPropertieKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
ocidPropertieKeyArray's addObject:(refMe's NSURLPathKey)
ocidPropertieKeyArray's addObject:(refMe's NSURLContentTypeKey)
  ##オプション(隠しファイルは含まない)
  set ocidOption to refMe's NSDirectoryEnumerationSkipsHiddenFiles
  ####ディレクトリのコンテツを収集(最下層まで)
  set appFileManager to refMe's NSFileManager's defaultManager()
  set ocidEmuDict to (appFileManager's enumeratorAtURL:(ocidDirPathURL) includingPropertiesForKeys:(ocidPropertieKeyArray) options:(ocidOption) errorHandler:(reference))
  ###戻り値をリストに格納
  set ocidEmuFileURLArray to ocidEmuDict's allObjects()
ocidFilePathURLAllArray's addObjectsFromArray:(ocidEmuFileURLArray)
  
  ##############################
  ####並び替え並び替え compare
  (*
compare:
caseInsensitiveCompare:
localizedCompare:
localizedStandardCompare:
localizedCaseInsensitiveCompare:
*)
  #NSSortDescriptor's
  set ocidSortDescriptorsArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
  set ocidSortDescriptor to (refMe's NSSortDescriptor's sortDescriptorWithKey:"absoluteString" ascending:(true) selector:"localizedStandardCompare:")
ocidSortDescriptorsArray's addObject:(ocidSortDescriptor)
  ##
ocidFilePathURLAllArray's sortUsingDescriptors:(ocidSortDescriptorsArray)
  ##############################
  ##まずはHTMLの基本的部分を生成
  ########################################
  #headerに渡すエレメント
  set ocidH3Element to refMe's NSXMLElement's elementWithName:("h3")
(ocidH3Element's setStringValue:("イメージ一覧"))
  
  ########################################
  #footerに渡すエレメント
  set ocidFotterAElement to refMe's NSXMLElement's elementWithName:("a")
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("href") stringValue:("https://quicktimer.cocolog-nifty.com/"))
(ocidFotterAElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("target") stringValue:("_blank"))
(ocidFotterAElement's addAttribute:(ocidAddNode))
  set strContents to ("AppleScriptで生成しました") as text
(ocidFotterAElement's setStringValue:(strContents))
  
  ########################################
  #articleに渡すエレメント
  #テーブル部生成開始
  set ocidTableElement to refMe's NSXMLElement's elementWithName:("table")
  #####【caption】
  set ocidCaptionElement to refMe's NSXMLElement's elementWithName:("caption")
ocidCaptionElement's setStringValue:("イメージファイル一覧(クリックで新しいWINDOWで開きます)")
ocidTableElement's addChild:(ocidCaptionElement)
  #####【colgroup】
  set ocidColgroupElement to refMe's NSXMLElement's elementWithName:("colgroup")
  #タイトル部の数だけ繰り返し
  set listColName to {"LineNo", "Image"} as list
  repeat with itemColName in listColName
    #######【col】col生成
    set ocidAddElement to (refMe's NSXMLElement's elementWithName:("col"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
(ocidColgroupElement's addChild:(ocidAddElement))
  end repeat
  #テーブルエレメントに追加
ocidTableElement's addChild:(ocidColgroupElement)
  #######【thead】
  set ocidTheadElement to refMe's NSXMLElement's elementWithName:("thead")
  #TR
  set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
  #タイトル部の数だけ繰り返し
  repeat with itemColName in listColName
    if (itemColName as text) is "LineNo" then
      #ここはTDではなくてTHを利用
      set ocidAddElement to (refMe's NSXMLElement's elementWithName:("th"))
      ####項番処理
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
      #
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("id") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
(ocidAddElement's addAttribute:(ocidAddNode))
      #値を入れる
(ocidAddElement's setStringValue:("\"))
      #TH→TRにセット
(ocidTrElement's addChild:(ocidAddElement))
    else
      #ここはTDではなくてTHを利用
      set ocidAddElement to (refMe's NSXMLElement's elementWithName:("th"))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
      #
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("id") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
(ocidAddElement's addAttribute:(ocidAddNode))
      #値を入れる
(ocidAddElement's setStringValue:(itemColName))
      #TH→TRにセット
(ocidTrElement's addChild:(ocidAddElement))
    end if
  end repeat
  #TRをTHEADにセット
ocidTheadElement's addChild:(ocidTrElement)
  #THEADをテーブルにセット
ocidTableElement's addChild:(ocidTheadElement)
  
  ##################################
  #本処理
  ######【tbody】
  set ocidTbodyElement to refMe's NSXMLElement's elementWithName:("tbody")
  set numCntRow to 1 as integer
  repeat with itemArray in ocidFilePathURLAllArray
    #TRの開始
    set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
    ####項番処理
    set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("項目番号:" & numCntRow))
(ocidThElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("headers") stringValue:("LineNo"))
(ocidThElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
(ocidThElement's addAttribute:(ocidAddNode))
(ocidThElement's setStringValue:(numCntRow as text))
(ocidTrElement's addChild:(ocidThElement))
    ##################################
    set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
    ####
    #一つ上の階層を基準とした相対パスにする
    ##コンテナ
    set ocidPreDirPathURL to itemArray's URLByDeletingLastPathComponent()
    set ocidContainerName to ocidPreDirPathURL's lastPathComponent()
    set ocidFileName to itemArray's lastPathComponent()
    set ocidRelativePath to (ocidContainerName's stringByAppendingPathComponent:(ocidFileName))
    ###
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(ocidFileName))
(ocidTdElement's addAttribute:(ocidAddNode))
    # set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("headers") stringValue:(ocidFileName))
    #(ocidTdElement's addAttribute:(ocidAddNode))
    # set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
    # (ocidTdElement's addAttribute:(ocidAddNode))
    ###
    set ocidAElement to (refMe's NSXMLElement's elementWithName:("a"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("href") stringValue:(ocidRelativePath))
(ocidAElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("target") stringValue:("_blank"))
(ocidAElement's addAttribute:(ocidAddNode))
    ###
    set ocidImgElement to (refMe's NSXMLElement's elementWithName:("img"))
(ocidImgElement's addAttribute:(refMe's NSXMLNode's attributeWithName:("src") stringValue:(ocidRelativePath)))
(ocidImgElement's addAttribute:(refMe's NSXMLNode's attributeWithName:("alt") stringValue:(ocidFileName)))
(ocidImgElement's addAttribute:(refMe's NSXMLNode's attributeWithName:("style") stringValue:("object-fit: cover;")))
(ocidAElement's addChild:(ocidImgElement))
    #
(ocidTdElement's addChild:(ocidAElement))
    ##
(ocidTrElement's addChild:(ocidTdElement))
(ocidTbodyElement's addChild:(ocidTrElement))
    set numCntRow to numCntRow + 1 as integer
  end repeat
  #TBODYをテーブルにセット
ocidTableElement's addChild:(ocidTbodyElement)
  
  
  ######【tfoot】 TRで
  set ocidTfootElement to refMe's NSXMLElement's elementWithName:("tfoot")
  set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
  #項目数を取得して
  set numCntCol to (count of listColName) as integer
  #colspan指定して1行でセット
  set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("テーブルの終わり"))
(ocidThElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("colspan") stringValue:(numCntCol as text))
(ocidThElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
(ocidThElement's addAttribute:(ocidAddNode))
  #
  set numCntContents to (count of ocidFilePathURLAllArray) as integer
  set strContents to ("項目数 : " & (numCntContents - 1)) as text
(ocidThElement's setStringValue:(strContents))
  #THをTRにセットして
ocidTrElement's addChild:(ocidThElement)
  #TRをTFOOTにセット
ocidTfootElement's addChild:(ocidTrElement)
  #TFOOTをテーブルにセット
ocidTableElement's addChild:(ocidTfootElement)
  
  ##############################
  #HTMLにする
  ##############################
  set ocidHTML to doMakeRootElement({ocidH3Element, ocidTableElement, ocidFotterAElement})
  ##############################
  #保存
  ##############################
  #読み取りやすい表示
  set ocidXMLdata to ocidHTML's XMLDataWithOptions:(refMe's NSXMLNodePrettyPrint)
  #
  set ocidSaveDirPathURL to ocidDirPathURL's URLByDeletingLastPathComponent()
  #
  set strSaveFileName to ("index.html") as text
  set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileName)
  
  set listDone to ocidXMLdata's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error|:(reference)
  
  ####【6】ブラウザで開く
  set aliasFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
  tell application "Finder"
open location aliasFilePath
  end tell
  
end open











############################################################
# 基本的なHTMLの構造
(*
doMakeRootElement({argHeaderContents, argArticleContents, argFooterContents})
HTMLのBODY部
header
article
footerにそれぞれAddchildするデータをリストで渡す
戻り値はRootエレメントにセットされた
NSXMLDocumentを戻すので 保存すればOK
*)
############################################################
to doMakeRootElement({argHeaderContents, argArticleContents, argFooterContents})
  #XML初期化
  set ocidXMLDoc to refMe's NSXMLDocument's alloc()'s init()
ocidXMLDoc's setDocumentContentKind:(refMe's NSXMLDocumentHTMLKind)
  # DTD付与
  set ocidDTD to refMe's NSXMLDTD's alloc()'s init()
ocidDTD's setName:("html")
ocidXMLDoc's setDTD:(ocidDTD)
  #
  set ocidRootElement to refMe's NSXMLElement's elementWithName:("html")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("lang") stringValue:("ja")
ocidRootElement's addAttribute:(ocidAddNode)
  #
  set ocidHeadElement to refMe's NSXMLElement's elementWithName:("head")
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("title")
ocidAddElement's setStringValue:("ImageList")
ocidHeadElement's addChild:(ocidAddElement)
  # http-equiv
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/html; charset=UTF-8")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("name") stringValue:("viewport")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("width=720")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("style")
ocidAddElement's setStringValue:("body {margin: 10px;background-color: #FFFFFF;}table {max-width: 1280px;border-spacing: 0;caption-side: top;font-family: system-ui;}thead th {border: solid 1px #666666;padding: .5ch 1ch;border-block-width: 1px 0;border-inline-width: 1px 0;&:first-of-type {border-start-start-radius: .5em}&:last-of-type {border-start-end-radius: .5em;border-inline-end-width: 1px}}tbody th {border-spacing: 0;width: 40px !important;border: solid 1px #666666;padding: .5ch 1ch;border-block-width: 1px 0;border-inline-width: 1px 0;}tbody td {word-wrap: break-word;width: 720px;max-width: 720px;border-spacing: 0;border: solid 1px #666666;padding: .5ch 1ch;border-block-width: 1px 0;border-inline-width: 1px 0;&:last-of-type {border-inline-end-width: 1px}}tbody tr:nth-of-type(odd) {background: #F2F2F2;}.kind_string {font-size: 0.75em;}.date_string {font-size: 0.5em;}tfoot th {border: solid 1px #666666;padding: .5ch 1ch;&:first-of-type {border-end-start-radius: .5em}&:last-of-type {border-end-end-radius: .5em;border-inline-end-width: 1px}}img {max-width: 720px;}")
ocidHeadElement's addChild:(ocidAddElement)
ocidRootElement's addChild:(ocidHeadElement)
  #
  #ボディエレメント
  set ocidBodyElement to refMe's NSXMLElement's elementWithName:("body")
  #ヘッダー
  set ocidHeaderElement to refMe's NSXMLElement's elementWithName:("header")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("header")
ocidHeaderElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_header")
ocidHeaderElement's addAttribute:(ocidAddNode)
ocidHeaderElement's addChild:(argHeaderContents)
ocidBodyElement's addChild:(ocidHeaderElement)
  #アーティクル
  set ocidArticleElement to refMe's NSXMLElement's elementWithName:("article")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("article")
ocidArticleElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_article")
ocidArticleElement's addAttribute:(ocidAddNode)
ocidArticleElement's addChild:(argArticleContents)
  set ocidH6Element to refMe's NSXMLElement's elementWithName:("h6")
(ocidH6Element's setStringValue:("イメージ一覧"))
ocidArticleElement's addChild:(ocidH6Element)
ocidBodyElement's addChild:(ocidArticleElement)
  #フッター
  set ocidFooterElement to refMe's NSXMLElement's elementWithName:("footer")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("footer")
ocidFooterElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_footer")
ocidFooterElement's addAttribute:(ocidAddNode)
ocidFooterElement's addChild:(argFooterContents)
ocidBodyElement's addChild:(ocidFooterElement)
  #ボディをROOTエレメントにセット
ocidRootElement's addChild:(ocidBodyElement)
  #ROOTをXMLにセット
ocidXMLDoc's setRootElement:(ocidRootElement)
  #値を戻す
return ocidXMLDoc
end doMakeRootElement

|

TSV2HTML タブ区切りテキストをHTMLテーブルに変換 UNIX改行修正


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
(*
com.cocolog-nifty.quicktimer.icefloe
TSV2HTML項番あり

*)
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions
property refMe : a reference to current application

### 【1】入力ファイル
#ダイアログ
tell current application
  set strName to name as text
end tell
#スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
#デフォルトロケーション
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
#
set listUTI to {"public.tab-separated-values-text"}
set strMes to ("ファイルを選んでください") as text
set strPrompt to ("ファイルを選んでください") as text
try
  ### ファイル選択時
  set aliasFilePath to (choose file strMes with prompt strPrompt default location aliasDesktopDirPath of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
if aliasFilePath is (missing value) then
return "選んでください"
end if
set strFilePath to (POSIX path of aliasFilePath) as text
set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
#保存するタブ区切りテキストのパス
set ocidBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
set ocidFileName to ocidBaseFilePathURL's lastPathComponent()
set ocidSaveFilePathURL to (ocidBaseFilePathURL's URLByAppendingPathExtension:("html"))
### 【2】 ファイルのテキストを読み込み
set listResponse to (refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
set ocidReadString to (item 1 of listResponse)
#可変にして
set ocidLineString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
(ocidLineString's setString:(ocidReadString))
#改行をUNIXに強制
set ocidLineStringLF to (ocidLineString's stringByReplacingOccurrencesOfString:("\r\n") withString:("\n"))
set ocidLineString to (ocidLineStringLF's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
#改行毎でリストにする
set ocidCharSet to (refMe's NSCharacterSet's newlineCharacterSet)
set ocidLineArray to (ocidLineString's componentsSeparatedByCharactersInSet:(ocidCharSet))
#最初の1行目だけ別で取得しておく
set ocidFirstObjectString to ocidLineArray's firstObject()
set ocidFirstLineArray to ocidFirstObjectString's componentsSeparatedByString:("\t")

###【4】データをHTMLに整形
########################################
#headerに渡すエレメント
set ocidH3Element to refMe's NSXMLElement's elementWithName:("h3")
(ocidH3Element's setStringValue:("タブ区切りテキストをHTMLテーブルに"))
########################################
#footerに渡すエレメント
set ocidFotterAElement to refMe's NSXMLElement's elementWithName:("a")
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("href") stringValue:("https://quicktimer.cocolog-nifty.com/"))
(ocidFotterAElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("target") stringValue:("_blank"))
(ocidFotterAElement's addAttribute:(ocidAddNode))
set strContents to ("AppleScriptで生成しました") as text
(ocidFotterAElement's setStringValue:(strContents))
########################################
#articleに渡すエレメント
#テーブル部生成開始
set ocidTableElement to refMe's NSXMLElement's elementWithName:("table")
#【caption】
set ocidCaptionElement to refMe's NSXMLElement's elementWithName:("caption")
ocidCaptionElement's setStringValue:(ocidFileName)
ocidTableElement's addChild:(ocidCaptionElement)
#【colgroup】
set ocidColgroupElement to refMe's NSXMLElement's elementWithName:("colgroup")
#タイトル部の数だけ繰り返し
#項番部を追加する
set strFirstCol to ("LineNo") as text
ocidFirstLineArray's insertObject:(strFirstCol) atIndex:(0)
repeat with itemColName in ocidFirstLineArray
  #【col】col生成
  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("col"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
(ocidColgroupElement's addChild:(ocidAddElement))
end repeat
#テーブルエレメントに追加
ocidTableElement's addChild:(ocidColgroupElement)
#【thead】
set ocidTheadElement to refMe's NSXMLElement's elementWithName:("thead")
#TR
set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
#タイトル部の数だけ繰り返し
repeat with itemColName in ocidFirstLineArray
  if (itemColName as text) is "LineNo" then
    #ここはTDではなくてTHを利用
    set ocidAddElement to (refMe's NSXMLElement's elementWithName:("th"))
    ####項番処理
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
    #
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("id") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
(ocidAddElement's addAttribute:(ocidAddNode))
    #値を入れる
(ocidAddElement's setStringValue:("\"))
    #TH→TRにセット
(ocidTrElement's addChild:(ocidAddElement))
  else
    #ここはTDではなくてTHを利用
    set ocidAddElement to (refMe's NSXMLElement's elementWithName:("th"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
    #
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("id") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
(ocidAddElement's addAttribute:(ocidAddNode))
    #値を入れる
(ocidAddElement's setStringValue:(itemColName))
    #TH→TRにセット
(ocidTrElement's addChild:(ocidAddElement))
  end if
end repeat
#TRをTHEADにセット
ocidTheadElement's addChild:(ocidTrElement)
#THEADをテーブルにセット
ocidTableElement's addChild:(ocidTheadElement)
########################################
#【tbody】
set ocidTbodyElement to refMe's NSXMLElement's elementWithName:("tbody")
###【3-4】:item
set numCntContents to (count of ocidLineArray) - 1 as integer
repeat with itemIntNo from 1 to numCntContents by 1
  set ocidLineItem to (ocidLineArray's objectAtIndex:(itemIntNo))
  #空行で終わり(TSVが改行で終わるタイプ)
  if (ocidLineItem as text) is "" then
    exit repeat
  end if
  #
  set ocidItemLineArray to (ocidLineItem's componentsSeparatedByString:("\t"))
  set numCntItemLineArray to (count of ocidItemLineArray) as integer
  ##############
  #TRの開始
  set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
  ####項番処理
  set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("項目番号:" & itemIntNo))
(ocidThElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("headers") stringValue:("LineNo"))
(ocidThElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
(ocidThElement's addAttribute:(ocidAddNode))
(ocidThElement's setStringValue:(itemIntNo as text))
(ocidTrElement's addChild:(ocidThElement))
  
  repeat with itemLineNo from 0 to (numCntItemLineArray - 1) by 1
    set coidFieldValue to (ocidItemLineArray's objectAtIndex:(itemLineNo))
    if itemLineNo = 0 then
      set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
      set strTitle to (ocidFirstLineArray's objectAtIndex:(itemLineNo + 1))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(strTitle))
(ocidThElement's addAttribute:(ocidAddNode))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("headers") stringValue:(strTitle))
(ocidThElement's addAttribute:(ocidAddNode))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
(ocidThElement's addAttribute:(ocidAddNode))
(ocidThElement's setStringValue:(coidFieldValue))
(ocidTrElement's addChild:(ocidThElement))
    else
      set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
      set strTitle to (ocidFirstLineArray's objectAtIndex:(itemLineNo + 1))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(strTitle))
(ocidTdElement's addAttribute:(ocidAddNode))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("headers") stringValue:(strTitle))
(ocidTdElement's addAttribute:(ocidAddNode))
(ocidTdElement's setStringValue:(coidFieldValue))
(ocidTrElement's addChild:(ocidTdElement))
    end if
  end repeat
(ocidTbodyElement's addChild:(ocidTrElement))
end repeat
#TBODYをテーブルにセット
ocidTableElement's addChild:(ocidTbodyElement)
#【tfoot】 TRで
set ocidTfootElement to refMe's NSXMLElement's elementWithName:("tfoot")
set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
#項目数を取得して
set numCntCol to (count of ocidFirstLineArray) as integer
#colspan指定して1行でセット
set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("テーブルの終わり"))
(ocidThElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("colspan") stringValue:(numCntCol as text))
(ocidThElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
(ocidThElement's addAttribute:(ocidAddNode))
#
set strContents to ("項目数 : " & (numCntContents - 1)) as text
(ocidThElement's setStringValue:(strContents))
#THをTRにセットして
ocidTrElement's addChild:(ocidThElement)
#TRをTFOOTにセット
ocidTfootElement's addChild:(ocidTrElement)
#TFOOTをテーブルにセット
ocidTableElement's addChild:(ocidTfootElement)

##############################
#HTMLにする
##############################
set ocidHTML to doMakeRootElement({ocidH3Element, ocidTableElement, ocidFotterAElement})

##############################
#保存
##############################

#####【5−2】保存
#読み取りやすい表示
set ocidXMLdata to ocidHTML's XMLDataWithOptions:(refMe's NSXMLNodePrettyPrint)

set listDone to ocidXMLdata's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error|:(reference)

####【6】ブラウザで開く
set aliasFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
tell application "Finder"
open location aliasFilePath
end tell

############################################################
# 基本的なHTMLの構造
(*
doMakeRootElement({argHeaderContents, argArticleContents, argFooterContents})
HTMLのBODY部
header
article
footerにそれぞれAddchildするデータをリストで渡す
戻り値はRootエレメントにセットされた
NSXMLDocumentを戻すので 保存すればOK
*)
############################################################
to doMakeRootElement({argHeaderContents, argArticleContents, argFooterContents})
  #XML初期化
  set ocidXMLDoc to refMe's NSXMLDocument's alloc()'s init()
ocidXMLDoc's setDocumentContentKind:(refMe's NSXMLDocumentHTMLKind)
  # DTD付与
  set ocidDTD to refMe's NSXMLDTD's alloc()'s init()
ocidDTD's setName:("html")
ocidXMLDoc's setDTD:(ocidDTD)
  #
  set ocidRootElement to refMe's NSXMLElement's elementWithName:("html")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("lang") stringValue:("ja")
ocidRootElement's addAttribute:(ocidAddNode)
  #
  set ocidHeadElement to refMe's NSXMLElement's elementWithName:("head")
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("title")
ocidAddElement's setStringValue:("TSV2HTML")
ocidHeadElement's addChild:(ocidAddElement)
  # http-equiv
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/html; charset=UTF-8")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Style-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/css")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Script-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/javascript")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("name") stringValue:("viewport")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("width=720")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("style")
ocidAddElement's setStringValue:("body { margin: 10px; background-color: #FFFFFF; } table { border-spacing: 0; caption-side: top; font-family: system-ui; } thead th { border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:first-of-type { border-start-start-radius: .5em } &:last-of-type { border-start-end-radius: .5em; border-inline-end-width: 1px } } tbody td { word-wrap: break-word;max-width: 360px;border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:last-of-type { border-inline-end-width: 1px } } tbody th { border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; } tbody tr:nth-of-type(odd) { background: #F2F2F2; } .kind_string { font-size: 0.75em; } .date_string { font-size: 0.5em; } tfoot th { border: solid 1px #666666; padding: .5ch 1ch; &:first-of-type { border-end-start-radius: .5em } &:last-of-type { border-end-end-radius: .5em; border-inline-end-width: 1px } }")
ocidHeadElement's addChild:(ocidAddElement)
ocidRootElement's addChild:(ocidHeadElement)
  #
  #ボディエレメント
  set ocidBodyElement to refMe's NSXMLElement's elementWithName:("body")
  #ヘッダー
  set ocidHeaderElement to refMe's NSXMLElement's elementWithName:("header")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("header")
ocidHeaderElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_header")
ocidHeaderElement's addAttribute:(ocidAddNode)
ocidHeaderElement's addChild:(argHeaderContents)
ocidBodyElement's addChild:(ocidHeaderElement)
  #アーティクル
  set ocidArticleElement to refMe's NSXMLElement's elementWithName:("article")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("article")
ocidArticleElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_article")
ocidArticleElement's addAttribute:(ocidAddNode)
ocidArticleElement's addChild:(argArticleContents)
ocidBodyElement's addChild:(ocidArticleElement)
  #フッター
  set ocidFooterElement to refMe's NSXMLElement's elementWithName:("footer")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("footer")
ocidFooterElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_footer")
ocidFooterElement's addAttribute:(ocidAddNode)
ocidFooterElement's addChild:(argFooterContents)
ocidBodyElement's addChild:(ocidFooterElement)
  #ボディをROOTエレメントにセット
ocidRootElement's addChild:(ocidBodyElement)
  #ROOTをXMLにセット
ocidXMLDoc's setRootElement:(ocidRootElement)
  #値を戻す
return ocidXMLDoc
end doMakeRootElement

|

[exiftool]Exif2HTMLv3 exiftoolのExif情報をHTMLで表示する。 exiftoolインストール付き(たいぶ修正)


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# インストールされていない場合インストール処理をします
# exiftoolをインストールしたくない人は実行しないでください
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "UniformTypeIdentifiers"
use scripting additions

property refMe : a reference to current application
set appFileManager to refMe's NSFileManager's defaultManager()

########################################
### 設定項目
### exiftoolへのパス
########################################
#一般的にはパスはこちら
# set strExifPath to "/usr/local/bin/exiftool/exiftool" as text
#自分用
set strExifPath to "~/bin/exiftool/exiftool" as text


#exiftoolパス処理
set ocidExifPathStr to refMe's NSString's stringWithString:(strExifPath)
set ocidExifPath to ocidExifPathStr's stringByStandardizingPath()
set ocidExifPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidExifPath) isDirectory:false)
set strExifPath to ocidExifPathURL's |path| as text
#
set boolDirExists to appFileManager's fileExistsAtPath:(ocidExifPath) isDirectory:(false)
if boolDirExists = true then
log "インストール済み"
else if boolDirExists = false then
log "インストールされていません"
doInstallBin()
end if

########################################
####出力先/var/folders/XX/(再起動時に削除されます)
set ocidTemporaryDirPathURL to appFileManager's temporaryDirectory
set ocidVarFoldersDirURL to ocidTemporaryDirPathURL's URLByDeletingLastPathComponent()
set ocidTemporaryItemsPathURL to ocidVarFoldersDirURL's URLByAppendingPathComponent:"TemporaryItems"
##フォルダを作る
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listDone to appFileManager's createDirectoryAtURL:(ocidTemporaryItemsPathURL) withIntermediateDirectories:(true) attributes:(ocidAttrDict) |error|:(reference)
set aliasTemporaryItems to (ocidTemporaryItemsPathURL's absoluteURL()) as alias
########################################
#######ファイル選択
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
#ユーザーホームディレクトリ
set ocidHomeDirURL to appFileManager's homeDirectoryForCurrentUser()
#デスクトップの場合
set ocidDefaultLocationURL to ocidHomeDirURL's URLByAppendingPathComponent:("Desktop") isDirectory:true
#ダウンロードフォルダの場合
#set ocidDefaultLocationURL to ocidHomeDirURL's URLByAppendingPathComponent:("Downloads") isDirectory:true
#フォントフォルダの場合
#set ocidDefaultLocationURL to ocidHomeDirURL's URLByAppendingPathComponent:("Library/Fonts") isDirectory:true
#エイリアスパスにする
set aliasDefaultLocation to (ocidDefaultLocationURL's absoluteURL()) as alias
set listUTI to {"public.item"}
set strPromptText to "ファイルを選んでください" as text
set strMesText to "ファイルを選んでください" as text
set aliasFilePath to (choose file strMesText with prompt strPromptText default location (aliasDefaultLocation) of type listUTI with invisibles without multiple selections allowed and showing package contents) as alias
####入力ファイル関連
set strFilePath to POSIX path of aliasFilePath as text
###NSストリングに
set ocidFilePath to refMe's NSString's stringWithString:strFilePath
###NSURLに
set ocidFilePathURL to refMe's NSURL's fileURLWithPath:ocidFilePath
##ファイル名取得
set strFileName to (ocidFilePathURL's lastPathComponent) as text

########################################
######出力ファイル
##ファイル名
set strSaveFileName to (strFileName & ".html") as text
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
set aliasSaveFilePath to (choose file name with prompt "htmlのファイル名を付けてください" default name strSaveFileName default location aliasTemporaryItems) as «class furl»
#
set strSaveFilePath to (POSIX path of aliasSaveFilePath) as text
###NSストリングに
set ocidSaveFilePath to refMe's NSString's stringWithString:(strSaveFilePath)
###NSURLに
set ocidSaveFilePathURL to refMe's NSURL's fileURLWithPath:(ocidSaveFilePath)
##拡張子
set strFileExtension to (ocidSaveFilePathURL's pathExtension) as text
###拡張子つけ忘れ対策
if strFileExtension is not "html" then
  set strSaveFilePath to (POSIX path of aliasSaveFilePath & ".html") as text
end if
set strErrorFilePath to (strSaveFilePath & ".json") as text

########################################
###【1】データ取得 JSON出力
try
  set strCommandText to ("\"" & strExifPath & "\" -json \"" & strFilePath & "\"") as text
  set strResponseJosn to (do shell script strCommandText) as text
on error
  try
    set strCommandText to ("\"" & strExifPath & "\" -json \"" & strFilePath & "\" > \"" & strErrorFilePath & "\"") as text
    set strResponseJosn to (do shell script strCommandText) as text
  on error
    set strCommandText to ("/bin/cat \"" & strErrorFilePath & "\"") as text
    set strResponseJosn to (do shell script strCommandText) as text
log "たぶんexiftoolの非対応のファイルタイプですA"
  end try
end try
if strResponseJosn is "" then
return "たぶんexiftoolの非対応のファイルタイプですB"
end if
###【2】NSStringにテキストに格納して
set ocidReadDataJson to refMe's NSString's stringWithString:strResponseJosn
###【3】NSConcreteMutableDataに変換
set ocidReadDataUTF to ocidReadDataJson's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
###【4】NSInlineDataデータ初期化
set ocidReadData to (refMe's NSData's alloc()'s initWithData:(ocidReadDataUTF))
###【5】NSJSONSerialization
set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:ocidReadData options:0 |error|:(reference))
set ocidJsonData to (item 1 of listJSONSerialization)
-->(*__NSSingleObjectArrayI*)
####解説
(*
exiftoolの書き出すJSONはrootがArray構造から始まっているので
PlistにするにはDictに変換なりする必要がある
幸い『[{}]』といったシングルArray構造なので
Arrayから最初のOBJECTを取り出せばDICTレコード構造になる
*)
set ocidJsonDict to (ocidJsonData's firstObject())
-->(*__NSDictionaryI*)
###【6】レコードをNSDictionaryとして格納
set ocidJsonDict to (refMe's NSDictionary's alloc()'s initWithDictionary:ocidJsonDict)
#AllKeys
set ocidAllKeyArray to ocidJsonDict's allKeys()
#並び替えソート
set ocidAllKeySortedArray to ocidAllKeyArray's sortedArrayUsingSelector:("localizedStandardCompare:")

##############################
# XML 生成開始
##############################
#XML初期化
set ocidXMLDoc to refMe's NSXMLDocument's alloc()'s init()
ocidXMLDoc's setDocumentContentKind:(refMe's NSXMLDocumentHTMLKind)
# DTD付与
set ocidDTD to refMe's NSXMLDTD's alloc()'s init()
ocidDTD's setName:("html")
ocidXMLDoc's setDTD:(ocidDTD)
# XML主要部分を生成
set strTitleText to ("【ExifTool】: " & strFileName & " :メタデータ一覧") as text
set ocidRootElement to doMakeRootElement(strTitleText)
#ボディエレメント
set ocidBodyElement to refMe's NSXMLElement's elementWithName:("body")
#ヘッダー
set ocidHeaderElement to refMe's NSXMLElement's elementWithName:("header")
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("header")
ocidHeaderElement's addAttribute:(ocidAddNode)
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_header")
ocidHeaderElement's addAttribute:(ocidAddNode)
ocidBodyElement's addChild:(ocidHeaderElement)
#アーティクル
set ocidArticleElement to refMe's NSXMLElement's elementWithName:("article")
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("article")
ocidArticleElement's addAttribute:(ocidAddNode)
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_article")
ocidArticleElement's addAttribute:(ocidAddNode)
ocidBodyElement's addChild:(ocidArticleElement)
#フッター
set ocidFooterElement to refMe's NSXMLElement's elementWithName:("footer")
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("footer")
ocidFooterElement's addAttribute:(ocidAddNode)
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_footer")
ocidFooterElement's addAttribute:(ocidAddNode)
#リンク付与(不要なら削除可)
set ocidAElement to refMe's NSXMLElement's elementWithName:("a")
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("href") stringValue:("https://quicktimer.cocolog-nifty.com/"))
(ocidAElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("target") stringValue:("_blank"))
(ocidAElement's addAttribute:(ocidAddNode))
set strContents to ("AppleScriptで生成しました") as text
(ocidAElement's setStringValue:(strContents))
ocidFooterElement's addChild:(ocidAElement)
ocidBodyElement's addChild:(ocidFooterElement)

##############################
# TABLE コンテンツ部分生成開始
##############################
#テーブル部生成開始
set ocidTableElement to refMe's NSXMLElement's elementWithName:("table")
###【caption】
set ocidCaptionElement to refMe's NSXMLElement's elementWithName:("caption")
ocidCaptionElement's setStringValue:(strTitleText)
ocidTableElement's addChild:(ocidCaptionElement)
###【colgroup】
set ocidColgroupElement to refMe's NSXMLElement's elementWithName:("colgroup")
#テーブルのタイトル部
set listColName to {"行番号", "項目名", "値"} as list
#タイトル部の数だけ繰り返し
repeat with itemColName in listColName
  ###【col】col生成
  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("col"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
(ocidColgroupElement's addChild:(ocidAddElement))
end repeat
#テーブルエレメントに追加
ocidTableElement's addChild:(ocidColgroupElement)
###【thead】
set ocidTheadElement to refMe's NSXMLElement's elementWithName:("thead")
#TR
set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
#タイトル部の数だけ繰り返し
repeat with itemColName in listColName
  #ここはTDではなくてTHを利用
  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("th"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
  #値を入れる
(ocidAddElement's setStringValue:(itemColName))
  #TH→TRにセット
(ocidTrElement's addChild:(ocidAddElement))
end repeat
#TRをTHEADにセット
ocidTheadElement's addChild:(ocidTrElement)
#THEADをテーブルにセット
ocidTableElement's addChild:(ocidTheadElement)
###【tbody】
set ocidTbodyElement to refMe's NSXMLElement's elementWithName:("tbody")
#行番号
set numCntLineNo to 1 as integer
#ファイルのパスの数だけ繰り返し
repeat with itemKeyName in ocidAllKeySortedArray
  #TRの開始
  set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
  #【行番号】をTHでセット
  set strZeroSupp to ("00") as text
  set strZeroSupp to ("00" & numCntLineNo) as text
  set strLineNO to (text -3 through -1 of strZeroSupp) as text
  set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("行番号"))
(ocidThElement's addAttribute:(ocidAddNode))
(ocidThElement's setStringValue:(strLineNO))
(ocidTrElement's addChild:(ocidThElement))
  #【項目名=KEY名】をTDでセット
  set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("項目名"))
(ocidTdElement's setStringValue:(itemKeyName))
(ocidTdElement's addAttribute:(ocidAddNode))
  #TDをTRにセット
(ocidTrElement's addChild:(ocidTdElement))
  #【値=Value】TD
  #値の取得
  set ocidValue to (ocidJsonDict's valueForKey:(itemKeyName))
  set strValueClass to className() of ocidValue as text
  set strValue to "" as text
  if strValueClass contains "Array" then
    set strValue to (ocidValue's componentsJoinedByString:(", "))
  else
    set strValue to ocidValue as text
  end if
  #
  set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("値"))
(ocidTdElement's setStringValue:(strValue))
(ocidTdElement's addAttribute:(ocidAddNode))
  #TDをTRにセット
(ocidTrElement's addChild:(ocidTdElement))
  #出来上がったTRをTBODYにセット
(ocidTbodyElement's addChild:(ocidTrElement))
  #
  set numCntLineNo to (numCntLineNo + 1) as integer
end repeat
#TBODYをテーブルにセット
ocidTableElement's addChild:(ocidTbodyElement)
###【tfoot】 TRで
set ocidTfootElement to refMe's NSXMLElement's elementWithName:("tfoot")
set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
#項目数を取得して
set numCntCol to (count of listColName) as integer
#colspan指定して1行でセット
set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("テーブルの終わり"))
(ocidThElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("colspan") stringValue:(numCntCol as text))
(ocidThElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
(ocidThElement's addAttribute:(ocidAddNode))
#項目キーの数
set numCntKey to (count of ocidAllKeySortedArray) as integer
set strValue to ("メタデータの数は:" & numCntKey & " 件でした") as text
ocidThElement's setStringValue:(strValue)
#THをTRにセットして
ocidTrElement's addChild:(ocidThElement)
#TRをTFOOTにセット
ocidTfootElement's addChild:(ocidTrElement)
#TFOOTをテーブルにセット
ocidTableElement's addChild:(ocidTfootElement)
# 出来上がったテーブルをArticleエレメントにセット
ocidArticleElement's addChild:(ocidTableElement)
#ルートエレメントにセット
ocidRootElement's addChild:(ocidBodyElement)
##############################
# TABLE
##############################
#ROOTエレメントをXMLにセット
ocidXMLDoc's setRootElement:(ocidRootElement)
#読み取りやすい表示
set ocidXMLdata to ocidXMLDoc's XMLDataWithOptions:(refMe's NSXMLNodePrettyPrint)
#保存
set listDone to ocidXMLdata's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error|:(reference)

(*
####テキストエディタで開く
log strSaveFilePath
tell application "TextEdit"
activate
open (POSIX file strSaveFilePath as alias)
end tell
*)
####サファリで開く
set strOpenURL to ocidSaveFilePathURL's absoluteString() as text
tell application "Safari"
activate
make new document with properties {name:"JSON2HTMLv3"}
  tell window 1
open location strOpenURL
  end tell
end tell
####
set ocidContainerDirPathURL to ocidSaveFilePathURL's URLByDeletingLastPathComponent()
set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
set boolDone to appSharedWorkspace's openURL:(ocidContainerDirPathURL)


##############################
# 基本的なHTMLの構造
##############################
to doMakeRootElement(argStrTitleText)
  set strTitleText to argStrTitleText as text
  #
  set ocidRootElement to refMe's NSXMLElement's elementWithName:("html")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("lang") stringValue:("ja")
ocidRootElement's addAttribute:(ocidAddNode)
  #
  set ocidHeadElement to refMe's NSXMLElement's elementWithName:("head")
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("title")
ocidAddElement's setStringValue:(strTitleText)
ocidHeadElement's addChild:(ocidAddElement)
  # http-equiv
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/html; charset=UTF-8")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Style-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/css")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Script-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/javascript")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("name") stringValue:("viewport")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("width=720")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("style")
ocidAddElement's setStringValue:("body { margin: 10px; background-color: #FFFFFF; } table { border-spacing: 0; caption-side: top; font-family: system-ui; } thead th { border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:first-of-type { border-start-start-radius: .5em } &:last-of-type { border-start-end-radius: .5em; border-inline-end-width: 1px } } tbody td { word-wrap: break-word;max-width: 360px;border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:last-of-type { border-inline-end-width: 1px } } tbody th { border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; } tbody tr:nth-of-type(odd) { background: #F2F2F2; } .kind_string { font-size: 0.75em; } .date_string { font-size: 0.5em; } tfoot th { border: solid 1px #666666; padding: .5ch 1ch; &:first-of-type { border-end-start-radius: .5em } &:last-of-type { border-end-end-radius: .5em; border-inline-end-width: 1px } }")
ocidHeadElement's addChild:(ocidAddElement)
  #
ocidRootElement's addChild:(ocidHeadElement)
  #
return ocidRootElement
end doMakeRootElement


##############################
# exiftoolインストール
##############################
to doInstallBin()
  set strVerURL to ("https://exiftool.org/ver.txt") as text
  set strInstrallDirPath to ("~/bin/exiftool") as text
  ###インストール先
  set ocidInstrallDirPathStr to refMe's NSString's stringWithString:(strInstrallDirPath)
  set ocidInstrallDirPath to ocidInstrallDirPathStr's stringByStandardizingPath()
  set ocidInstrallDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidInstrallDirPath) isDirectory:true)
  ###フォルダを作る
  set appFileManager to refMe's NSFileManager's defaultManager()
  set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
  set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidInstrallDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
  set strInstrallDirPath to (ocidInstrallDirPathURL's |path|()) as text
  ###バージョンテキストURL
  set ocidVerURLStr to refMe's NSString's stringWithString:(strVerURL)
  set ocidVerURL to refMe's NSURL's alloc()'s initWithString:(ocidVerURLStr)
  set ocidVerText to refMe's NSString's stringWithContentsOfURL:(ocidVerURL) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
  set strVer to (item 1 of ocidVerText) as text
  ###URLとファイル名の整形
  set strDmgName to ("ExifTool-" & strVer & ".dmg") as text
  set strPkgName to ("ExifTool-" & strVer & ".pkg") as text
  set strVoluemPath to ("/Volumes/ExifTool-" & strVer & "") as text
  set strPkgPath to ("" & strVoluemPath & "/" & strPkgName & "/Contents/Archive.pax.gz") as text
  set strURL to ("https://exiftool.org/" & strDmgName & "") as text
  set ocidURLStr to refMe's NSString's stringWithString:(strURL)
  set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidURLStr)
  ###ダウンロードディレクトリ
  set appFileManager to refMe's NSFileManager's defaultManager()
  set ocidTempDirURL to appFileManager's temporaryDirectory()
  set ocidUUID to refMe's NSUUID's alloc()'s init()
  set ocidUUIDString to ocidUUID's UUIDString
  set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true
  ###フォルダを作る
  set appFileManager to refMe's NSFileManager's defaultManager()
  set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
  set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
  ###保存URL
  set ocidSaveDmgFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strDmgName)
  set strSaveDmgFilePathURL to (ocidSaveDmgFilePathURL's |path|()) as text
  ###ダウンロード
  set ocidOption to refMe's NSDataReadingMappedAlways
  set listDone to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error|:(reference)
  set ocidDmgData to (item 1 of listDone)
  ###保存
  set ocidOption to refMe's NSDataWritingAtomic
  set listDone to ocidDmgData's writeToURL:(ocidSaveDmgFilePathURL) options:(ocidOption) |error|:(reference)
log item 1 of listDone
  ####ディスクイメージマウント
strSaveDmgFilePathURL
  set strCommandText to ("/usr/bin/hdiutil attach \"" & strSaveDmgFilePathURL & "\" -noverify -nobrowse -noautoopen") as text
do shell script strCommandText
  ###解凍先ディレクトリを作成
  set ocidExpandPkgDirPathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:("Expand")
  set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
  set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidExpandPkgDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
  set strExpandPkgDirPathURL to (ocidExpandPkgDirPathURL's |path|()) as text
  ###解凍
  set strCoommandText to "/usr/bin/bsdtar -xzf \"" & strPkgPath & "\" -C \"" & strExpandPkgDirPathURL & "\"" as text
do shell script strCoommandText
  ###ディスクイメージアンマウンド
  set strCoommandText to "/usr/bin/hdiutil detach \"" & strVoluemPath & "\" -force" as text
do shell script strCoommandText
  ###ユーザーディレクトリにコピー
  set ocidDittoDirPathURL to ocidExpandPkgDirPathURL's URLByAppendingPathComponent:("usr/local/bin")
  set strDittoDirPathURL to (ocidDittoDirPathURL's |path|()) as text
  set strCoommandText to "/usr/bin/ditto \"" & strDittoDirPathURL & "\" \"" & strInstrallDirPath & "\"" as text
do shell script strCoommandText
end doInstallBin


|

[exiftool]Exif2HTMLv3 exiftoolのExif情報をHTMLで表示する(たいぶ修正)


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "UniformTypeIdentifiers"
use scripting additions

property refMe : a reference to current application
set appFileManager to refMe's NSFileManager's defaultManager()

########################################
### 設定項目
### exiftoolへのパス
########################################
#一般的にはパスはこちら
# set strExifPath to "/usr/local/bin/exiftool/exiftool" as text
#自分用
set strExifPath to "~/bin/exiftool/exiftool" as text


#exiftoolパス処理
set ocidExifPathStr to refMe's NSString's stringWithString:(strExifPath)
set ocidExifPath to ocidExifPathStr's stringByStandardizingPath()
set ocidExifPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidExifPath) isDirectory:false)
set strExifPath to ocidExifPathURL's |path| as text

########################################
####出力先/var/folders/XX/(再起動時に削除されます)
set ocidTemporaryDirPathURL to appFileManager's temporaryDirectory
set ocidVarFoldersDirURL to ocidTemporaryDirPathURL's URLByDeletingLastPathComponent()
set ocidTemporaryItemsPathURL to ocidVarFoldersDirURL's URLByAppendingPathComponent:"TemporaryItems"
##フォルダを作る
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listDone to appFileManager's createDirectoryAtURL:(ocidTemporaryItemsPathURL) withIntermediateDirectories:(true) attributes:(ocidAttrDict) |error|:(reference)
set aliasTemporaryItems to (ocidTemporaryItemsPathURL's absoluteURL()) as alias
########################################
#######ファイル選択
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
#ユーザーホームディレクトリ
set ocidHomeDirURL to appFileManager's homeDirectoryForCurrentUser()
#デスクトップの場合
set ocidDefaultLocationURL to ocidHomeDirURL's URLByAppendingPathComponent:("Desktop") isDirectory:true
#ダウンロードフォルダの場合
#set ocidDefaultLocationURL to ocidHomeDirURL's URLByAppendingPathComponent:("Downloads") isDirectory:true
#フォントフォルダの場合
#set ocidDefaultLocationURL to ocidHomeDirURL's URLByAppendingPathComponent:("Library/Fonts") isDirectory:true
#エイリアスパスにする
set aliasDefaultLocation to (ocidDefaultLocationURL's absoluteURL()) as alias
set listUTI to {"public.item"}
set strPromptText to "ファイルを選んでください" as text
set strMesText to "ファイルを選んでください" as text
set aliasFilePath to (choose file strMesText with prompt strPromptText default location (aliasDefaultLocation) of type listUTI with invisibles without multiple selections allowed and showing package contents) as alias
####入力ファイル関連
set strFilePath to POSIX path of aliasFilePath as text
###NSストリングに
set ocidFilePath to refMe's NSString's stringWithString:strFilePath
###NSURLに
set ocidFilePathURL to refMe's NSURL's fileURLWithPath:ocidFilePath
##ファイル名取得
set strFileName to (ocidFilePathURL's lastPathComponent) as text

########################################
######出力ファイル
##ファイル名
set strSaveFileName to (strFileName & ".html") as text
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
set aliasSaveFilePath to (choose file name with prompt "htmlのファイル名を付けてください" default name strSaveFileName default location aliasTemporaryItems) as «class furl»
#
set strSaveFilePath to (POSIX path of aliasSaveFilePath) as text
###NSストリングに
set ocidSaveFilePath to refMe's NSString's stringWithString:(strSaveFilePath)
###NSURLに
set ocidSaveFilePathURL to refMe's NSURL's fileURLWithPath:(ocidSaveFilePath)
##拡張子
set strFileExtension to (ocidSaveFilePathURL's pathExtension) as text
###拡張子つけ忘れ対策
if strFileExtension is not "html" then
  set strSaveFilePath to (POSIX path of aliasSaveFilePath & ".html") as text
end if
set strErrorFilePath to (strSaveFilePath & ".json") as text

########################################
###【1】データ取得 JSON出力
try
  set strCommandText to ("\"" & strExifPath & "\" -json \"" & strFilePath & "\"") as text
  set strResponseJosn to (do shell script strCommandText) as text
on error
  try
    set strCommandText to ("\"" & strExifPath & "\" -json \"" & strFilePath & "\" > \"" & strErrorFilePath & "\"") as text
    set strResponseJosn to (do shell script strCommandText) as text
  on error
    set strCommandText to ("/bin/cat \"" & strErrorFilePath & "\"") as text
    set strResponseJosn to (do shell script strCommandText) as text
log "たぶんexiftoolの非対応のファイルタイプですA"
  end try
end try
if strResponseJosn is "" then
return "たぶんexiftoolの非対応のファイルタイプですB"
end if
###【2】NSStringにテキストに格納して
set ocidReadDataJson to refMe's NSString's stringWithString:strResponseJosn
###【3】NSConcreteMutableDataに変換
set ocidReadDataUTF to ocidReadDataJson's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
###【4】NSInlineDataデータ初期化
set ocidReadData to (refMe's NSData's alloc()'s initWithData:(ocidReadDataUTF))
###【5】NSJSONSerialization
set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:ocidReadData options:0 |error|:(reference))
set ocidJsonData to (item 1 of listJSONSerialization)
-->(*__NSSingleObjectArrayI*)
####解説
(*
exiftoolの書き出すJSONはrootがArray構造から始まっているので
PlistにするにはDictに変換なりする必要がある
幸い『[{}]』といったシングルArray構造なので
Arrayから最初のOBJECTを取り出せばDICTレコード構造になる
*)
set ocidJsonDict to (ocidJsonData's firstObject())
-->(*__NSDictionaryI*)
###【6】レコードをNSDictionaryとして格納
set ocidJsonDict to (refMe's NSDictionary's alloc()'s initWithDictionary:ocidJsonDict)
#AllKeys
set ocidAllKeyArray to ocidJsonDict's allKeys()
#並び替えソート
set ocidAllKeySortedArray to ocidAllKeyArray's sortedArrayUsingSelector:("localizedStandardCompare:")

##############################
# XML 生成開始
##############################
#XML初期化
set ocidXMLDoc to refMe's NSXMLDocument's alloc()'s init()
ocidXMLDoc's setDocumentContentKind:(refMe's NSXMLDocumentHTMLKind)
# DTD付与
set ocidDTD to refMe's NSXMLDTD's alloc()'s init()
ocidDTD's setName:("html")
ocidXMLDoc's setDTD:(ocidDTD)
# XML主要部分を生成
set strTitleText to ("【ExifTool】: " & strFileName & " :メタデータ一覧") as text
set ocidRootElement to doMakeRootElement(strTitleText)
#ボディエレメント
set ocidBodyElement to refMe's NSXMLElement's elementWithName:("body")
#ヘッダー
set ocidHeaderElement to refMe's NSXMLElement's elementWithName:("header")
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("header")
ocidHeaderElement's addAttribute:(ocidAddNode)
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_header")
ocidHeaderElement's addAttribute:(ocidAddNode)
ocidBodyElement's addChild:(ocidHeaderElement)
#アーティクル
set ocidArticleElement to refMe's NSXMLElement's elementWithName:("article")
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("article")
ocidArticleElement's addAttribute:(ocidAddNode)
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_article")
ocidArticleElement's addAttribute:(ocidAddNode)
ocidBodyElement's addChild:(ocidArticleElement)
#フッター
set ocidFooterElement to refMe's NSXMLElement's elementWithName:("footer")
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("footer")
ocidFooterElement's addAttribute:(ocidAddNode)
set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_footer")
ocidFooterElement's addAttribute:(ocidAddNode)
#リンク付与(不要なら削除可)
set ocidAElement to refMe's NSXMLElement's elementWithName:("a")
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("href") stringValue:("https://quicktimer.cocolog-nifty.com/"))
(ocidAElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("target") stringValue:("_blank"))
(ocidAElement's addAttribute:(ocidAddNode))
set strContents to ("AppleScriptで生成しました") as text
(ocidAElement's setStringValue:(strContents))
ocidFooterElement's addChild:(ocidAElement)
ocidBodyElement's addChild:(ocidFooterElement)

##############################
# TABLE コンテンツ部分生成開始
##############################
#テーブル部生成開始
set ocidTableElement to refMe's NSXMLElement's elementWithName:("table")
###【caption】
set ocidCaptionElement to refMe's NSXMLElement's elementWithName:("caption")
ocidCaptionElement's setStringValue:(strTitleText)
ocidTableElement's addChild:(ocidCaptionElement)
###【colgroup】
set ocidColgroupElement to refMe's NSXMLElement's elementWithName:("colgroup")
#テーブルのタイトル部
set listColName to {"行番号", "項目名", "値"} as list
#タイトル部の数だけ繰り返し
repeat with itemColName in listColName
  ###【col】col生成
  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("col"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
(ocidColgroupElement's addChild:(ocidAddElement))
end repeat
#テーブルエレメントに追加
ocidTableElement's addChild:(ocidColgroupElement)
###【thead】
set ocidTheadElement to refMe's NSXMLElement's elementWithName:("thead")
#TR
set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
#タイトル部の数だけ繰り返し
repeat with itemColName in listColName
  #ここはTDではなくてTHを利用
  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("th"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
  #値を入れる
(ocidAddElement's setStringValue:(itemColName))
  #TH→TRにセット
(ocidTrElement's addChild:(ocidAddElement))
end repeat
#TRをTHEADにセット
ocidTheadElement's addChild:(ocidTrElement)
#THEADをテーブルにセット
ocidTableElement's addChild:(ocidTheadElement)
###【tbody】
set ocidTbodyElement to refMe's NSXMLElement's elementWithName:("tbody")
#行番号
set numCntLineNo to 1 as integer
#ファイルのパスの数だけ繰り返し
repeat with itemKeyName in ocidAllKeySortedArray
  #TRの開始
  set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
  #【行番号】をTHでセット
  set strZeroSupp to ("00") as text
  set strZeroSupp to ("00" & numCntLineNo) as text
  set strLineNO to (text -3 through -1 of strZeroSupp) as text
  set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("行番号"))
(ocidThElement's addAttribute:(ocidAddNode))
(ocidThElement's setStringValue:(strLineNO))
(ocidTrElement's addChild:(ocidThElement))
  #【項目名=KEY名】をTDでセット
  set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("項目名"))
(ocidTdElement's setStringValue:(itemKeyName))
(ocidTdElement's addAttribute:(ocidAddNode))
  #TDをTRにセット
(ocidTrElement's addChild:(ocidTdElement))
  #【値=Value】TD
  #値の取得
  set ocidValue to (ocidJsonDict's valueForKey:(itemKeyName))
  set strValueClass to className() of ocidValue as text
  set strValue to "" as text
  if strValueClass contains "Array" then
    set strValue to (ocidValue's componentsJoinedByString:(", "))
  else
    set strValue to ocidValue as text
  end if
  #
  set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("値"))
(ocidTdElement's setStringValue:(strValue))
(ocidTdElement's addAttribute:(ocidAddNode))
  #TDをTRにセット
(ocidTrElement's addChild:(ocidTdElement))
  #出来上がったTRをTBODYにセット
(ocidTbodyElement's addChild:(ocidTrElement))
  #
  set numCntLineNo to (numCntLineNo + 1) as integer
end repeat
#TBODYをテーブルにセット
ocidTableElement's addChild:(ocidTbodyElement)
###【tfoot】 TRで
set ocidTfootElement to refMe's NSXMLElement's elementWithName:("tfoot")
set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
#項目数を取得して
set numCntCol to (count of listColName) as integer
#colspan指定して1行でセット
set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("テーブルの終わり"))
(ocidThElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("colspan") stringValue:(numCntCol as text))
(ocidThElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
(ocidThElement's addAttribute:(ocidAddNode))
#項目キーの数
set numCntKey to (count of ocidAllKeySortedArray) as integer
set strValue to ("メタデータの数は:" & numCntKey & " 件でした") as text
ocidThElement's setStringValue:(strValue)
#THをTRにセットして
ocidTrElement's addChild:(ocidThElement)
#TRをTFOOTにセット
ocidTfootElement's addChild:(ocidTrElement)
#TFOOTをテーブルにセット
ocidTableElement's addChild:(ocidTfootElement)
# 出来上がったテーブルをArticleエレメントにセット
ocidArticleElement's addChild:(ocidTableElement)
#ルートエレメントにセット
ocidRootElement's addChild:(ocidBodyElement)
##############################
# TABLE
##############################
#ROOTエレメントをXMLにセット
ocidXMLDoc's setRootElement:(ocidRootElement)
#読み取りやすい表示
set ocidXMLdata to ocidXMLDoc's XMLDataWithOptions:(refMe's NSXMLNodePrettyPrint)
#保存
set listDone to ocidXMLdata's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error|:(reference)

(*
####テキストエディタで開く
log strSaveFilePath
tell application "TextEdit"
activate
open (POSIX file strSaveFilePath as alias)
end tell
*)
####サファリで開く
set strOpenURL to ocidSaveFilePathURL's absoluteString() as text
tell application "Safari"
activate
make new document with properties {name:"JSON2HTMLv3"}
  tell window 1
open location strOpenURL
  end tell
end tell
####
set ocidContainerDirPathURL to ocidSaveFilePathURL's URLByDeletingLastPathComponent()
set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
set boolDone to appSharedWorkspace's openURL:(ocidContainerDirPathURL)


##############################
# 基本的なHTMLの構造
##############################
to doMakeRootElement(argStrTitleText)
  set strTitleText to argStrTitleText as text
  #
  set ocidRootElement to refMe's NSXMLElement's elementWithName:("html")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("lang") stringValue:("ja")
ocidRootElement's addAttribute:(ocidAddNode)
  #
  set ocidHeadElement to refMe's NSXMLElement's elementWithName:("head")
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("title")
ocidAddElement's setStringValue:(strTitleText)
ocidHeadElement's addChild:(ocidAddElement)
  # http-equiv
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/html; charset=UTF-8")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Style-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/css")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Script-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/javascript")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("name") stringValue:("viewport")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("width=720")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("style")
ocidAddElement's setStringValue:("body { margin: 10px; background-color: #FFFFFF; } table { border-spacing: 0; caption-side: top; font-family: system-ui; } thead th { border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:first-of-type { border-start-start-radius: .5em } &:last-of-type { border-start-end-radius: .5em; border-inline-end-width: 1px } } tbody td { word-wrap: break-word;max-width: 360px;border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:last-of-type { border-inline-end-width: 1px } } tbody th { border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; } tbody tr:nth-of-type(odd) { background: #F2F2F2; } .kind_string { font-size: 0.75em; } .date_string { font-size: 0.5em; } tfoot th { border: solid 1px #666666; padding: .5ch 1ch; &:first-of-type { border-end-start-radius: .5em } &:last-of-type { border-end-end-radius: .5em; border-inline-end-width: 1px } }")
ocidHeadElement's addChild:(ocidAddElement)
  #
ocidRootElement's addChild:(ocidHeadElement)
  #
return ocidRootElement
end doMakeRootElement

|

フォルダ内のファイルリストをHTMLで作成する(最下層まで)画像のCMYK判定修正


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKIt"
use framework "UniformTypeIdentifiers"
use scripting additions
property refMe : a reference to current application


###Wクリックで起動した場合
on run
  ###ダイアログを前面に出す
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  ##デフォルト=デスクトップ
  set appFileManager to refMe's NSFileManager's defaultManager()
  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
  set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
  set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
  set strPromptText to "フォルダをえらんでください"
  set strMesText to "フォルダをえらんでください"
  try
    set aliasDirPath to (choose folder strMesText with prompt strPromptText default location aliasDesktopDirPath with invisibles and showing package contents without multiple selections allowed) as alias
  on error
log "エラーしました"
return "エラーしました"
  end try
open aliasDirPath
end run


on open aliasDirPath
  ##パス
  set aliasDirPath to aliasDirPath as alias
  set strDirPath to (POSIX path of aliasDirPath) as text
  set ocidDirPathStr to refMe's NSString's stringWithString:(strDirPath)
  set ocidDirPath to ocidDirPathStr's stringByStandardizingPath()
  set ocidDirPathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidDirPath)
  set strDirPathURL to ocidDirPathURL's absoluteString() as text
  ##フォルダ判定
  set listBoole to (ocidDirPathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsDirectoryKey) |error|:(reference))
  set boolIsDir to (item 2 of listBoole) as boolean
  if boolIsDir is false then
return "フォルダ以外です処理を終了します"
  end if
  ##フォルダ名→保存先HTMLパス
  set ocidDirName to ocidDirPathURL's lastPathComponent()
  set ocidSaveFileName to refMe's NSMutableString's alloc()'s initWithCapacity:0
ocidSaveFileName's appendString:("_ファイルリスト")
ocidSaveFileName's appendString:(ocidDirName)
  set ocidBaseFilePathURL to ocidDirPathURL's URLByAppendingPathComponent:(ocidSaveFileName)
  set ocidSaveFilePathURL to ocidBaseFilePathURL's URLByAppendingPathExtension:("html")
  
  ##ファイルの各種プロパティを取得
  set appFileManager to refMe's NSFileManager's defaultManager()
  set ocidOption to refMe's NSDirectoryEnumerationSkipsHiddenFiles
  set ocidPropertieArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
ocidPropertieArray's addObject:(refMe's NSURLPathKey)
ocidPropertieArray's addObject:(refMe's NSURLFileSizeKey)
ocidPropertieArray's addObject:(refMe's NSURLCreationDateKey)
ocidPropertieArray's addObject:(refMe's NSURLContentModificationDateKey)
ocidPropertieArray's addObject:(refMe's NSURLNameKey)
ocidPropertieArray's addObject:(refMe's NSURLContentTypeKey)
ocidPropertieArray's addObject:(refMe's NSURLFileAllocatedSizeKey)
ocidPropertieArray's addObject:(refMe's NSURLIsRegularFileKey)
  ########################################
  ##コンテンツの収集 A 第一階層のみの場合
  ########################################
  (*
set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidDirPathURL) includingPropertiesForKeys:(ocidPropertieArray) options:(ocidOption) |error|:(reference))
set ocidFilePathURLArray to item 1 of listResponse
#パスリストをファイル名でソート並び替え
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("lastPathComponent") ascending:(yes) selector:("localizedStandardCompare:")
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidFilePathURLArray's sortedArrayUsingDescriptors:(ocidDescriptorArray)
*)
  ########################################
  ##コンテンツの収集 B 最下層までの場合
  ########################################
  set ocidEmuDict to appFileManager's enumeratorAtURL:(ocidDirPathURL) includingPropertiesForKeys:(ocidPropertieArray) options:(ocidOption) errorHandler:(reference)
  set ocidEmuFileURLArray to ocidEmuDict's allObjects()
  set ocidFilePathURLAllArray to (refMe's NSMutableArray's alloc()'s initWithCapacity:0)
ocidFilePathURLAllArray's addObjectsFromArray:(ocidEmuFileURLArray)
  #
  set ocidFilePathURLArray to (refMe's NSMutableArray's alloc()'s initWithCapacity:0)
  repeat with itemFilePathURL in ocidFilePathURLAllArray
    set listResult to (itemFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsRegularFileKey) |error|:(reference))
    set boolIsRegularFileKey to item 2 of listResult
    if boolIsRegularFileKey is (refMe's NSNumber's numberWithBool:true) then
      ####リストにする
(ocidFilePathURLArray's addObject:(itemFilePathURL))
    end if
  end repeat
  #パスリストをファイル名でソート並び替え absoluteString localizedStandardCompare
  set ocidDescriptor to (refMe's NSSortDescriptor's sortDescriptorWithKey:"path" ascending:(true) selector:"localizedStandardCompare:")
  set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
  set ocidSortedArray to ocidFilePathURLArray's sortedArrayUsingDescriptors:(ocidDescriptorArray)
  
  ##############################
  # XML 生成開始
  ##############################
  #XML初期化
  set ocidXMLDoc to refMe's NSXMLDocument's alloc()'s init()
ocidXMLDoc's setDocumentContentKind:(refMe's NSXMLDocumentHTMLKind)
  # DTD付与
  set ocidDTD to refMe's NSXMLDTD's alloc()'s init()
ocidDTD's setName:("html")
ocidXMLDoc's setDTD:(ocidDTD)
  # XML主要部分を生成
  set ocidRootElement to doMakeRootElement()
  #ボディエレメント
  set ocidBodyElement to refMe's NSXMLElement's elementWithName:("body")
  #ヘッダー
  set ocidHeaderElement to refMe's NSXMLElement's elementWithName:("header")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("header")
ocidHeaderElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_header")
ocidHeaderElement's addAttribute:(ocidAddNode)
ocidBodyElement's addChild:(ocidHeaderElement)
  #アーティクル
  set ocidArticleElement to refMe's NSXMLElement's elementWithName:("article")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("article")
ocidArticleElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_article")
ocidArticleElement's addAttribute:(ocidAddNode)
ocidBodyElement's addChild:(ocidArticleElement)
  #フッター
  set ocidFooterElement to refMe's NSXMLElement's elementWithName:("footer")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("footer")
ocidFooterElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_footer")
ocidFooterElement's addAttribute:(ocidAddNode)
  #リンク付与(不要なら削除可)
  set ocidAElement to refMe's NSXMLElement's elementWithName:("a")
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("href") stringValue:("https://quicktimer.cocolog-nifty.com/"))
(ocidAElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("target") stringValue:("_blank"))
(ocidAElement's addAttribute:(ocidAddNode))
  set strContents to ("AppleScriptで生成しました") as text
(ocidAElement's setStringValue:(strContents))
ocidFooterElement's addChild:(ocidAElement)
ocidBodyElement's addChild:(ocidFooterElement)
  ##############################
  # TABLE コンテンツ部分生成開始
  ##############################
  #テーブル部生成開始
  set ocidTableElement to refMe's NSXMLElement's elementWithName:("table")
  #【caption】
  set ocidCaptionElement to refMe's NSXMLElement's elementWithName:("caption")
ocidCaptionElement's setStringValue:("【ファイルリスト】: 行番号に※表示はCMYKデータ(PDFを除く)")
ocidTableElement's addChild:(ocidCaptionElement)
  #【colgroup】
  set ocidColgroupElement to refMe's NSXMLElement's elementWithName:("colgroup")
  #テーブルのタイトル部
  set listColName to {"行番号", "ファイル名", "サイズ", "種類", "作成日", "修正日"} as list
  #タイトル部の数だけ繰り返し
  repeat with itemColName in listColName
    #【col】col生成
    set ocidAddElement to (refMe's NSXMLElement's elementWithName:("col"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
(ocidColgroupElement's addChild:(ocidAddElement))
  end repeat
  #テーブルエレメントに追加
ocidTableElement's addChild:(ocidColgroupElement)
  #【thead】
  set ocidTheadElement to refMe's NSXMLElement's elementWithName:("thead")
  #TR
  set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
  #タイトル部の数だけ繰り返し
  repeat with itemColName in listColName
    #ここはTDではなくてTHを利用
    set ocidAddElement to (refMe's NSXMLElement's elementWithName:("th"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
    #値を入れる
(ocidAddElement's setStringValue:(itemColName))
    #TH→TRにセット
(ocidTrElement's addChild:(ocidAddElement))
  end repeat
  #TRをTHEADにセット
ocidTheadElement's addChild:(ocidTrElement)
  #THEADをテーブルにセット
ocidTableElement's addChild:(ocidTheadElement)
  #【tbody】
  set ocidTbodyElement to refMe's NSXMLElement's elementWithName:("tbody")
  #行番号
  set numCntLineNo to 1 as integer
  #合計ファイルサイズ用
  set numAllFileSize to 0 as integer
  #ファイルのパスの数だけ繰り返し
  repeat with itemFilePathURL in ocidSortedArray
    ##UTIを求めて
    set listResourceValue to (itemFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLContentTypeKey) |error|:(reference))
    set ocidContentType to (item 2 of listResourceValue)
    set strUTI to (ocidContentType's identifier) as text
    set strUTILIST to "public.jpeg, com.adobe.photoshop-image,public.tiff,com.adobe.pd" as text
    if strUTILIST contains strUTI then
log "CMYKチェック対象ファイル"
      set ocidReadImage to (refMe's NSImage's alloc()'s initWithContentsOfURL:(itemFilePathURL))
      set ocidImageRepArray to ocidReadImage's representations()
      set ocidImageRep to ocidImageRepArray's firstObject()
      set ocidColorSpace to ocidImageRep's colorSpace()
      #シンプルにコンポーネント番号で判定する場合
      # 1 = GS 3=RGB 4=CMYK
      set numColorCompNo to ocidColorSpace's numberOfColorComponents as integer
      #colorSpaceModelで判定したい場合
      # set ocidColorModel to ocidColorSpace's colorSpaceModel()
      # if ocidColorModel = (refMe's NSColorSpaceModelCMYK) then
log numColorCompNo
      if numColorCompNo = 4 then
log "CMYYKデータです"
        set ocidReadImage to (missing value)
        set ocidImageRep to (missing value)
        set boolCMYK to true as boolean
      else
        set boolCMYK to false as boolean
      end if
    else
      set boolCMYK to false as boolean
    end if
    ##
    #ファイルのリソースを取得
    set listResponse to (itemFilePathURL's resourceValuesForKeys:(ocidPropertieArray) |error|:(reference))
    set ocidValueDict to (item 1 of listResponse)
    #TRの開始
    set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
    #【行番号】をTHでセット
    set strZeroSupp to ("00") as text
    set strZeroSupp to ("00" & numCntLineNo) as text
    set strLineNO to (text -3 through -1 of strZeroSupp) as text
    set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("行番号"))
(ocidThElement's addAttribute:(ocidAddNode))
    if boolCMYK is true then
      set strSetLineNO to (strLineNO & "*") as text
    else if boolCMYK is false then
      set strSetLineNO to (strLineNO) as text
    end if
(ocidThElement's setStringValue:(strSetLineNO))
(ocidTrElement's addChild:(ocidThElement))
    #【ファイル名】をTDでセット
    set ocidValue to (ocidValueDict's valueForKey:(refMe's NSURLNameKey))
    set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("ファイル名"))
(ocidTdElement's addAttribute:(ocidAddNode))
    ####
    set itemFilePath to itemFilePathURL's |path|
    set ocidRange to (itemFilePath's rangeOfString:(ocidDirPath))
    set numLength to (|length| of ocidRange) + 1 as integer
    set ocidRlativePath to (itemFilePath's substringFromIndex:(numLength))
    
    #↑のTDの内容=ファイル名にリンクを付与
    set ocidAElement to (refMe's NSXMLElement's elementWithName:("a"))
    set strHref to ("./" & ocidRlativePath) as text
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("href") stringValue:(strHref))
(ocidAElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("target") stringValue:("_blank"))
(ocidAElement's addAttribute:(ocidAddNode))
    set strHref to (ocidRlativePath) as text
(ocidAElement's setStringValue:(strHref))
    #リンクをTDにセット
(ocidTdElement's addChild:(ocidAElement))
    #TDをTRにセット
(ocidTrElement's addChild:(ocidTdElement))
    #【ファイルサイズ】TD
    set ocidValue to (ocidValueDict's valueForKey:(refMe's NSURLFileSizeKey))
    #ファイルサイズの合計に加算
    set numAllFileSize to (numAllFileSize + (ocidValue as integer))
    set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("ファイルサイズ"))
(ocidTdElement's addAttribute:(ocidAddNode))
    #単位による分岐
    set numFileSize to ocidValue as integer
    if (numFileSize) < 102400 then
      set numValue to (numFileSize / 1024) as integer
      set strValue to numValue & " kb" as text
    else if (numFileSize) > (10240 * 100000) then
      set numValue to (numFileSize / (1024 * 1000000))
      set ocidFormatter to refMe's NSNumberFormatter's alloc()'s init()
(ocidFormatter's setNumberStyle:(refMe's NSNumberFormatterDecimalStyle))
(ocidFormatter's setMinimumFractionDigits:(2))
(ocidFormatter's setMaximumFractionDigits:(2))
      set strValue to (ocidFormatter's stringFromNumber:(numValue)) as text
      set strValue to strValue & " gb" as text
    else
      set numValue to (numFileSize / (1024 * 1000))
      set ocidFormatter to refMe's NSNumberFormatter's alloc()'s init()
(ocidFormatter's setNumberStyle:(refMe's NSNumberFormatterDecimalStyle))
(ocidFormatter's setMinimumFractionDigits:(2))
(ocidFormatter's setMaximumFractionDigits:(2))
      set strValue to (ocidFormatter's stringFromNumber:(numValue)) as text
      set strValue to strValue & " mb" as text
    end if
(ocidTdElement's setStringValue:(strValue))
(ocidTrElement's addChild:(ocidTdElement))
    #【種類】TDでセット
    set ocidValue to (ocidValueDict's valueForKey:(refMe's NSURLContentTypeKey))'s localizedDescription()
    set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("種類"))
(ocidTdElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("class") stringValue:("kind_string"))
(ocidTdElement's addAttribute:(ocidAddNode))
(ocidTdElement's setStringValue:(ocidValue))
(ocidTrElement's addChild:(ocidTdElement))
    #【作成日】TDでセット
    set ocidValue to (ocidValueDict's valueForKey:(refMe's NSURLCreationDateKey))
    set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("作成"))
(ocidTdElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("class") stringValue:("date_string"))
(ocidTdElement's addAttribute:(ocidAddNode))
    set strDate to (ocidValue as date) as text
(ocidTdElement's setStringValue:(strDate))
(ocidTrElement's addChild:(ocidTdElement))
    #【修正日】TDでセット
    set ocidValue to (ocidValueDict's valueForKey:(refMe's NSURLContentModificationDateKey))
    set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("修正日"))
(ocidTdElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("class") stringValue:("date_string"))
(ocidTdElement's addAttribute:(ocidAddNode))
    set strDate to (ocidValue as date) as text
(ocidTdElement's setStringValue:(strDate))
(ocidTrElement's addChild:(ocidTdElement))
    #出来上がったTRをTBODYにセット
(ocidTbodyElement's addChild:(ocidTrElement))
    #項目番号のカウントアップ
    set numCntLineNo to (numCntLineNo + 1) as integer
  end repeat
  #TBODYをテーブルにセット
ocidTableElement's addChild:(ocidTbodyElement)
  #【tfoot】 TRで
  set ocidTfootElement to refMe's NSXMLElement's elementWithName:("tfoot")
  set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
  #項目数を取得して
  set numCntCol to (count of listColName) as integer
  #colspan指定して1行でセット
  set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("テーブルの終わり"))
(ocidThElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("colspan") stringValue:(numCntCol as text))
(ocidThElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
(ocidThElement's addAttribute:(ocidAddNode))
  #
  if (numAllFileSize) < 102400 then
    set numValue to (numAllFileSize / 1024) as integer
    set strValue to "フォルダ合計:" & numValue & " kb" as text
  else if (numAllFileSize) > (10240 * 100000) then
    set numValue to (numAllFileSize / (10240 * 100000))
    set ocidFormatter to refMe's NSNumberFormatter's alloc()'s init()
(ocidFormatter's setNumberStyle:(refMe's NSNumberFormatterDecimalStyle))
(ocidFormatter's setMinimumFractionDigits:(2))
(ocidFormatter's setMaximumFractionDigits:(2))
    set strValue to (ocidFormatter's stringFromNumber:(numValue)) as text
    set strValue to "フォルダ合計:" & strValue & " gb" as text
  else
    set numValue to (numAllFileSize / 1024000) as integer
    set strValue to "フォルダ合計:" & numValue & " mb" as text
  end if
ocidThElement's setStringValue:(strValue)
  
  #THをTRにセットして
ocidTrElement's addChild:(ocidThElement)
  #TRをTFOOTにセット
ocidTfootElement's addChild:(ocidTrElement)
  #TFOOTをテーブルにセット
ocidTableElement's addChild:(ocidTfootElement)
  # 出来上がったテーブルをArticleエレメントにセット
ocidArticleElement's addChild:(ocidTableElement)
  #
ocidRootElement's addChild:(ocidBodyElement)
  ##############################
  # TABLE
  ##############################
  #ROOTエレメントをXMLにセット
ocidXMLDoc's setRootElement:(ocidRootElement)
  #読み取りやすい表示
  set ocidXMLdata to ocidXMLDoc's XMLDataWithOptions:(refMe's NSXMLNodePrettyPrint)
  #保存
  set listDone to ocidXMLdata's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error|:(reference)
  set ocidSaveFilePath to ocidSaveFilePathURL's |path|
  set ocidContainerDirPathURL to ocidSaveFilePathURL's URLByDeletingLastPathComponent()
  set ocidContainerDirPath to ocidContainerDirPathURL's |path|
  set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
  set boolDone to appSharedWorkspace's selectFile:(ocidSaveFilePath) inFileViewerRootedAtPath:(ocidContainerDirPath)
  set boolDone to appSharedWorkspace's openURL:(ocidSaveFilePathURL)
  if (boolDone as boolean) is false then
    #ファイルを開く
    set aliasSaveFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
    tell application "Finder"
open file aliasSaveFilePath
    end tell
  end if
  ##処理終了
return "処理終了"
end open
##############################
# 基本的なHTMLの構造
##############################
to doMakeRootElement()
  #
  set ocidRootElement to refMe's NSXMLElement's elementWithName:("html")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("lang") stringValue:("ja")
ocidRootElement's addAttribute:(ocidAddNode)
  #
  set ocidHeadElement to refMe's NSXMLElement's elementWithName:("head")
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("title")
ocidAddElement's setStringValue:("ファイル一覧")
ocidHeadElement's addChild:(ocidAddElement)
  # http-equiv
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/html; charset=UTF-8")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Style-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/css")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Script-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/javascript")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("name") stringValue:("viewport")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("width=720")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("style")
ocidAddElement's setStringValue:("body { margin: 10px; background-color: #FFFFFF; } table { border-spacing: 0; caption-side: top; font-family: system-ui; } thead th { border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:first-of-type { border-start-start-radius: .5em } &:last-of-type { border-start-end-radius: .5em; border-inline-end-width: 1px } } tbody td { word-wrap: break-word;max-width: 360px;border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:last-of-type { border-inline-end-width: 1px } } tbody th { border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; } tbody tr:nth-of-type(odd) { background: #F2F2F2; } .kind_string { font-size: 0.75em; } .date_string { font-size: 0.5em; } tfoot th { border: solid 1px #666666; padding: .5ch 1ch; &:first-of-type { border-end-start-radius: .5em } &:last-of-type { border-end-end-radius: .5em; border-inline-end-width: 1px } }")
ocidHeadElement's addChild:(ocidAddElement)
  #
ocidRootElement's addChild:(ocidHeadElement)
  #
return ocidRootElement
end doMakeRootElement

|

フォルダ内のファイルリストをHTMLで作成する(最下層まで)ファイルサイズ計算部修正


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKIt"
use framework "UniformTypeIdentifiers"
use scripting additions
property refMe : a reference to current application


###Wクリックで起動した場合
on run
  ###ダイアログを前面に出す
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  ##デフォルト=デスクトップ
  set appFileManager to refMe's NSFileManager's defaultManager()
  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
  set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
  set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
  set strPromptText to "フォルダをえらんでください"
  set strMesText to "フォルダをえらんでください"
  try
    set aliasDirPath to (choose folder strMesText with prompt strPromptText default location aliasDesktopDirPath with invisibles and showing package contents without multiple selections allowed) as alias
  on error
log "エラーしました"
return "エラーしました"
  end try
open aliasDirPath
end run


on open aliasDirPath
  ##パス
  set aliasDirPath to aliasDirPath as alias
  set strDirPath to (POSIX path of aliasDirPath) as text
  set ocidDirPathStr to refMe's NSString's stringWithString:(strDirPath)
  set ocidDirPath to ocidDirPathStr's stringByStandardizingPath()
  set ocidDirPathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidDirPath)
  set strDirPathURL to ocidDirPathURL's absoluteString() as text
  ##フォルダ判定
  set listBoole to (ocidDirPathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsDirectoryKey) |error|:(reference))
  set boolIsDir to (item 2 of listBoole) as boolean
  if boolIsDir is false then
return "フォルダ以外です処理を終了します"
  end if
  ##フォルダ名→保存先HTMLパス
  set ocidDirName to ocidDirPathURL's lastPathComponent()
  set ocidSaveFileName to refMe's NSMutableString's alloc()'s initWithCapacity:0
ocidSaveFileName's appendString:("_ファイルリスト")
ocidSaveFileName's appendString:(ocidDirName)
  set ocidBaseFilePathURL to ocidDirPathURL's URLByAppendingPathComponent:(ocidSaveFileName)
  set ocidSaveFilePathURL to ocidBaseFilePathURL's URLByAppendingPathExtension:("html")
  
  ##ファイルの各種プロパティを取得
  set appFileManager to refMe's NSFileManager's defaultManager()
  set ocidOption to refMe's NSDirectoryEnumerationSkipsHiddenFiles
  set ocidPropertieArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
ocidPropertieArray's addObject:(refMe's NSURLPathKey)
ocidPropertieArray's addObject:(refMe's NSURLFileSizeKey)
ocidPropertieArray's addObject:(refMe's NSURLCreationDateKey)
ocidPropertieArray's addObject:(refMe's NSURLContentModificationDateKey)
ocidPropertieArray's addObject:(refMe's NSURLNameKey)
ocidPropertieArray's addObject:(refMe's NSURLContentTypeKey)
ocidPropertieArray's addObject:(refMe's NSURLFileAllocatedSizeKey)
ocidPropertieArray's addObject:(refMe's NSURLIsRegularFileKey)
  ########################################
  ##コンテンツの収集 A 第一階層のみの場合
  ########################################
  (*
set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidDirPathURL) includingPropertiesForKeys:(ocidPropertieArray) options:(ocidOption) |error|:(reference))
set ocidFilePathURLArray to item 1 of listResponse
#パスリストをファイル名でソート並び替え
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("lastPathComponent") ascending:(yes) selector:("localizedStandardCompare:")
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidFilePathURLArray's sortedArrayUsingDescriptors:(ocidDescriptorArray)
*)
  ########################################
  ##コンテンツの収集 B 最下層までの場合
  ########################################
  set ocidEmuDict to appFileManager's enumeratorAtURL:(ocidDirPathURL) includingPropertiesForKeys:(ocidPropertieArray) options:(ocidOption) errorHandler:(reference)
  set ocidEmuFileURLArray to ocidEmuDict's allObjects()
  set ocidFilePathURLAllArray to (refMe's NSMutableArray's alloc()'s initWithCapacity:0)
ocidFilePathURLAllArray's addObjectsFromArray:(ocidEmuFileURLArray)
  #
  set ocidFilePathURLArray to (refMe's NSMutableArray's alloc()'s initWithCapacity:0)
  repeat with itemFilePathURL in ocidFilePathURLAllArray
    set listResult to (itemFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsRegularFileKey) |error|:(reference))
    set boolIsRegularFileKey to item 2 of listResult
    if boolIsRegularFileKey is (refMe's NSNumber's numberWithBool:true) then
      ####リストにする
(ocidFilePathURLArray's addObject:(itemFilePathURL))
    end if
  end repeat
  #パスリストをファイル名でソート並び替え absoluteString localizedStandardCompare
  set ocidDescriptor to (refMe's NSSortDescriptor's sortDescriptorWithKey:"path" ascending:(true) selector:"localizedStandardCompare:")
  set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
  set ocidSortedArray to ocidFilePathURLArray's sortedArrayUsingDescriptors:(ocidDescriptorArray)
  
  ##############################
  # XML 生成開始
  ##############################
  #XML初期化
  set ocidXMLDoc to refMe's NSXMLDocument's alloc()'s init()
ocidXMLDoc's setDocumentContentKind:(refMe's NSXMLDocumentHTMLKind)
  # DTD付与
  set ocidDTD to refMe's NSXMLDTD's alloc()'s init()
ocidDTD's setName:("html")
ocidXMLDoc's setDTD:(ocidDTD)
  # XML主要部分を生成
  set ocidRootElement to doMakeRootElement()
  #ボディエレメント
  set ocidBodyElement to refMe's NSXMLElement's elementWithName:("body")
  #ヘッダー
  set ocidHeaderElement to refMe's NSXMLElement's elementWithName:("header")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("header")
ocidHeaderElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_header")
ocidHeaderElement's addAttribute:(ocidAddNode)
ocidBodyElement's addChild:(ocidHeaderElement)
  #アーティクル
  set ocidArticleElement to refMe's NSXMLElement's elementWithName:("article")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("article")
ocidArticleElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_article")
ocidArticleElement's addAttribute:(ocidAddNode)
ocidBodyElement's addChild:(ocidArticleElement)
  #フッター
  set ocidFooterElement to refMe's NSXMLElement's elementWithName:("footer")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("footer")
ocidFooterElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_footer")
ocidFooterElement's addAttribute:(ocidAddNode)
  #リンク付与(不要なら削除可)
  set ocidAElement to refMe's NSXMLElement's elementWithName:("a")
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("href") stringValue:("https://quicktimer.cocolog-nifty.com/"))
(ocidAElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("target") stringValue:("_blank"))
(ocidAElement's addAttribute:(ocidAddNode))
  set strContents to ("AppleScriptで生成しました") as text
(ocidAElement's setStringValue:(strContents))
ocidFooterElement's addChild:(ocidAElement)
ocidBodyElement's addChild:(ocidFooterElement)
  ##############################
  # TABLE コンテンツ部分生成開始
  ##############################
  #テーブル部生成開始
  set ocidTableElement to refMe's NSXMLElement's elementWithName:("table")
  #【caption】
  set ocidCaptionElement to refMe's NSXMLElement's elementWithName:("caption")
ocidCaptionElement's setStringValue:("【ファイルリスト】: ")
ocidTableElement's addChild:(ocidCaptionElement)
  #【colgroup】
  set ocidColgroupElement to refMe's NSXMLElement's elementWithName:("colgroup")
  #テーブルのタイトル部
  set listColName to {"行番号", "ファイル名", "サイズ", "種類", "作成日", "修正日"} as list
  #タイトル部の数だけ繰り返し
  repeat with itemColName in listColName
    #【col】col生成
    set ocidAddElement to (refMe's NSXMLElement's elementWithName:("col"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
(ocidColgroupElement's addChild:(ocidAddElement))
  end repeat
  #テーブルエレメントに追加
ocidTableElement's addChild:(ocidColgroupElement)
  #【thead】
  set ocidTheadElement to refMe's NSXMLElement's elementWithName:("thead")
  #TR
  set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
  #タイトル部の数だけ繰り返し
  repeat with itemColName in listColName
    #ここはTDではなくてTHを利用
    set ocidAddElement to (refMe's NSXMLElement's elementWithName:("th"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
    #値を入れる
(ocidAddElement's setStringValue:(itemColName))
    #TH→TRにセット
(ocidTrElement's addChild:(ocidAddElement))
  end repeat
  #TRをTHEADにセット
ocidTheadElement's addChild:(ocidTrElement)
  #THEADをテーブルにセット
ocidTableElement's addChild:(ocidTheadElement)
  #【tbody】
  set ocidTbodyElement to refMe's NSXMLElement's elementWithName:("tbody")
  #行番号
  set numCntLineNo to 1 as integer
  #合計ファイルサイズ用
  set numAllFileSize to 0 as integer
  #ファイルのパスの数だけ繰り返し
  repeat with itemFilePathURL in ocidSortedArray
    #ファイルのリソースを取得
    set listResponse to (itemFilePathURL's resourceValuesForKeys:(ocidPropertieArray) |error|:(reference))
    set ocidValueDict to (item 1 of listResponse)
    #TRの開始
    set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
    #【行番号】をTHでセット
    set strZeroSupp to ("00") as text
    set strZeroSupp to ("00" & numCntLineNo) as text
    set strLineNO to (text -3 through -1 of strZeroSupp) as text
    set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("行番号"))
(ocidThElement's addAttribute:(ocidAddNode))
(ocidThElement's setStringValue:(strLineNO))
(ocidTrElement's addChild:(ocidThElement))
    #【ファイル名】をTDでセット
    set ocidValue to (ocidValueDict's valueForKey:(refMe's NSURLNameKey))
    set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("ファイル名"))
(ocidTdElement's addAttribute:(ocidAddNode))
    ####
    set itemFilePath to itemFilePathURL's |path|
    set ocidRange to (itemFilePath's rangeOfString:(ocidDirPath))
    set numLength to (|length| of ocidRange) + 1 as integer
    set ocidRlativePath to (itemFilePath's substringFromIndex:(numLength))
    
    #↑のTDの内容=ファイル名にリンクを付与
    set ocidAElement to (refMe's NSXMLElement's elementWithName:("a"))
    set strHref to ("./" & ocidRlativePath) as text
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("href") stringValue:(strHref))
(ocidAElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("target") stringValue:("_blank"))
(ocidAElement's addAttribute:(ocidAddNode))
    set strHref to (ocidRlativePath) as text
(ocidAElement's setStringValue:(strHref))
    #リンクをTDにセット
(ocidTdElement's addChild:(ocidAElement))
    #TDをTRにセット
(ocidTrElement's addChild:(ocidTdElement))
    #【ファイルサイズ】TD
    set ocidValue to (ocidValueDict's valueForKey:(refMe's NSURLFileSizeKey))
    #ファイルサイズの合計に加算
    set numAllFileSize to (numAllFileSize + (ocidValue as integer))
    set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("ファイルサイズ"))
(ocidTdElement's addAttribute:(ocidAddNode))
    #単位による分岐
    set numFileSize to ocidValue as integer
    if (numFileSize) < 102400 then
      set numValue to (numFileSize / 1024) as integer
      set strValue to numValue & " kb" as text
    else if (numFileSize) > (10240 * 100000) then
      set numValue to (numFileSize / (1024 * 1000000))
      set ocidFormatter to refMe's NSNumberFormatter's alloc()'s init()
(ocidFormatter's setNumberStyle:(refMe's NSNumberFormatterDecimalStyle))
(ocidFormatter's setMinimumFractionDigits:(2))
(ocidFormatter's setMaximumFractionDigits:(2))
      set strValue to (ocidFormatter's stringFromNumber:(numValue)) as text
      set strValue to strValue & " gb" as text
    else
      set numValue to (numFileSize / (1024 * 1000))
      set ocidFormatter to refMe's NSNumberFormatter's alloc()'s init()
(ocidFormatter's setNumberStyle:(refMe's NSNumberFormatterDecimalStyle))
(ocidFormatter's setMinimumFractionDigits:(2))
(ocidFormatter's setMaximumFractionDigits:(2))
      set strValue to (ocidFormatter's stringFromNumber:(numValue)) as text
      set strValue to strValue & " mb" as text
    end if
(ocidTdElement's setStringValue:(strValue))
(ocidTrElement's addChild:(ocidTdElement))
    #【種類】TDでセット
    set ocidValue to (ocidValueDict's valueForKey:(refMe's NSURLContentTypeKey))'s localizedDescription()
    set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("種類"))
(ocidTdElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("class") stringValue:("kind_string"))
(ocidTdElement's addAttribute:(ocidAddNode))
(ocidTdElement's setStringValue:(ocidValue))
(ocidTrElement's addChild:(ocidTdElement))
    #【作成日】TDでセット
    set ocidValue to (ocidValueDict's valueForKey:(refMe's NSURLCreationDateKey))
    set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("作成"))
(ocidTdElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("class") stringValue:("date_string"))
(ocidTdElement's addAttribute:(ocidAddNode))
    set strDate to (ocidValue as date) as text
(ocidTdElement's setStringValue:(strDate))
(ocidTrElement's addChild:(ocidTdElement))
    #【修正日】TDでセット
    set ocidValue to (ocidValueDict's valueForKey:(refMe's NSURLContentModificationDateKey))
    set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("修正日"))
(ocidTdElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("class") stringValue:("date_string"))
(ocidTdElement's addAttribute:(ocidAddNode))
    set strDate to (ocidValue as date) as text
(ocidTdElement's setStringValue:(strDate))
(ocidTrElement's addChild:(ocidTdElement))
    #出来上がったTRをTBODYにセット
(ocidTbodyElement's addChild:(ocidTrElement))
    #項目番号のカウントアップ
    set numCntLineNo to (numCntLineNo + 1) as integer
  end repeat
  #TBODYをテーブルにセット
ocidTableElement's addChild:(ocidTbodyElement)
  #【tfoot】 TRで
  set ocidTfootElement to refMe's NSXMLElement's elementWithName:("tfoot")
  set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
  #項目数を取得して
  set numCntCol to (count of listColName) as integer
  #colspan指定して1行でセット
  set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("テーブルの終わり"))
(ocidThElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("colspan") stringValue:(numCntCol as text))
(ocidThElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
(ocidThElement's addAttribute:(ocidAddNode))
  #
  if (numAllFileSize) < 102400 then
    set numValue to (numAllFileSize / 1024) as integer
    set strValue to "フォルダ合計:" & numValue & " kb" as text
  else if (numAllFileSize) > (10240 * 100000) then
    set numValue to (numAllFileSize / (10240 * 100000))
    set ocidFormatter to refMe's NSNumberFormatter's alloc()'s init()
(ocidFormatter's setNumberStyle:(refMe's NSNumberFormatterDecimalStyle))
(ocidFormatter's setMinimumFractionDigits:(2))
(ocidFormatter's setMaximumFractionDigits:(2))
    set strValue to (ocidFormatter's stringFromNumber:(numValue)) as text
    set strValue to "フォルダ合計:" & strValue & " gb" as text
  else
    set numValue to (numAllFileSize / 1024000) as integer
    set strValue to "フォルダ合計:" & numValue & " mb" as text
  end if
ocidThElement's setStringValue:(strValue)
  
  #THをTRにセットして
ocidTrElement's addChild:(ocidThElement)
  #TRをTFOOTにセット
ocidTfootElement's addChild:(ocidTrElement)
  #TFOOTをテーブルにセット
ocidTableElement's addChild:(ocidTfootElement)
  # 出来上がったテーブルをArticleエレメントにセット
ocidArticleElement's addChild:(ocidTableElement)
  #
ocidRootElement's addChild:(ocidBodyElement)
  ##############################
  # TABLE
  ##############################
  #ROOTエレメントをXMLにセット
ocidXMLDoc's setRootElement:(ocidRootElement)
  #読み取りやすい表示
  set ocidXMLdata to ocidXMLDoc's XMLDataWithOptions:(refMe's NSXMLNodePrettyPrint)
  #保存
  set listDone to ocidXMLdata's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error|:(reference)
  set ocidSaveFilePath to ocidSaveFilePathURL's |path|
  set ocidContainerDirPathURL to ocidSaveFilePathURL's URLByDeletingLastPathComponent()
  set ocidContainerDirPath to ocidContainerDirPathURL's |path|
  set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
  set boolDone to appSharedWorkspace's selectFile:(ocidSaveFilePath) inFileViewerRootedAtPath:(ocidContainerDirPath)
  set boolDone to appSharedWorkspace's openURL:(ocidSaveFilePathURL)
  if (boolDone as boolean) is false then
    #ファイルを開く
    set aliasSaveFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
    tell application "Finder"
open file aliasSaveFilePath
    end tell
  end if
  ##処理終了
return "処理終了"
end open
##############################
# 基本的なHTMLの構造
##############################
to doMakeRootElement()
  #
  set ocidRootElement to refMe's NSXMLElement's elementWithName:("html")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("lang") stringValue:("ja")
ocidRootElement's addAttribute:(ocidAddNode)
  #
  set ocidHeadElement to refMe's NSXMLElement's elementWithName:("head")
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("title")
ocidAddElement's setStringValue:("ファイル一覧")
ocidHeadElement's addChild:(ocidAddElement)
  # http-equiv
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/html; charset=UTF-8")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Style-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/css")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Script-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/javascript")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("name") stringValue:("viewport")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("width=720")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("style")
ocidAddElement's setStringValue:("body { margin: 10px; background-color: #FFFFFF; } table { border-spacing: 0; caption-side: top; font-family: system-ui; } thead th { border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:first-of-type { border-start-start-radius: .5em } &:last-of-type { border-start-end-radius: .5em; border-inline-end-width: 1px } } tbody td { word-wrap: break-word;max-width: 360px;border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:last-of-type { border-inline-end-width: 1px } } tbody th { border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; } tbody tr:nth-of-type(odd) { background: #F2F2F2; } .kind_string { font-size: 0.75em; } .date_string { font-size: 0.5em; } tfoot th { border: solid 1px #666666; padding: .5ch 1ch; &:first-of-type { border-end-start-radius: .5em } &:last-of-type { border-end-end-radius: .5em; border-inline-end-width: 1px } }")
ocidHeadElement's addChild:(ocidAddElement)
  #
ocidRootElement's addChild:(ocidHeadElement)
  #
return ocidRootElement
end doMakeRootElement

|

TSV2HTML タブ区切りテキストをHTMLテーブルに変換

修正版があります
TSV2HTML タブ区切りテキストをHTMLテーブルに変換 UNIX改行修正
https://quicktimer.cocolog-nifty.com/icefloe/2024/02/post-d6338f.html

【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
(*
com.cocolog-nifty.quicktimer.icefloe
*)
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions
property refMe : a reference to current application

### 【1】入力ファイル
#ダイアログ
tell current application
  set strName to name as text
end tell
#スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
#デフォルトロケーション
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
#
set listUTI to {"public.tab-separated-values-text"}
set strMes to ("ファイルを選んでください") as text
set strPrompt to ("ファイルを選んでください") as text
try
  ### ファイル選択時
  set aliasFilePath to (choose file strMes with prompt strPrompt default location aliasDesktopDirPath of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
if aliasFilePath is (missing value) then
return "選んでください"
end if
set strFilePath to (POSIX path of aliasFilePath) as text
set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
#保存するタブ区切りテキストのパス
set ocidBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
set ocidFileName to ocidBaseFilePathURL's lastPathComponent()
set ocidSaveFilePathURL to (ocidBaseFilePathURL's URLByAppendingPathExtension:("html"))
### 【2】 ファイルのテキストを読み込み
set listResponse to (refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
set ocidReadString to (item 1 of listResponse)
#可変にして
set ocidLineString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
(ocidLineString's setString:(ocidReadString))
#改行をUNIXに強制
set ocidLineStringLF to (ocidLineString's stringByReplacingOccurrencesOfString:("\r\n") withString:("\n"))
set ocidLineString to (ocidLineStringLF's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
#改行毎でリストにする
set ocidCharSet to (refMe's NSCharacterSet's newlineCharacterSet)
set ocidLineArray to (ocidLineString's componentsSeparatedByCharactersInSet:(ocidCharSet))
#最初の1行目だけ別で取得しておく
set ocidFirstObjectString to ocidLineArray's firstObject()
set ocidFirstLineArray to ocidFirstObjectString's componentsSeparatedByString:("\t")

###【4】データをHTMLに整形
########################################
#headerに渡すエレメント
set ocidH3Element to refMe's NSXMLElement's elementWithName:("h3")
(ocidH3Element's setStringValue:("タブ区切りテキストをHTMLテーブルに"))
########################################
#footerに渡すエレメント
set ocidFotterAElement to refMe's NSXMLElement's elementWithName:("a")
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("href") stringValue:("https://quicktimer.cocolog-nifty.com/"))
(ocidFotterAElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("target") stringValue:("_blank"))
(ocidFotterAElement's addAttribute:(ocidAddNode))
set strContents to ("AppleScriptで生成しました") as text
(ocidFotterAElement's setStringValue:(strContents))
########################################
#articleに渡すエレメント
#テーブル部生成開始
set ocidTableElement to refMe's NSXMLElement's elementWithName:("table")
#【caption】
set ocidCaptionElement to refMe's NSXMLElement's elementWithName:("caption")
ocidCaptionElement's setStringValue:(ocidFileName)
ocidTableElement's addChild:(ocidCaptionElement)
#【colgroup】
set ocidColgroupElement to refMe's NSXMLElement's elementWithName:("colgroup")
#タイトル部の数だけ繰り返し
repeat with itemColName in ocidFirstLineArray
  #【col】col生成
  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("col"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
(ocidColgroupElement's addChild:(ocidAddElement))
end repeat
#テーブルエレメントに追加
ocidTableElement's addChild:(ocidColgroupElement)
#【thead】
set ocidTheadElement to refMe's NSXMLElement's elementWithName:("thead")
#TR
set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
#タイトル部の数だけ繰り返し
repeat with itemColName in ocidFirstLineArray
  #ここはTDではなくてTHを利用
  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("th"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
  #
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("id") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
(ocidAddElement's addAttribute:(ocidAddNode))
  #値を入れる
(ocidAddElement's setStringValue:(itemColName))
  #TH→TRにセット
(ocidTrElement's addChild:(ocidAddElement))
end repeat
#TRをTHEADにセット
ocidTheadElement's addChild:(ocidTrElement)
#THEADをテーブルにセット
ocidTableElement's addChild:(ocidTheadElement)
########################################
#【tbody】
set ocidTbodyElement to refMe's NSXMLElement's elementWithName:("tbody")
###【3-4】:item
set numCntContents to (count of ocidLineArray) - 1 as integer
repeat with itemIntNo from 1 to numCntContents by 1
  set ocidLineItem to (ocidLineArray's objectAtIndex:(itemIntNo))
  #空行で終わり
  if (ocidLineItem as text) is "" then
    exit repeat
  end if
  #
  set ocidItemLineArray to (ocidLineItem's componentsSeparatedByString:("\t"))
  set numCntItemLineArray to (count of ocidItemLineArray) as integer
  ##############
  #TRの開始
  set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
  repeat with itemLineNo from 0 to (numCntItemLineArray - 1) by 1
    set coidFieldValue to (ocidItemLineArray's objectAtIndex:(itemLineNo))
    if itemLineNo = 0 then
      set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
      set strTitle to (ocidFirstLineArray's objectAtIndex:(itemLineNo))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(strTitle))
(ocidThElement's addAttribute:(ocidAddNode))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("headers") stringValue:(strTitle))
(ocidThElement's addAttribute:(ocidAddNode))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
(ocidThElement's addAttribute:(ocidAddNode))
(ocidThElement's setStringValue:(coidFieldValue))
(ocidTrElement's addChild:(ocidThElement))
    else
      set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
      set strTitle to (ocidFirstLineArray's objectAtIndex:(itemLineNo))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(strTitle))
(ocidTdElement's addAttribute:(ocidAddNode))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("headers") stringValue:(strTitle))
(ocidTdElement's addAttribute:(ocidAddNode))
(ocidTdElement's setStringValue:(coidFieldValue))
(ocidTrElement's addChild:(ocidTdElement))
    end if
  end repeat
(ocidTbodyElement's addChild:(ocidTrElement))
end repeat
#TBODYをテーブルにセット
ocidTableElement's addChild:(ocidTbodyElement)
#【tfoot】 TRで
set ocidTfootElement to refMe's NSXMLElement's elementWithName:("tfoot")
set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
#項目数を取得して
set numCntCol to (count of ocidFirstLineArray) as integer
#colspan指定して1行でセット
set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("テーブルの終わり"))
(ocidThElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("colspan") stringValue:(numCntCol as text))
(ocidThElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
(ocidThElement's addAttribute:(ocidAddNode))
#
set strContents to ("項目数 : " & (numCntContents - 1)) as text
(ocidThElement's setStringValue:(strContents))
#THをTRにセットして
ocidTrElement's addChild:(ocidThElement)
#TRをTFOOTにセット
ocidTfootElement's addChild:(ocidTrElement)
#TFOOTをテーブルにセット
ocidTableElement's addChild:(ocidTfootElement)

##############################
#HTMLにする
##############################
set ocidHTML to doMakeRootElement({ocidH3Element, ocidTableElement, ocidFotterAElement})

##############################
#保存
##############################

#####【5−2】保存
#読み取りやすい表示
set ocidXMLdata to ocidHTML's XMLDataWithOptions:(refMe's NSXMLNodePrettyPrint)

set listDone to ocidXMLdata's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error|:(reference)

####【6】ブラウザで開く
set aliasFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
tell application "Finder"
open location aliasFilePath
end tell

############################################################
# 基本的なHTMLの構造
(*
doMakeRootElement({argHeaderContents, argArticleContents, argFooterContents})
HTMLのBODY部
header
article
footerにそれぞれAddchildするデータをリストで渡す
戻り値はRootエレメントにセットされた
NSXMLDocumentを戻すので 保存すればOK
*)
############################################################
to doMakeRootElement({argHeaderContents, argArticleContents, argFooterContents})
  #XML初期化
  set ocidXMLDoc to refMe's NSXMLDocument's alloc()'s init()
ocidXMLDoc's setDocumentContentKind:(refMe's NSXMLDocumentHTMLKind)
  # DTD付与
  set ocidDTD to refMe's NSXMLDTD's alloc()'s init()
ocidDTD's setName:("html")
ocidXMLDoc's setDTD:(ocidDTD)
  #
  set ocidRootElement to refMe's NSXMLElement's elementWithName:("html")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("lang") stringValue:("ja")
ocidRootElement's addAttribute:(ocidAddNode)
  #
  set ocidHeadElement to refMe's NSXMLElement's elementWithName:("head")
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("title")
ocidAddElement's setStringValue:("TSV2HTML")
ocidHeadElement's addChild:(ocidAddElement)
  # http-equiv
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/html; charset=UTF-8")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Style-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/css")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Script-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/javascript")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("name") stringValue:("viewport")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("width=720")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("style")
ocidAddElement's setStringValue:("body { margin: 10px; background-color: #FFFFFF; } table { border-spacing: 0; caption-side: top; font-family: system-ui; } thead th { border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:first-of-type { border-start-start-radius: .5em } &:last-of-type { border-start-end-radius: .5em; border-inline-end-width: 1px } } tbody td { word-wrap: break-word;max-width: 360px;border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:last-of-type { border-inline-end-width: 1px } } tbody th { border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; } tbody tr:nth-of-type(odd) { background: #F2F2F2; } .kind_string { font-size: 0.75em; } .date_string { font-size: 0.5em; } tfoot th { border: solid 1px #666666; padding: .5ch 1ch; &:first-of-type { border-end-start-radius: .5em } &:last-of-type { border-end-end-radius: .5em; border-inline-end-width: 1px } }")
ocidHeadElement's addChild:(ocidAddElement)
ocidRootElement's addChild:(ocidHeadElement)
  #
  #ボディエレメント
  set ocidBodyElement to refMe's NSXMLElement's elementWithName:("body")
  #ヘッダー
  set ocidHeaderElement to refMe's NSXMLElement's elementWithName:(