Script: Lookup Safari URL in open databases

This version searches both, “https://” and “http://” URLs. This is important as DEVONthink can’t find an old record with a http scheme if the website you are searching for uses https in the meantime.

If used on a discourse forum URL (the ones I know…) like the DEVONthink forum, it will find posts from the same thread. But this is only possible by using the search window (instead of first using the “lookup records with URL” command) so if theres no record found you’ll only see an empty search window. Don’t know another way to do it, as the “lookup” command doesn’t allow wildcards. If you know more discourse forums let me know.

tell application "Safari" to tell window 1 to set theURL to current tab's URL

set theURL to characters ((offset of "//" in theURL) + 2) thru -1 in theURL as string

set theForums to {"discourse.", "discuss.", "forum.", "forums.", "meta."}

if (characters 1 thru (offset of "." in theURL) in theURL as string) is in theForums then
	
	set d to AppleScript's text item delimiters
	set AppleScript's text item delimiters to "/"
	set TextItems to text items of theURL
	set AppleScript's text item delimiters to d
	
	try
		item -2 of TextItems as integer
		set reverseURL to reverse of (characters of theURL) as string
		set reverseOffset to -((offset of "/" in reverseURL) + 1)
		set theURL to (characters 1 thru reverseOffset) in theURL as string
		set theSearchURL to "x-devonthink://search?query=" & theURL
		open location theSearchURL
		return
	end try
	
end if

tell application id "DNtp"
	try
		set theDatabases to databases
		set theResults to {}
		
		repeat with thisScheme in {"https://", "http://"}
			repeat with thisDatabase in theDatabases
				set thisDatabasesResults to lookup records with URL thisScheme & theURL in thisDatabase
				set theResults to theResults & thisDatabasesResults
			end repeat
		end repeat
		
		set ResultCount to (count of theResults)
		
		if ResultCount = 0 then
			set noResults to display notification "Noch nicht hinzugefügt" with title "DEVONthink URL Check"
			return
		end if
		
		if ResultCount = 1 then
			open window for record (item 1 of theResults)
			activate
			return
		end if
		
		if ResultCount > 1 then
			set theSearchURL to "x-devonthink://search?query=" & theURL
		end if
		
	end try
end tell

open location theSearchURL