Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use framework "Foundation"
- use scripting additions
- -- ref. https://apidocs.imgur.com
- property apiUrl : "https://api.imgur.com/3/image"
- property authHeadArg : {"-H", "Authorization: Client-ID cc2c5a0c5e345d1"}
- property authHead : " " & item 1 of authHeadArg & " '" & item 2 of authHeadArg & "'"
- property logFilePath : (POSIX path of (path to library folder from user domain)) & "/Logs/ImgurLib.log"
- property deliveryFilePath : (POSIX path of (path to temporary items folder from user domain)) & "ImgurLib.delivery"
- (* >>>>>>>>
- Upload image file to Imgur
- *)
- on upload for imageFilePath given completeTo:completeHandleObject : missing value
- return uploadAsyncWithImageFile(imageFilePath, completeHandleObject)
- end upload
- on delete of hash
- deleteWithHash(hash)
- end delete
- on lock by hash
- lockWithHash(hash)
- end lock
- on uploadWithImageFile(imageFilePath)
- return uploadAsyncWithImageFile(imageFilePath, missing value)
- end uploadWithImageFile
- on uploadAsyncWithImageFile(imageFilePath, completeHandleObject)
- set uploadTaskInfo to uploadExecute(imageFilePath)
- set theResult to uploadTaskInfo
- if |error| of theResult is not missing value then return theResult
- if completeHandleObject is missing value then
- (task of uploadTaskInfo)'s waitUntilExit()
- return uploadResult(uploadTaskInfo)
- end if
- set uploadTaskInfo to uploadTaskInfo & {completeHandleObject:completeHandleObject}
- current application's NSTimer's scheduledTimerWithTimeInterval:0.1 target:me selector:"uploadAsyncPollingTimerFire:" userInfo:uploadTaskInfo repeats:true
- return {imageURL:"In progress...", hash:"In progress...", |error|:missing value, filePath:filePath of uploadTaskInfo, fileName:fileName of uploadTaskInfo}
- end uploadAsyncWithImageFile
- -- Private's for upload image file
- on uploadAsyncPollingTimerFire:timer
- set uploadTaskInfo to (timer's userInfo) as record
- if (task of uploadTaskInfo)'s isRunning() then return
- timer's invalidate()
- set theResult to uploadResult(uploadTaskInfo)
- try
- -- imgurUploadAsyncCompleted(theResult) of completeHandleObject of uploadTaskInfo
- imgurUploadCompleted of (completeHandleObject of uploadTaskInfo) by theResult
- on error message
- displayCriticalError(message)
- end try
- end uploadAsyncPollingTimerFire:
- on uploadExecute(imageFilePath)
- set imageFileName to ""
- set task to missing value
- try
- if class of imageFilePath is in {alias, «class furl»} then set imageFilePath to POSIX path of imageFilePath
- set imageFilePath to (current application's NSString's stringWithString:imageFilePath)'s stringByStandardizingPath()
- set imageFileName to imageFilePath's lastPathComponent() as text
- set imageFilePath to imageFilePath as text
- set workspace to current application's NSWorkspace's sharedWorkspace
- set {fileTypeUTI, |error|} to workspace's typeOfFile:imageFilePath |error|:(reference)
- if fileTypeUTI is missing value then error |error|'s localizedDescription
- if not (workspace's type:fileTypeUTI conformsToType:"public.image") then error "Could not upload because that is not an image file."
- set task to current application's NSTask's alloc's init
- set task's launchPath to "/usr/bin/curl"
- (*
- set task's arguments to {"--show-error", "--silent", apiUrl} & authHeadArg & {"-F", "image=@" & imageFilePath}
- *)
- set task's arguments to {"--show-error", "--silent", apiUrl} & authHeadArg & {"-F", "image=@-"}
- set {fileHandle, |error|} to current application's NSFileHandle's fileHandleForReadingFromURL:(current application's NSURL's fileURLWithPath:imageFilePath isDirectory:false) |error|:(reference)
- if fileHandle is missing value then error |error|'s localizedDescription
- set task's standardInput to fileHandle
- (*
- set task's launchPath to "/bin/bash"
- set task's arguments to {"-c", "cat " & quoted form of imageFilePath & " | curl --show-error --silent " & apiUrl & authHead & " -F image=@-"}
- *)
- set task's currentDirectoryPath to POSIX path of (path to temporary items)
- set task's standardOutput to current application's NSPipe's pipe
- set task's standardError to current application's NSPipe's pipe
- on error |error|
- return {imageURL:missing value, hash:missing value, |error|:(|error| as text), filePath:imageFilePath, fileName:imageFileName}
- end try
- task's |launch|()
- return {|error|:missing value, task:task, filePath:imageFilePath, fileName:imageFileName}
- end uploadExecute
- on uploadResult(uploadTaskInfo)
- set task to task of uploadTaskInfo
- set filePath to filePath of uploadTaskInfo
- set fileName to fileName of uploadTaskInfo
- set respRec to {}
- try
- if task's terminationStatus as integer is not 0 then error current application's NSString's alloc()'s initWithData:(task's standardError's fileHandleForReading's readDataToEndOfFile()) encoding:(current application's NSUTF8StringEncoding)
- set {respRec, |error|} to current application's NSJSONSerialization's JSONObjectWithData:(task's standardOutput's fileHandleForReading's readDataToEndOfFile()) options:0 |error|:(reference)
- if respRec is missing value then |error|'s localizedDescription
- set respRec to respRec as record
- if not (success of respRec) then error errorMessageInResponse(respRec)
- on error |error|
- return {imageURL:missing value, hash:missing value, |error|:(|error| as text), filePath:filePath, fileName:fileName}
- end try
- set imgUrl to link of |data| of respRec
- set deleteHash to deleteHash of |data| of respRec
- set AppleScript's text item delimiters to " "
- do shell script "printf '[%s] uploaded " & deleteHash & "
- %s
- %s
- %s
- curl %s
- ' \"$(date)\" " & quoted form of fileName & " " & quoted form of filePath & " " & quoted form of imgUrl & " " & quoted form of curlArgsStringWithDeleteHash(deleteHash) & " >> " & quoted form of logFilePath
- return {imageURL:imgUrl, hash:deleteHash, |error|:missing value, filePath:filePath, fileName:fileName}
- end uploadResult
- (* >>>>>>>>
- Delete image file from Imgur
- *)
- on deleteWithHash(deleteHash)
- set respRec to {}
- try
- set respJson to do shell script "curl --show-error --silent " & curlArgsStringWithDeleteHash(deleteHash)
- set respRec to run script "JSON.parse(" & quoted form of respJson & ");" in "JavaScript"
- if not (success of respRec) then error errorMessageInResponse(respRec)
- on error |error|
- return {success:false, |error|:(|error| as text)}
- end try
- do shell script "printf '[%s] deleted " & deleteHash & "
- ' \"$(date)\" >> " & quoted form of logFilePath
- return {success:true, |error|:missing value}
- end deleteWithHash
- (* >>>>>>>>
- Lock(except/hide for list) uploaded imfe file in logfile
- *)
- on lockWithHash(deleteHash)
- do shell script "printf '[%s] locked " & deleteHash & "
- ' \"$(date)\" >> " & quoted form of logFilePath
- end lockWithHash
- (* >>>>>>>>
- List uploaded info from logfile
- *)
- on uploaded()
- set uploads to current application's NSMutableArray's new()
- set hashes to current application's NSMutableArray's new()
- repeat with theLine in (every paragraph of (do shell script "tail -n 300 " & quoted form of logFilePath & " | awk '
- /^[^ ].*(deleted|locked)/{
- printf \"-%s\\n\", $NF;
- }
- /^[^ ].*uploaded/{
- hash=$NF; sub(\" uploaded.*$\", \"\"); date=$0; getline; sub(\"^ \", \"\");
- printf \"+%s “%s” - %s\\n\", date, $0, hash;
- }'"))
- set hash to last word of theLine
- if first text of theLine is "+" then
- (uploads's addObject:(text 2 thru -1 of theLine))
- (hashes's addObject:hash)
- else
- set theIndex to (hashes's indexOfObject:hash)
- if theIndex is not (current application's NSNotFound) then
- (uploads's removeObjectAtIndex:theIndex)
- (hashes's removeObjectAtIndex:theIndex)
- end if
- end if
- end repeat
- return (uploads's reverseObjectEnumerator()'s allObjects()) as list
- end uploaded
- (* >>>>>>>>
- Post(save) file list into temporary file for delivery process to process
- *)
- on postDeliveryFiles(theFiles)
- set posixFiles to ""
- repeat with theFile in theFiles
- set thePath to theFile
- if class of thePath is in {alias, «class furl»} then set thePath to POSIX path of thePath
- set posixFiles to posixFiles & thePath & (ASCII character 10)
- end repeat
- if length of posixFiles is 0 then return
- do shell script "cat >> " & quoted form of deliveryFilePath & " << IMGURLIB_DELIVERY_END
- " & posixFiles & "IMGURLIB_DELIVERY_END
- "
- end postDeliveryFiles
- (* >>>>>>>>
- Take(load) file list from temporary file for delivery process to process
- *)
- on takeDeliveryFilePaths()
- return every paragraph of (do shell script "IMGURFILE=" & quoted form of deliveryFilePath & ";cat \"$IMGURFILE\" 2> /dev/null; rm -f \"$IMGURFILE\"; exit 0")
- end takeDeliveryFilePaths
- -- Private's
- on curlArgsStringWithDeleteHash(deleteHash)
- return "-X DELETE " & apiUrl & "/" & deleteHash & authHead
- end curlArgsStringWithDeleteHash
- on errorMessageInResponse(response)
- set message to |error| of |data| of response
- if class of message is in {string, text} then return message
- try
- return message of message
- end try
- if class of message is list then
- return (current application's NSArray's arrayWithArray:message)'s |description|()
- else if class of message is record then
- return (current application's NSDictionary's dictionaryWithDictionary:message)'s |description|()
- end if
- return "Error message unknown by ImgurLib"
- end errorMessageInResponse
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement