Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Watch YouTube videos with QuickTime

Requires SIMBL and GreaseKit. Tested on Safari.
# YouTube in MP4 via QuickTime Plugin!
# http://www.joeyhagedorn.com/2008/04/16/youtube-in-mp4-via-quicktime-plugin

open -a Safari http://www.joeyhagedorn.com/media/downloads/youtubeQT.user.js


# Download YouTube Videos as MP4 Files
# http://googlesystem.blogspot.com/2008/04/download-youtube-videos-as-mp4-files.html

open -a Safari http://members.optusnet.com.au/lbramsay/youtube_mp4.user.js


1. Youtube QT (http://www.joeyhagedorn.com/media/downloads/youtubeQT.user.js)
// ==UserScript==
// @name           Youtube QT
// @namespace      userscripts.org
// @description    Plays the high-resolution YouTube video in an embedded Quicktime player 
// @version        0.1
// @include        http://youtube.com/watch?*
// @include        http://www.youtube.com/watch?*
// @include        http://*.youtube.com/watch?*
// ==/UserScript==
	
var video_id = null;
var video_hash = null;
var video_player = document.getElementById('movie_player');

if (video_player) {var flash_variables=video_player.attributes.getNamedItem('flashvars');
	if (flash_variables) {var flash_values=flash_variables.value;
		if (flash_values) {var video_id_match=flash_values.match(/video_id=([^(\&|$)]*)/);
			if (video_id_match!=null) video_id=video_id_match[1];
				var video_hash_match=flash_values.match(/t=([^(\&|$)]*)/);
				if (video_hash_match!=null) video_hash=video_hash_match[1];
		}
	}
}

if (video_id==null || video_hash==null) {var args=unsafeWindow.swfArgs;
	if (args) {video_id=args['video_id'];
		video_hash=args['t'];
	}
}

if (video_id==null || video_hash==null) return;

var yt_mp4_path = 'http://www.youtube.com/get_video?fmt=18&video_id='+video_id+'&t='+video_hash;
var div_embed=document.getElementById('watch-player-div');

if (div_embed) {div_embed.innerHTML='<embed src=\''+yt_mp4_path+'\' type="video/mp4" width=480 height=400 scale=\'aspect\'></embed>';
};


2. Download YouTube Videos as MP4 (http://members.optusnet.com.au/lbramsay/youtube_mp4.user.js)
// ==UserScript==
// @name           Download YouTube Videos as MP4
// @description    Adds an option to download YouTube videos.
// @namespace      http://googlesystem.blogspot.com
// @include        http://*.youtube.com/watch?*
// @include        http://youtube.com/watch?*
// @version        0.4
// ==/UserScript==

if ( navigator.userAgent.indexOf("AppleWebKit") != -1 ) {
      if (document.getElementById('download-youtube-video')) return;
    
      var video_id = null;
      var video_hash = null;
      var video_player = document.getElementById('movie_player');
      
      if (video_player) {
        var flash_variables = video_player.attributes.getNamedItem('flashvars');  
        if (flash_variables) {
          var flash_values = flash_variables.value;
          if (flash_values) {
            var video_id_match = flash_values.match(/video_id=([^(\&|$)]*)/);
            if (video_id_match!=null) video_id = video_id_match[1];
            var video_hash_match = flash_values.match(/t=([^(\&|$)]*)/);
            if (video_hash_match!=null) video_hash = video_hash_match[1];        
          }
        }
      }
      
      if (video_id==null || video_hash==null) {
        var args = window.swfArgs;
        if (args) {
          video_id = args['video_id'];
          video_hash = args['t'];  
        }
      }
      
      if (video_id==null || video_hash==null) return;
     
       var yt_mp4_path ='http://www.youtube.com/get_video?fmt=18&amp;video_id='+video_id+'&amp;t='+video_hash; 
       var div_embed = document.getElementById('watch-embed-div');
       if (div_embed) {
          div_embed.innerHTML = div_embed.innerHTML + '<br /> <span id=\'download-youtube-video\'> <a href=\''+yt_mp4_path+'\'>Download as MP4</a> '+ ((navigator.userAgent.indexOf('Safari')!=-1)?'(control-click and select <i>Download linked file as</i>)' : ('(right-click and select <i>Save '+ (navigator.appName=='Microsoft Internet Explorer'?'target':'link') +' as</i>)')) + '</span>';
      }

} else {
    (function () {
    
      if (document.getElementById('download-youtube-video')) return;
    
      var video_id = null;
      var video_hash = null;
      var video_player = document.getElementById('movie_player');
      
      if (video_player) {
        var flash_variables = video_player.attributes.getNamedItem('flashvars');  
        if (flash_variables) {
          var flash_values = flash_variables.value;
          if (flash_values) {
            var video_id_match = flash_values.match(/video_id=([^(\&|$)]*)/);
            if (video_id_match!=null) video_id = video_id_match[1];
            var video_hash_match = flash_values.match(/t=([^(\&|$)]*)/);
            if (video_hash_match!=null) video_hash = video_hash_match[1];        
          }
        }
      }
      
      if (video_id==null || video_hash==null) {
        var args = unsafeWindow.swfArgs;
        if (args) {
          video_id = args['video_id'];
          video_hash = args['t'];  
        }
      }
      
      if (video_id==null || video_hash==null) return;
     
       var yt_mp4_path ='http://www.youtube.com/get_video?fmt=18&amp;video_id='+video_id+'&amp;t='+video_hash; 
       var div_embed = document.getElementById('watch-embed-div');
       if (div_embed) {
          div_embed.innerHTML = div_embed.innerHTML + '<br /> <span id=\'download-youtube-video\'> <a href=\''+yt_mp4_path+'\'>Download as MP4</a> '+ ((navigator.userAgent.indexOf('Safari')!=-1)?'(control-click and select <i>Download linked file as</i>)' : ('(right-click and select <i>Save '+ (navigator.appName=='Microsoft Internet Explorer'?'target':'link') +' as</i>)')) + '</span>';
      }
      
    })();
}

List & delete Safari history

# for PlistBuddy see: http://codesnippets.joyent.com/posts/show/1484

# list Safari history
function lsh() {
   /usr/libexec/PlistBuddy -c Print ~/Library/Safari/History.plist | \
      /usr/bin/awk '/^[[:space:]]+= /{sub( /^[[:space:]]+=[[:space:]]+/,""); print}' | \
      sed -E -n -e 's/^(.{1,100}).*$/\1/' -e '1!G;h;$p' | /usr/bin/nl
      #/usr/bin/sed -n '1!G;h;$p' | /usr/bin/nl
      #/usr/bin/awk '!x[$0]++' | /usr/bin/sed -n '1!G;h;$p' | /usr/bin/nl
      #/usr/bin/sort -u | /usr/bin/nl
   return 0
}

lsh


# delete Safari history except ...
# ... for those domains specified by an egrep regex

function dshe() {

   declare array_indices historyplistfile index regex

   regex="${1:-$'\777'}"   # delete entire history if there is no argument $1; for \777 see man ruby
   historyplistfile="${HOME}/Library/Safari/History.plist"

   array_indices="$(/usr/libexec/PlistBuddy -c print "${historyplistfile}" | /usr/bin/awk '/^[[:space:]]+= /{x++;print x-1,$0}' | \
       /usr/bin/egrep -iv "${regex}" | /usr/bin/awk '{print $1}' | /usr/bin/sort -rn)"

:<<-'COMMENT'
   # test
   for index in ${array_indices}; do 
      echo $index; 
      #/usr/libexec/PlistBuddy -c "Print :WebHistoryDates:'${index}'" "${historyplistfile}" 
      /usr/libexec/PlistBuddy -c "Print :WebHistoryDates:'${index}':title" "${historyplistfile}" 
   done
COMMENT

   for index in ${array_indices}; do 
      /usr/libexec/PlistBuddy -c "Delete :WebHistoryDates:'${index}'" "${historyplistfile}" 
   done

   /usr/libexec/PlistBuddy -c save "${historyplistfile}" &>/dev/null

   return 0

}


lsh
dshe unix
lsh
dshe
lsh

List & delete Safari cookies

# for PlistBuddy see: http://codesnippets.joyent.com/posts/show/1484

# list Safari cookies
function lsc() {
   /usr/libexec/PlistBuddy -c print ~/Library/Cookies/Cookies.plist | \
      /usr/bin/awk '/^[[:space:]]+Domain = /{sub( /^[[:space:]]+Domain =[[:space:]]+/,""); print}' | \
      /usr/bin/sort -u | /usr/bin/nl
      #/usr/bin/awk '!x[$0]++' | /usr/bin/sed -n '1!G;h;$p' | /usr/bin/nl
   return 0
}

lsc


# delete Safari cookies except ...
# ... for those domains specified by an egrep regex

/usr/libexec/PlistBuddy -c Print ~/Library/Cookies/Cookies.plist
/usr/libexec/PlistBuddy -c 'Print :0' ~/Library/Cookies/Cookies.plist
/usr/libexec/PlistBuddy -c 'Print :1' ~/Library/Cookies/Cookies.plist


function dsce() {

   declare array_indices cookiesplistfile index regex

   regex="${1:-$'\777'}"   # delete all cookies if there is no argument $1; for \777 see man ruby
   cookiesplistfile="${HOME}/Library/Cookies/Cookies.plist"

   array_indices="$(/usr/libexec/PlistBuddy -c print "${cookiesplistfile}" | /usr/bin/awk '/Domain = /{x++;print x-1,$0}' | \
       /usr/bin/egrep -iv "${regex}" | /usr/bin/awk '{print $1}' | /usr/bin/sort -rn)"

:<<-'COMMENT'
   # test
   for index in ${array_indices}; do 
      echo $index; 
      #/usr/libexec/PlistBuddy -c "Print :'${index}'" "${cookiesplistfile}" 
      /usr/libexec/PlistBuddy -c "Print :'${index}':Domain" "${cookiesplistfile}" 
   done
COMMENT

   for index in ${array_indices}; do 
      /usr/libexec/PlistBuddy -c "Delete :'${index}'" "${cookiesplistfile}" 
   done

   /usr/libexec/PlistBuddy -c save "${cookiesplistfile}" &>/dev/null

   return 0

}


lsc

dsce 'xxx.com|xxx.org'

lsc

Local SOCKS Proxy for Safari

Surfing the web with Safari (3.0.4) on Mac OS X 10.4 can be made a bit more private & secure by setting up a local SOCKS Proxy on an admin user account.
Use the following BASH command-line instructions at your own risk!

I. Setting up a local SOCKS proxy for Safari on a single admin user account


# first enable remote login on your admin user account: System Preferences > Sharing > Services > Remote Login

# test if remote login is enabled
sudo launchctl list | grep com.openssh.sshd                               # com.openssh.sshd
defaults read /System/Library/LaunchDaemons/ssh
netstat -an | awk '/\*\.22[[:space:]]+.*LISTEN$/ {print}'                 # tcp4 ... *.22 ... LISTEN
service --test-if-available ssh; echo $?                                  # 0
service --test-if-configured-on ssh; echo $?                              # 0

# test if sshd daemon supports tcp_wrappers
# cf. http://www.la-samhna.de/library/brutessh.html#5
otool -L /usr/sbin/sshd | grep libwrap                                      

# then make sure you are connected to the internet
ping -c 10 checkip.dyndns.org
curl -L -s --max-time 10 http://checkip.dyndns.org | grep -Eo -m 1 '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}'   


# then set up the local SOCKS Proxy
# cf. http://macapper.com/2007/05/22/advanced-os-x-secure-tunneling-via-ssh

#ssh -q -D 8080 -f -C -N -x $(whoami)@$(ipconfig getifaddr $(route -n get default | awk '/interface:/ { print $2 }') 2>/dev/null)
#ssh -v -D 8080 -f -C -N -x $(whoami)@$(ipconfig getifaddr $(route -n get default | awk '/interface:/ { print $2 }') 2>/dev/null) 

ssh -q -D 8080 -f -C -N -x $(whoami)@127.0.0.1     # cf. AllowUsers $(whoami)@127.0.0.1 below

# ... enter your user account login password


# SSH Without a Password
# http://www.csua.berkeley.edu/~ranga/notes/ssh_nopass.html
# http://homepage.mac.com/kelleherk/iblog/C1901548470/E20061128145420/index.html

# RSA
mkdir -p $HOME/.ssh
chmod -R 0700 $HOME/.ssh
ssh-keygen -t rsa -f $HOME/.ssh/id_rsa -P ''
cp -p $HOME/.ssh/id_rsa.pub $HOME/.ssh/authorized_keys2
chmod 0600 $HOME/.ssh/authorized_keys2
srm -v $HOME/.ssh/id_rsa.pub
#ls -ld $HOME/.ssh
#ls -l $HOME/.ssh/authorized_keys2

# encrypt the known_hosts file
ssh-keygen -H -f $HOME/.ssh/known_hosts 
srm -v $HOME/.ssh/known_hosts.old
chmod 0600 $HOME/.ssh/known_hosts


# securing SSH
# See:
# - man sshd_config
# - sudo nano /private/etc/sshd_config
# - http://switch.richard5.net/2006/09/24/securing-your-ssh-access/ 
# - http://www.mactech.com/articles/mactech/Vol.21/21.02/Security/index.html
# - Mac OS X Security Configuration Guides at http://www.apple.com/server/documentation/

sudo sh -c "
echo '
# added
Protocol 2
PermitRootLogin no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no
PubkeyAuthentication yes
AuthorizedKeysFile $HOME/.ssh/authorized_keys2
#KeepAlive yes
MaxAuthTries 3
MaxStartups 3
#UseDNS no
LoginGraceTime 40
LogLevel INFO     # QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG
#AllowUsers $(whoami)      # add more users if you like: ~<TAB><TAB>  (in Terminal.app) or dscl . -list /Users
AllowUsers $(whoami)@127.0.0.1      # cf. ssh -q -D 8080 -f -C -N -x $(whoami)@127.0.0.1 above
#AllowUsers $(whoami)@$(ipconfig getifaddr $(route -n get default | awk '/interface:/ { print $2 }') 2>/dev/null)   # requires internet connection
#AllowGroups sshusersgroup     # cf. dscl . -list /Groups; groups
' >> /private/etc/sshd_config
"


# then open Safari ...

open -a Safari

# ... and go to:
# Safari > Preferences ... > Advanced > Proxies: Change Settings ... 
# > Select a proxy server to configure: SOCKS Proxy > SOCKS Proxy Server: 127.0.0.1 : 8080 > Apply Now


sudo reboot       # ... or just restart: System Preferences > Sharing > Services > Remote Login

ssh -q -D 8080 -f -C -N -x $(whoami)@127.0.0.1      # should now work without password; cf. man ssh_config for configuring SSH shortcuts


# check local SOCKS Proxy setup

scutil --proxy                   # SOCKSProxy : 127.0.0.1, SOCKSEnable : 1, SOCKSPort : 8080

sudo ln -s "/Applications/Utilities/Network Utility.app/Contents/Resources/stroke" /bin/portscan
portscan localhost 8000 8100     # Open TCP Port:  8080  http-alt

lsof -i :22 -P
lsof -i :8080 -P
lsof -i TCP -P
lsof -U -P             # list UNIX domain socket files
sudo lsof -U -P
netstat -n -f inet


#-------------------------- 


# now you can, for example, test if a website can discover your real internal IP address provided your computer
# is behind a DSL router and you have a firewall running (cf. http://textsnippets.com/posts/show/1267)
# cf. http://www.auditmypc.com/internal-ip.html

# first get your internal IP address
ipconfig getifaddr $(route -n get default | awk '/interface:/ { print $2 }')

# note: to run the 'real IP' test you first have to enable Plug-ins, Java & JavaScript in Safari
# Safari > Preferences ... > Security > Enable plug-ins & Enable Java & Enable JavaScript

open -a Safari http://www.auditmypc.com/software_audit.asp
open -a Safari http://www.whatsmyip.org/more/    # Internal (LAN) IP: 127.0.0.1



II. Setting up a local SOCKS proxy for Safari using two different user accounts on the same computer


# The following BASH command-line instructions assume you have a regular user account 
# and an admin user account on the same computer!

# First, log in to the regular user account 
regular_user_name="$(whoami)"
regular_user_path="$HOME"
echo $regular_user_name $regular_user_path    

# note down the output from the echo command
# log out from the regular user account

# Then log in to the admin account for the following instructions!

# first make sure you are connected to the internet
ping -c 10 checkip.dyndns.org
curl -L -s --max-time 10 http://checkip.dyndns.org | grep -Eo -m 1 '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}'   

# get internal IP address & set regular user account information
regular_user_name="...insert information from regular user account above..."
regular_user_path="...insert information from regular user account above..."
internal_IP_address=$(ipconfig getifaddr $(route -n get default | awk '/interface:/ { print $2 }'))
echo $internal_IP_address $regular_user_name $regular_user_path

# enable remote login: System Preferences > Sharing > Services > Remote Login

# test if remote login is enabled
service --test-if-available ssh; echo $?               # 0
service --test-if-configured-on ssh; echo $?           # 0


# SSH Without a Password

# admin user account
# RSA
mkdir -p $HOME/.ssh
chmod -R 0700 $HOME/.ssh
ssh-keygen -t rsa -f $HOME/.ssh/id_rsa -P ''
cp -p $HOME/.ssh/id_rsa.pub $HOME/.ssh/authorized_keys2
chmod 0600 $HOME/.ssh/authorized_keys2
srm -v $HOME/.ssh/id_rsa.pub
ls -ld $HOME/.ssh
ls -l $HOME/.ssh

# regular user account
sudo mkdir -p $regular_user_path/.ssh
sudo chmod -R 0700 $regular_user_path/.ssh
sudo cp $HOME/.ssh/authorized_keys2 $regular_user_path/.ssh/authorized_keys2
#scp ~/.ssh/authorized_keys2 $regular_user_name@$internal_IP_address:~/.ssh/authorized_keys2
sudo chown -R $regular_user_name:$regular_user_name $regular_user_path/.ssh
sudo chmod 0600 $regular_user_path/.ssh/authorized_keys2
sudo ls -l $regular_user_path/.ssh
sudo ls -ld $regular_user_path/.ssh

# delete all files in ~/.ssh on both user accounts
#sudo find $regular_user_path/.ssh -type f -exec srm -fv "{}" \;
#find $HOME/.ssh -type f -exec srm -fv "{}" \;


# log in to regular user account via SSH
# enter admin account login password if prompted
ssh -i $HOME/.ssh/id_rsa $regular_user_name@$internal_IP_address     
exit

# encrypt the known_hosts file
ssh-keygen -H -f $HOME/.ssh/known_hosts       
srm -v $HOME/.ssh/known_hosts.old
chmod 0600 $HOME/.ssh/known_hosts

ssh -i $HOME/.ssh/id_rsa $regular_user_name@$internal_IP_address    # test
ls 
exit


# securing SSH
# man sshd_config
# sudo nano /private/etc/sshd_config

sudo sh -c "
echo '
# added
Protocol 2
PermitRootLogin no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no
PubkeyAuthentication yes
#AuthorizedKeysFile $regular_user_path/.ssh/authorized_keys2
#KeepAlive yes
MaxAuthTries 3
MaxStartups 3
#UseDNS no
#PermitUserEnvironment yes     # requires ~/.ssh/environment file; see man ssh and man sshd_config
LoginGraceTime 40
LogLevel INFO     # QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG
#AllowUsers $(whoami) $regular_user_name
AllowUsers $(whoami)@$internal_IP_address $regular_user_name@$internal_IP_address
' >> /private/etc/sshd_config
"


# set up the local SOCKS Proxy
# enter admin account login password if prompted
ssh -q -D 8080 -f -C -N -x $regular_user_name@$internal_IP_address    

open -a Safari

# Safari > Preferences ... > Advanced > Proxies: Change Settings ... 
# > Select a proxy server to configure: SOCKS Proxy > SOCKS Proxy Server: 127.0.0.1 : 8080 > Apply Now

# restart sshd: System Preferences > Sharing > Services > Remote Login

# check local SOCKS Proxy setup
scutil --proxy                    # SOCKSProxy : 127.0.0.1, SOCKSEnable : 1, SOCKSPort : 8080
portscan localhost 8000 8100      # Open TCP Port:  8080  http-alt

ssh -p 22 $regular_user_name@$internal_IP_address ls
ssh -l $regular_user_name $internal_IP_address 'echo hello world; whoami; hostname; logname'

# test privacy of internal IP address
open -a Safari http://www.auditmypc.com/software_audit.asp
open -a Safari http://www.whatsmyip.org/more/ # Internal (LAN) IP: 127.0.0.1


Further information on SSH & Mac OS X:

- Getting started with SSH
- Remote Login With SSH
- SSH Without A Password
- Exit Your SSH Session Without Killing Your Job
- SSH on Mac OS X
- SSH
- ssh tunnelling
- ssh X forwarding debugging
- Tutorial: SSH To Alternate Ports and Enabling Multiple SSH Daemons
- Route All Your Internet Traffic Through a Proxy
- SSH Notes
- SSH Host Key Protection
- Setup the SSH server to use keys for authentication
- Auto-closing SSH tunnels
- SSH Tunnelling (Port Forwarding)
- Defending against brute force ssh attacks
- SSH + Screen = Easy Administration
- SSH SOCKS Proxy From Behind a Gateway
- nylon - flexible Unix proxy server with mirror mode; sudo port install nylon
- tsocks - transparent SOCKS proxying library; sudo port install tsocks
- Create a SOCKS proxy with SSH in Leopard

Delete WebKit search fields


# defaults read com.apple.Safari | grep -i com.apple.WebKit.searchField:
# open $HOME/Library/Preferences/com.apple.Safari.plist
# put the following function into ~/.bash_login

function dws() { 

if [[ ! -e "$HOME/Library/Preferences/com.apple.Safari.plist" ]]; then
   printf "There is no com.apple.Safari.plist file in $HOME/Library/Preferences\x21\n"
   return 1
fi

defaults read com.apple.Safari | sed -En -e "s/^[[:space:]]*\"(com.apple.WebKit.searchField:.*)\" = .*$/\1/p" | while read item; do 
   #printf -- "$item\n"
   defaults delete com.apple.Safari "$item" 2>/dev/null
done

return 0

}     


Enable debug menu in Safari 3

To enable the debug menu in Safari 3, do the following
defaults write com.apple.Safari IncludeDebugMenu 1

And then enjoy the Web Inspector.

Safari <label> fix

if (navigator.userAgent.indexOf('Safari') != -1) {
	window.addEventListener('load', function() {
		var lock = false;
		var labels = document.getElementsByTagName('label');
		for (var i = 0; i < labels.length; i++)
			labels[i].addEventListener('click', function() {
				var input = (this.htmlFor ? document.getElementById(this.htmlFor) : this.getElementsByTagName('input')[0]);
				if (input && !lock) {
					input.focus();
					lock = true;
					input.click();
					lock = false;
				}
			});
	});
}

Remove favicons from Safari's cache

Safari caches the favicon for a site the first time it views it, even if the site doesn't have a favicon. This means if one is added later, or it is changed, you'll need to manually remove the cached file. This is pretty simple for a single site:

grep -r  "domain.tld" ~/Library/Safari/Icons/


Then, just remove all the files that match.