Apple Script, Automator và Folder Actions

N.E.M
5/3/2013 9:57Phản hồi: 16
Apple Script, Automator và Folder Actions
Đây là những tính năng để tự động làm một số việc được định sẵn trong mac, trong đó apple script là phần lõi quan trọng nhất và nó cũng là một ngôn ngữ lập trình được apple tạo ra dành cho đối tượng người sử dụng vì đặc tính dễ tìm hiểu, dễ sử dụng và dễ viết. Nó không quá khô khan như những ngôn ngữ khác mà hầu như giống như một câu hội thoại tiếng anh.
Dưới đây là một số công dụng của nó được mình viết, chỉnh sửa và phát triển thêm từ các code có sẵn.

Sử dụng apple script được chuyển đổi thành một ứng dụng. ( hàng đóng gói sẵn )
Các bạn down về chép vào thư mục nào cũng được, sau đó nắm kéo vào thanh toolbar như trong hình, khi nào cần xài chỉ việc click vào đó.
[​IMG]

1. Tạo file văn bản TXT:
Trong Mac không như trong Win không có phần cho tạo một file txt trắng, nên đoạn code sau đây sẽ giúp mac có được điều này. Rất thích hợp cho bác nào làm uploader cần tạo file text để điền serial xxx 😁

Cách dùng nhấn vào biểu tượng tờ giấy và cây viết là có file txt ngay tại thư mục đang mở.

[​IMG]

Link down: https://www.dropbox.com/s/pcr9zu3ca9gtow0/New text file.app.zip

2. Tạo file nén zip:
Tạo nhanh 1 file nén .zip
Cách dùng: chọn 1 folder hoặc nhiều folder ( hoặc nhiều file ) rồi nhấn vào biểu tượng thùng carton là sẽ có file zip.
Hạn chế: cái này tạo bằng automator nên không có đặt pass cho file zip để bửa nào rảnh viết lại bằng apple script thì sẽ có.

[​IMG]

Link down: https://www.dropbox.com/s/rt36qjahw7trung/Archive.app.zip

3. Remove DS_Store:

Quảng cáo


Mac luôn tạo ra file .DS_Store để lưu chỉnh sửa của từng folder như ảnh nền, kích thước, vị trí sắp xếp các icon của folder đó, bình thường thì nó ẩn và chúng ta không thấy được nó, nhưng sẽ rất là phiền phức nếu bạn viết một ứng dụng nào đó hoặc tạo một file nén mà đến khi xem lại thì thấy có thêm file này trong thư mục thì trông rất bất mãn :D
Cách dùng: chọn folder cần xóa, nhấn vào biểu tượng cái ổ đĩa có cây cọ, xóa xong sẽ có thông báo.
Chú ý: do là lưu cấu hình từng folder nên tránh lạm dụng để xóa trong các thư mục khác rồi hỏi sao thoát ra nó không lưu gì cả :D

[​IMG]

Link down: https://www.dropbox.com/s/wnbro0imd5emiuq/Remove DS_Store.app.zip


4. Unmount toàn bộ ổ đĩa được chọn:
Cách dùng: nhấn vào biểu tượng eject sẽ hiện khung hội thoại hỏi chọn ổ cần unmount chọn hết nhấn ok là nó unmount hết nhanh gọn :D

Quảng cáo


[​IMG]
[​IMG]



Link down: https://www.dropbox.com/s/sv367tg5uqrnij0/Unmount list disks.app.zip


5. Xóa vĩnh viễn một hoặc nhiều file mà không thông qua Trash:
Vào Automator phần Choose a type for your document chọn Service
Mục Service receives selected chọn Files of folder, in Finder
Ở mục Action bên khung trái các bạn tìm Run Applescript và nắm kéo nó qua khung phải

Code:
tell application "Finder"
    set selectionList to get selection as list
    set selectionone to selection
    set selectedCount to count items in selectionList
    set soundpathold to "System:Library:Components:CoreAudio.component:Contents:SharedSupport:SystemSounds:finder:"
    set soundpathnew to (the POSIX path of soundpathold)
end tell
using terms from application "Finder"
    if selectedCount = 0 then
        display dialog "Please choose a file to delete!!!" giving up after 3 buttons {"OK"} default button 1 with title "Delete file" with icon 0
    else if selectedCount = 1 then
        display dialog "Are you sure you want to permanently delete this file?" buttons {"Yes", "No"} default button 1 with title "Delete file" with icon 2
        if result = {button returned:"Yes"} then
            set posixPath1 to POSIX path of (selectionone as string) as string
            do shell script "rm -rf \"" & posixPath1 & "\""
            do shell script "afplay '" & soundpathnew & "empty trash.aif'"
        end if
    else if selectedCount ≥ 2 then
        display dialog "Are you sure you want to permanently delete these files?" buttons {"Yes", "No"} default button 1 with title "Delete file" with icon 2
        if result = {button returned:"Yes"} then
            repeat with i from 1 to number of items of the selectionList
                set selectedItem to item i of the selectionList
                set posixPath2 to POSIX path of (selectedItem as string) as string
                do shell script "rm -rf \"" & posixPath2 & "\""
            end repeat
            do shell script "afplay '" & soundpathnew & "empty trash.aif'"
        end if
    end if
end using terms from
Sau khi làm xong sẽ như trong hình các bạn chú ý làm giống nha :D

[​IMG]

Sau khi xong hết cac bước trên thì save lại với Permanently delete hoặc tên gì các bạn thích ( tên này sẽ hiển thị ở menu khi các bạn nhấp phải vào file hoặc folder)

[​IMG]

Giờ mỗi lần muốn xoá một hoặc nhiều file nào đó mà không muốn thông qua trash các bạn chỉ việc click chuột phải và chọn Permanently delete một khung hội thoại sẽ hỏi muốn xoá file này không, mình làm cho nó giống giống shift delete của win :D
Lưu ý là cái này là xoá vĩnh viễn và không qua trash nên khá nguy hiểm, dùng cẩn thận :D

[​IMG]



6. Tạo file HTML:
Cái này chủ yếu dành cho các bác làm Uploader có nhu cầu tạo file HTML đính kèm theo phần mềm, nhạc, phim một cách nhanh chóng.
Đầu tiên các bạn cần 1 đoạn code HTML ( bác nào chưa biết thì cứ w3schools.com mà chiến ). Dưới đây mình sẽ ví dụ 1 đoạn code HTML của mình:

HTML:
<!DOCTYPE html>
<html>
<body>
<div style="opacity:0.5;position:absolute;left:50px;width:300px;height:150px;background-color:#40B3DF"></div>
<div style="font-family:verdana;padding:20px;border-radius:10px;border:10px solid #EE872A;">
<div style="opacity:0.3;position:absolute;left:120px;width:100px;height:200px;background-color:#8AC007"></div>
<h3>It's Work</h3>
<div style="letter-spacing:12px;">Nemtabi</div>
<div style="color:#40B3DF;">Colors
<span style="background-color:#B4009E;color:#ffffff;">Boxes</span>
</div>
<div style="color:#000000;">and more...</div>
</div>
</body>
</html>
Các bạn cần convert một số kí tự đặc biệt để tránh applescript hiểu lộn khi compile, các bạn vào trang http://www.freeformatter.com/java-dotnet-escape.html rồi paste đoạn code HTML vào khung sau đó nhấn ESCAPE các bạn sẽ được đoạn code mới.
Rồi giờ mở Applescript Editor và paste đoạn code sau vào:

Code:
tell application "Finder"
    try
        set thisFolder to the target of the front window as alias
        set fileName to "untitled"
        set fileExt to ".html"
        --http://www.freeformatter.com/java-dotnet-escape.html
        set sourcecode to "<!DOCTYPE html>\r\n<html>\r\n<body>\r\n\r\n<div style=\"opacity:0.5;position:absolute;left:50px;width:300px;height:150px;background-color:#40B3DF\"></div>\r\n\r\n<div style=\"font-family:verdana;padding:20px;border-radius:10px;border:10px solid #EE872A;\">\r\n\r\n<div style=\"opacity:0.3;position:absolute;left:120px;width:100px;height:200px;background-color:#8AC007\"></div>\r\n\r\n<h3>It's Work</h3>\r\n\r\n<div style=\"letter-spacing:12px;\">Nemtabi</div>\r\n\r\n<div style=\"color:#40B3DF;\">Colors\r\n<span style=\"background-color:#B4009E;color:#ffffff;\">Boxes</span>\r\n</div>\r\n\r\n<div style=\"color:#000000;\">and more...</div>\r\n\r\n</div>\r\n\r\n</body>\r\n</html>\r\n\r\n"
        tell application "System Events"
            set fileList to get the name of every disk item of thisFolder
        end tell
        set newFile to fileName & fileExt
        set x to 1
        repeat
            if newFile is in fileList then
                set newFile to fileName & x & fileExt
                set x to x + 1
            else
                exit repeat
            end if
        end repeat
        make new file at thisFolder with properties {name:newFile, file type:"HTML", creator type:"html"}
    end try
end tell
set newpath to (the POSIX path of thisFolder)
set openhtml to open for access "" & newpath & "" & newFile & "" with write permission
write sourcecode to openhtml as «class utf8» starting at 0
close access openhtml
Các bạn thay set sourcecode to thành đoạn code HTML vừa được ESCAPE ở trên ( nhớ là vẫn để trong dấu nháy " nha ) | set fileName to là tên của file HTML được tạo ra.
Sau khi xong các bạn thử nhấn Compile xem có lỗi gì không nếu không có lỗi thì xuất ra thành 1 app hoặc 1 service thì tùy các bạn :D

Ở hình bên dưới mình tạo thành 1 app và đặt biểu tượng nó lên thanh toolbar cua finder khi cần tạo file html chỉ việc nhấn vào nút này là ta có ngay 1 file html.

[​IMG]
[​IMG]
[​IMG]





7. Mật khẩu bảo vệ Folder:
Tính năng bảo vệ folder chứa hàng nóng, hàng du học Liên Xô, tài liệu nguy hiểm cho xã hội :D Khi nhấn vào mở Folder sẽ hiện bảng thông báo nhập mật khẩu đồng thời ẩn hết các file trong đó và lock folder đó lại, khi nhập đúng sẽ hiện lại các file và unlock folder.
Đầu tiên là vào Applescript Editor và paste đoạn code này vào:


Code:
on opening folder this_folder
    tell application "Finder"
        set the selectionList to get every item in front window as list
        set the Frontw to (folder of the front window) as alias
        set PathW to POSIX path of (Frontw as string) as string
    end tell
    if not selectionList = {} or selectionList = "" then
        tell application "Finder" to set the selectionList2 to select every item in front window as list
        repeat with i from 1 to number of items of the selectionList2
            set selectedItem to item i of the selectionList2
            set posixPath1 to POSIX path of (selectedItem as string) as string
            do shell script "find " & quoted form of PathW & " \\! -name \".*\" -print0 | xargs -0 chflags uchg" -- lock file
            do shell script "chflags hidden " & quoted form of posixPath1 & "" -- hidden file
        end repeat
    end if
    repeat
        tell application "Finder"
            set dialogresult to display dialog "Restricted Folder. Please enter the password to access folder:" buttons {"Ok", "Close"} default button 1 default answer "" with hidden answer
            copy the result as list to {PWHash, button_choice}
            set button_choice to the button returned of dialogresult
            if button_choice is equal to "Ok" then
                set PWHash to the text returned of dialogresult
                if PWHash = {} or PWHash = "" then
                    display dialog "Access Denied" buttons {"Ok"} default button 1
                else
                    set HashInput to (do shell script "md5 -q -s " & PWHash)
                    set theHash to "e10adc3949ba59abbe56e057f20f883e" -- Dien ma Hash md5 tai day
                    if not HashInput = theHash then -- md5 password
                        display dialog "Access Denied" buttons {"Ok"} default button 1
                    else
                        display dialog "Access Granted" buttons {"Ok"} default button 1
                        tell application "Finder" to set the posixPath3 to (folder of the front window) as alias
                        set posixPath4 to POSIX path of (posixPath3 as string) as string
                        do shell script "find " & quoted form of posixPath4 & " \\! -name \".*\" -print0 | xargs -0 chflags nohidden"
                        do shell script "find " & quoted form of PathW & " \\! -name \".*\" -print0 | xargs -0 chflags nouchg"
                        exit repeat
                    end if
                end if
            else if button_choice is equal to "Close" then
                tell application "Finder"
                    close folder this_folder
                    exit repeat
                end tell
            end if
        end tell
    end repeat
end opening folder

Rồi mở Terminal
Code:
md5 -qs mat_khau
Thay mat_khau bằng mật khẩu của các bạn, nhấn enter và ta sẽ có được một đoạn mã hash được mã hóa md5, copy đoạn mã này rồi quay lại với Applescript Editor tìm dòng
Code:
set theHash to "e10adc3949ba59abbe56e057f20f883e" -- Dien ma Hash md5 tai day
Thay đoạn e10adc3949ba59abbe56e057f20f883e trong ngoặc kép bằng đoạn mã hash vừa được tạo ra ở Terminal. Kiểm tra hoàn tất thì nhấn nút Compile. Nếu không có lỗi gì thì save lại thành file Secret Folder hoặc tên nào tùy thích ( các bạn save ở đâu thì nhớ vào đó tìm lại vì chúng ta sẽ cần file này ở bước sau ).
Giờ thì tiếp tục kích hoạt tính năng khá hay nhưng ít ai biết Folder Actions để dùng nó các bạn vào System Preferences > Keyboard > Keyboard Shortcuts > Services > tìm Folder Actions Setup nếu nó chưa được check thì check nó vào.
[​IMG]
Quay lại file Secret Folder.scpt ( đuôi scpt thường sẽ không được hiện ra ) vừa tạo các bạn chép nó vào một trong 2 thư mục sau
Code:
~/Library/Scripts/Folder Action Scripts/
/Library/Scripts/Folder Action Scripts/
Folder nào không có thì tạo nó, cái đầu là của User, cái sau là của hệ thống, chép vào đâu thì cũng đều hiện trong Folder Action Setup tùy các bạn quyết định :D ( tránh chép cùng lúc cả 2 nơi )
OK giờ tới màn quan trọng nhất. Chọn Folder cần được bảo vệ nhấp phải tìm Folder Action Setup... ( nếu có nhiều service quá nó sẽ nằm trong tab Services của menu nhấp phải )
[​IMG]
Chọn nó sẽ hiện ra bảng chọn loại action nào cho folder, các bạn chọn Secret Folder.scpt rồi nhấn nút Attach thế là xong :D giờ vào folder đó và tận hưởng :D
Và quan trọng nhất là Folder sẽ mất bảo vệ nếu file này bị xóa, chỉnh sửa hoặc tắt Folder Actions, nhưng về cơ bản rất ít người biết đến sự tồn tại của thằng này nên không cần lo :D
[​IMG]
[​IMG]
[​IMG]
[​IMG]
[​IMG]
16 bình luận
Chia sẻ

Xu hướng

N.E.M
CAO CẤP
11 năm
cập nhật và tối ưu code Xóa vĩnh viễn :p
Bài hay thế này mà sao không thấy comment gì ? Thank bác có cơ hội sẽ học tập 😁
N.E.M
CAO CẤP
11 năm
bên này ít người xem 😁
@N.E.M Bạn PM cho anh dihuta để đưa ra ngoài trang tin đi nghe.
Bài hay và công phu lắm.

Gửi từ LG-P940 của tôi
N.E.M
CAO CẤP
11 năm
@killed hi thanks bác, ra đó khó chỉnh lắm, mấy bài này mình chỉ sửa liên tục à 😁
ruckus
ĐẠI BÀNG
11 năm
Cái xoá vĩnh viễn hay phết, không phải vào trash xoá lần 2 nữa
N.E.M
CAO CẤP
11 năm
Cập nhật thêm Mật khẩu bảo vệ Folder 🆒
Hi, bạn cho mình hỏi: nếu mình đặt Pass cho nhiều folder, xong oy suy nghĩ lại, không thích đặt pass cho 1 folder nào đó. Mún nó trở về bình thường thì làm sao vậy bạn? Thanks bạn nhiều
N.E.M
CAO CẤP
11 năm
@KentSeven vào folder action bỏ chọn folder đó đi
@N.E.M thanks bạn 😃
Applescript Editor o dau vay moi nguoi, minh ko bik, chi minh voi
thethidie
TÍCH CỰC
10 năm
hay quá thanks bác, mà bác biết sách nào nó dạy cái ngôn ngữ lập trình này ko ?
TerryFox
ĐẠI BÀNG
10 năm
xin lỗi cho mình hỏi Secret Folder.scpt file này ở đâu vậy bạn?
Cmd + Space => Spotlight xong nhập Applescrip Editor
Cái này bạn tự tạo. Đọc kĩ lại bài nhé!
Bài hay quá,đã lưu lại dùng sau này,thanks bác chủ nhiều!
oánh dấu

Xu hướng

Bài mới









  • Chịu trách nhiệm nội dung: Trần Mạnh Hiệp
  • © 2024 Công ty Cổ phần MXH Tinh Tế
  • Địa chỉ: Số 70 Bà Huyện Thanh Quan, P. Võ Thị Sáu, Quận 3, TPHCM
  • Số điện thoại: 02822460095
  • MST: 0313255119
  • Giấy phép thiết lập MXH số 11/GP-BTTTT, Ký ngày: 08/01/2019