Remove a bunch of old, unused programs

This commit is contained in:
Sami Samhuri 2021-02-10 20:19:38 -08:00
parent d1e0bf1015
commit 76279629dd
70 changed files with 0 additions and 4503 deletions

Binary file not shown.

View file

@ -1,11 +0,0 @@
#!/bin/sh
TITLE="$1"
URL="$2"
if [[ "$TITLE" != "" ]] && [[ "$URL" != "" ]]; then
osascript -e "tell application \"Safari\" to add reading list item \"${URL}\" with title \"${TITLE}\""
else
echo "usage: `basename $0` <title> <url>"
exit 1
fi

3
bsh
View file

@ -1,3 +0,0 @@
#!/bin/sh
java -jar $HOME/apps/bsh-2.0b4.jar

View file

@ -1,20 +0,0 @@
#!/bin/bash
AS_GET_TITLE='
tell application "Google Chrome"
set frontIndex to active tab index of front window
get title of tab frontIndex of front window
end tell
'
AS_GET_URL='
tell application "Google Chrome"
set frontIndex to active tab index of front window
get URL of tab frontIndex of front window
end tell
'
TITLE=`osascript - <<<"$AS_GET_TITLE"`
URL=`osascript - <<<"$AS_GET_URL"`
~/bin/add-to-reading-list "$TITLE" "$URL"

View file

@ -1,3 +0,0 @@
#!/bin/bash
java -jar $(dirname $0)/compiler.jar "$@"

Binary file not shown.

View file

@ -1,3 +0,0 @@
#!/bin/sh
php $(dirname "$0")/composer.phar "$@"

Binary file not shown.

View file

@ -1,26 +0,0 @@
#!/bin/sh
CONFIG="$HOME/config"
NUMFILES=$#
while [ $# -gt 0 ]; do
FILE="$1"
shift
NEWFILE="${FILE#.}"
echo " * Configurizing $NEWFILE ..."
mv "$FILE" "$CONFIG/$NEWFILE"
ln -s "$CONFIG/$NEWFILE" "$FILE"
pushd "$CONFIG"
git add "$NEWFILE"
git commit -m "[NEW] Configurized '$NEWFILE'"
popd
done
echo " * $NUMFILES new files/directories"
echo " * Pushing configs to remote repository ... "
pushd "$CONFIG"
git push origin master
popd
echo " * Done"

View file

@ -1,112 +0,0 @@
#!/bin/bash
#
# convert-mkv-to-mp4.sh
#
# Copyright (c) 2014 Don Melton
#
about() {
cat <<EOF
$program 1.0 of July 9, 2014
Copyright (c) 2013-2014 Don Melton
EOF
exit 0
}
usage() {
cat <<EOF
Convert Matroska video file into MP4 format without transcoding.
Usage: $program [OPTION]... [FILE]
--help display this help and exit
--version output version information and exit
Requires \`ffprobe\`, \`ffmpeg\` and \`mp4track\` executables in \$PATH.
Output is written to current working directory.
EOF
exit 0
}
syntax_error() {
echo "$program: $1" >&2
echo "Try \`$program --help\` for more information." >&2
exit 1
}
die() {
echo "$program: $1" >&2
exit ${2:-1}
}
readonly program="$(basename "$0")"
case $1 in
--help)
usage
;;
--version)
about
;;
esac
readonly input="$1"
if [ ! "$input" ]; then
syntax_error 'too few arguments'
fi
if [ ! -f "$input" ]; then
die "input file not found: $input"
fi
readonly output="$(basename "$input" | sed 's/\.[^.]*$//').mp4"
if [ -e "$output" ]; then
die "output file already exists: $output"
fi
for tool in ffprobe ffmpeg mp4track; do
if ! $(which $tool >/dev/null); then
die "executable not in \$PATH: $tool"
fi
done
readonly container="$(ffprobe -show_format "$input" 2>/dev/null | sed -n '/^format_name=/p' | sed 's/^.*=//;s/,.*$//')"
if [ "$container" != 'matroska' ]; then
die "input file not Matroska format: $input"
fi
readonly track1="$(ffprobe -show_streams -select_streams a:0 "$input" 2>/dev/null | sed -n '/^codec_name=/p' | sed 's/^.*=//;s/,.*$//')"
readonly track2="$(ffprobe -show_streams -select_streams a:1 "$input" 2>/dev/null | sed -n '/^codec_name=/p' | sed 's/^.*=//;s/,.*$//')"
adjust_defaults=''
if [ "$track1" == 'ac3' ] && [ "$track2" == 'aac' ]; then
map_options='-map 0:2 -map 0:1'
adjust_defaults='true'
elif [ "$track1" == 'aac' ]; then
map_options='-map 0:1'
else
die "input file does not contain compatible audio tracks: $input"
fi
echo "Converting: $input" >&2
time {
ffmpeg \
-i "$input" \
-map 0:0 \
$map_options \
-c copy \
"$output" \
|| exit 1
if [ "$adjust_defaults" ]; then
mp4track --track-index 1 --enabled true "$output" &&
mp4track --track-index 2 --enabled false "$output" || exit 1
fi
}

View file

@ -1,7 +0,0 @@
#!/bin/zsh
set -e # bail on errors
TWOX_IMG_PATH="$1"
ONEX_IMG_PATH="${TWOX_IMG_PATH%.png}@1x.png"
convert -resize "50%" "$TWOX_IMG_PATH" "$ONEX_IMG_PATH"

View file

@ -1,21 +0,0 @@
#!/bin/bash
# Toggle the visibility of Desktop icons.
# Desktop icons are visible if the CreateDesktop setting is missing or
# if it exists and is set to 1, true, yes, or on (case insensitive).
# Desktop icons are hidden if the CreateDesktop setting exists and
# is set to any value other than 1, true, yes, or on.
# The $icons variable is the value of CreateDesktop if it exists or is
# the empty string if it doesn't.
icons=`defaults read com.apple.finder CreateDesktop 2> /dev/null`
shopt -s nocasematch
case "$icons" in
"" | "1" | "true" | "yes" | "on" )
defaults write com.apple.finder CreateDesktop 0 && killall Finder;;
* )
defaults write com.apple.finder CreateDesktop 1 && killall Finder;;
esac

26
domainr
View file

@ -1,26 +0,0 @@
#!/usr/bin/python
from sys import argv
from httplib import HTTPConnection
import json
def main(args):
for arg in args:
print "Looking up domains for %s..." % arg
con = HTTPConnection('domai.nr')
req = con.request('GET', '/api/json/search?q=%s' % arg)
res = con.getresponse()
if res.status == 200:
data = res.read()
sites = json.loads(data)
for s in sites['results']:
print "\t%s - %s" % (s['domain'], s['availability'])
else:
print "Uh oh, you got a %s %s. What the dilly?" % (res.status, res.reason)
if __name__ == "__main__":
main(argv[1:])

2
drop
View file

@ -1,2 +0,0 @@
#!/bin/sh
[[ x"$1" = x ]] && cp -R . ~/Dropbox/${PWD##*/} || cp -R "$@" ~/Dropbox/

1388
dropbox

File diff suppressed because one or more lines are too long

View file

@ -1,4 +0,0 @@
#!/bin/sh
file='/Applications/Dropbox.app/Contents/Resources/emblem-dropbox-uptodate.icns'
[ -e "$file" ] && mv -f "$file" "$file.bak"

11
encode
View file

@ -1,11 +0,0 @@
#!/bin/zsh
source="$1"
dest="$2"
if [[ -e "$dest" ]]; then
# echo "$source -> $dest (skipped, exists)"
else
echo "$source -> $dest"
# echo HandBrakeCLI --preset=\'iPad\' -e x264 --main-feature --markers -i \'$source\' -o \'$dest\'
noglob HandBrakeCLI --preset='iPad' -e x264 --main-feature --markers -i "$source" -o "$dest" >>'/var/log/encode.log' 2>>'/var/log/encode.err'
fi

View file

@ -1,183 +0,0 @@
#!/usr/bin/env ruby -w
require 'fileutils'
ADD_TO_ITUNES_DIR = File.expand_path('~/Music/iTunes/iTunes Media/Automatically Add to iTunes.localized')
MIN_SIZE = 50 * 1024 * 1024
def main
root_dir =
if ENV['TR_TORRENT_DIR']
File.join(ENV['TR_TORRENT_DIR'], ENV['TR_TORRENT_NAME'])
else
ARGV.shift
end
if File.exists?(root_dir)
puts "* Looking for archives in #{root_dir}..."
extract_archives(root_dir)
puts "* Encoding files in #{root_dir}..."
encode_and_add_to_itunes(root_dir)
elsif root_dir
puts "file not found: #{root_dir}"
exit 1
else
puts "error: expected directory in environment variable TR_TORRENT_DIR or as first argument"
exit 2
end
end
def extract_archives(dir)
if File.directory?(dir)
Dir.foreach(dir) do |filename|
next if filename == '.' || filename == '..'
_extract_archives(dir, filename)
end
else
_extract_archives(*File.split(dir))
end
end
def _extract_archives(dir, filename)
path = File.join(dir, filename)
if File.directory?(path)
extract_archives(path)
elsif filename =~ /\.rar$/
pwd = Dir.pwd
Dir.chdir(dir)
puts "* Extracting #{filename}..."
`unrar x '#{filename}'`
Dir.chdir(pwd)
end
end
def encode_and_add_to_itunes(dir)
if File.directory?(dir)
Dir.foreach(dir) do |filename|
next if filename == '.' || filename == '..'
_encode_and_add_to_itunes(dir, filename)
end
else
_encode_and_add_to_itunes(*File.split(dir))
end
end
def _encode_and_add_to_itunes(dir, filename)
path = File.join(dir, filename)
if File.directory?(path)
# puts "* Descending into #{path}..."
encode_and_add_to_itunes(path)
else
encoded_path = encode(File.expand_path(dir), filename)
if encoded_path == :noencode
puts "* No encoding required for #{path}, adding to iTunes"
add_to_itunes(path)
elsif encoded_path
puts "* Encoded as #{encoded_path}, adding to iTunes"
add_to_itunes(encoded_path)
File.unlink(encoded_path)
else
# skipped or failed
end
end
end
def add_to_itunes(path)
FileUtils.cp(path, ADD_TO_ITUNES_DIR)
puts "* Copied #{path} to #{ADD_TO_ITUNES_DIR}"
end
def encode(dir, filename)
path = File.join(dir, filename)
size = File.stat(path).size
if size < MIN_SIZE
return
end
ext = File.extname(filename)
encoded_path =
case ext
when '.m4v', '.mp4', '.mp3', '.m4a'
:noencode
when '.mkv'
# fall back to ffmpeg since the MKV conversion can't handle very many audio formats
encode_mkv(dir, filename, ext) || encode_video(dir, filename, ext)
when '.mpg', '.mpeg', '.avi', '.xvid'
encode_video(dir, filename, ext)
else
# puts "* Skipped unknown file type: #{path}"
end
encoded_path
end
def encode_mkv(dir, filename, ext)
encoded_filename = encoded_filename(filename, ext)
encoded_path = File.join('/tmp', encoded_filename)
if File.exists?(encoded_path)
# TODO: option to skill all or remove
puts "* Skipping #{filename}, it is already encoded"
encoded_path
else
puts "* Converting MKV to MPEG4: #{filename} -> #{encoded_filename}"
pwd = Dir.pwd
Dir.chdir('/tmp')
path = File.join(dir, filename)
`convert-mkv-to-mp4.sh '#{path}'`
if $?.success?
encoded_path
else
puts "!! Failed to encode #{filename}"
end
end
ensure
Dir.chdir(pwd) if pwd
end
def encode_video(dir, filename, ext)
encoded_filename = encoded_filename(filename, ext)
encoded_path = File.join('/tmp', encoded_filename)
if File.exists?(encoded_path)
# TODO: option to skip all or remove
puts "* Skipping #{filename}, it is already encoded"
encoded_path
else
puts "* Converting #{ext.sub('.', '').upcase} to MPEG4 with ffmpeg: #{filename} -> #{encoded_filename}"
pwd = Dir.pwd
Dir.chdir('/tmp')
path = File.join(dir, filename)
`ffmpeg -i '#{path}' -vcodec libx264 -r 24 -acodec libfaac '#{encoded_filename}'`
if $?.success?
encoded_path
else
puts "!! Failed to encode #{filename}"
end
end
ensure
Dir.chdir(pwd) if pwd
end
def encoded_filename(filename, ext)
filename.sub(/#{ext}$/, '.mp4')
end
SIZE_SUFFIXES = %w[bytes KB MB GB TB PB EB]
def human_size(n)
suffix_idx = 0
while n > 1023 && suffix_idx < SIZE_SUFFIXES.length - 1
n /= 1024.0
suffix_idx += 1
end
suffix = SIZE_SUFFIXES[suffix_idx]
if n - n.to_i < 0.01
n = n.to_i
else
n = "%0.2f" % n
end
"#{n} #{suffix}"
end
main if $0 == __FILE__

View file

@ -1,50 +0,0 @@
#!/usr/bin/env ruby
SourceDir = '/Volumes/Atlas/DVD/Movies'
DestDir = '/Volumes/Atlas/Purchased/Movies'
def quote(s)
'"' + s.gsub(/(["$`])/, '\\\\\1') + '"'
end
def files_to_encode
files = Dir[File.join(SourceDir, '*')].inject({}) do |files, source|
basename = File.basename(source)
unless basename == 'scrub.json' || File.exists?(File.join(source, 'noencode'))
outname = basename.sub(/\.dvdmedia$/, '').sub(/Disc/, 'Part')
dest = File.join(DestDir, outname) + '.m4v'
files[source] = dest
end
files
end
# If only one disc is to be encoded strip the "(Part X of Y)" suffix.
# Otherwise make sure the # of parts matches how many are actually encoded.
sources = files.keys
sources.grep(/^.*\(Disc\s/).each do |source|
prefix = source.match(/^(.*)\(Disc\s/)[1]
parts = sources.select { |source| source[prefix] }
if parts.length == 1
files[source].sub!(/\s\(Part[^)]+\)/, '')
else
parts.each do |source|
files[source].sub!(/Part (\d) of \d/, "Part \\1 of #{parts.length}")
end
end
end
files
end
def main
files_to_encode.each do |source, dest|
if File.exists?(dest)
puts "#{source} -> #{dest} (skipped, exists)"
else
puts "#{source} -> #{dest}"
`encode #{quote(source)} #{quote(dest)}`
end
end
end
main if $0 == __FILE__

View file

@ -1,23 +0,0 @@
#!/usr/bin/env ruby
video_path = ARGV[0]
thumbnail_path = ARGV[1]
time = ARGV[2] || "00:00:00.000"
unless video_path && thumbnail_path
$stderr.puts "Usage: #{$0} <video-path> <thumbnail-path> [HH:MM:SS.MMM]"
exit 10
end
unless File.exists?(video_path)
$stderr.puts "Input video does not exist: #{video_path}"
exit 20
end
if File.exists?(thumbnail_path)
$stderr.puts "Cowardly refusing to overwrite existing file at thumbnail path: #{thumbnail_path}"
exit 30
end
`ffmpeg -i '#{video_path}' -ss '#{time}' -vframes 1 '#{thumbnail_path}'`
exit $?.exitstatus

View file

@ -1,29 +0,0 @@
#!/usr/bin/env ruby
HomePath = File.expand_path('~') # better way to do this?
ProjectsPath = File.join(HomePath, 'Projects')
def git_repos_in(path, recurse=true)
dirs = Dir[File.join(path, '*')].select do |path|
File.directory?(path)
end
if recurse
dirs.map do |path|
# add subdirs to the list but ignore subdirs of git repos
[path] + (git_repo?(path) ? [] : git_repos_in(path, true))
end.flatten
else
dirs
end.select { |path| git_repo?(path) }
end
def git_dir_in(path)
gitpath = File.join(path, '.git')
File.exists?(gitpath) ? gitpath : nil
end
alias git_repo? git_dir_in
git_repos_in(ProjectsPath).each do |path|
puts path
end

View file

@ -1,68 +0,0 @@
#!/usr/bin/env ruby -w
require 'optparse'
USAGE_TEXT = "Usage: find-missing-semis.rb [options] <directory>"
Line = Struct.new(:num, :text)
def main
options = parse_options
dir = ARGV.first
if File.directory?(dir)
Dir[File.join(dir, '**/*.m')].each do |path|
find_missing_semis(path, options[:fix])
end
else
puts USAGE_TEXT
exit 1
end
end
def parse_options
options = {
fix: false,
}
OptionParser.new do |opts|
opts.banner = USAGE_TEXT
opts.on("-f", "--[no-]fix", "Insert missing semicolons automatically") do |f|
options[:fix] = f
end
end.parse!
options
end
def find_missing_semis(path, should_fix = false)
num = 0
pairs = []
current_pair = nil
File.readlines(path).each do |text|
num += 1
line = Line.new(num, text)
if current_pair
current_pair << line
pairs << current_pair
end
current_pair = [line]
end
missing_semicolon_pairs = pairs.select do |l1, l2|
l1.text =~ /^[-+]/ && l1.text !~ /;$/ && l2.text =~ /^\{/
end
missing_semicolon_pairs.each do |l1, l2|
puts "Missing semicolon at #{path}:#{l1.num}: #{l1.text}"
if should_fix
l1.text = l1.text.chomp + ";\n"
end
end
if should_fix && missing_semicolon_pairs.length > 0
lines = pairs.map(&:first) + [pairs.last.last]
text = lines.map(&:text).join
File.open(path, 'w') do |f|
f.print(text)
end
end
end
main if $0 == __FILE__

View file

@ -1,3 +0,0 @@
#!/bin/sh
adb kill-server && adb start-server

View file

@ -1,4 +0,0 @@
#!/bin/sh
lsregister=/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister
$lsregister -kill -r -domain local -domain system -domain user

View file

@ -1,9 +0,0 @@
#!/bin/bash
cd /Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Plug-ins/iPhoneOS\ Build\ System\ Support.xcplugin/Contents/MacOS/
dd if=iPhoneOS\ Build\ System\ Support of=working bs=500 count=255
printf "\xc3\x26\x00\x00" >> working
dd if=iPhoneOS\ Build\ System\ Support of=working bs=1 skip=127504 seek=127504
/bin/mv -n iPhoneOS\ Build\ System\ Support iPhoneOS\ Build\ System\ Support.original
/bin/mv working iPhoneOS\ Build\ System\ Support
chmod a+x iPhoneOS\ Build\ System\ Support

View file

@ -1,17 +0,0 @@
#!/bin/sh
set -e # bail on errors
BRANCH="${1:-master}"
REMOTE="${2:-origin}"
git checkout "$BRANCH"
git update "$REMOTE"
MERGED=$(git branch --merged "$BRANCH" | grep -v " ${BRANCH}\$" | grep -v ' master')
echo "$MERGED"
if [[ $? -eq 0 ]]; then
echo "$MERGED" | xargs git branch -d
else
true
fi

View file

@ -1,17 +0,0 @@
#!/bin/bash
#
# From https://blog.filippo.io/git-fixup-amending-an-older-commit/
set -e
function usage() {
name=$(basename "$0")
echo "Usage: ${name} <commit-ish> [git commit arguments]" >&2
exit 1
}
[[ -z "$1" ]] && usage
target=$(git rev-parse "$1")
git commit --fixup="$target" "${@:2}"
VISUAL=true EDITOR=true git rebase -i --autostash --autosquash "$target^"

View file

@ -10,5 +10,4 @@ if [[ -z "$REPO" ]] || [[ -z "$BRANCH" ]]; then
echo "usage: $(basename "$0") <remote> <branch (ref)>" echo "usage: $(basename "$0") <remote> <branch (ref)>"
exit 1 exit 1
fi fi
#open -a "Google Chrome" "https://github.com/${REPO}/compare/${BRANCH}?expand=1"
open "https://github.com/${REPO}/compare/${BRANCH}?expand=1" open "https://github.com/${REPO}/compare/${BRANCH}?expand=1"

View file

@ -1,148 +0,0 @@
#!/usr/bin/env python2.6
"""git pull-request
Automatically check out github pull requests into their own branch
"""
import sys
import getopt
import json
import urllib2
import os
import re
def main():
global repo
# parse command line options
try:
opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
except getopt.error, msg:
print msg
print "for help use --help"
sys.exit(2)
# process options
for o, a in opts:
if o in ("-h", "--help"):
print __doc__
sys.exit(0)
# get repo name
origin = os.popen('git remote -v').read()
m = re.search('^origin.*?github\.com.*?[:/]([^/]+/[^/]+)\.git\s*\(fetch\)$',origin,re.MULTILINE)
if(m == None or m.group(1) == ''):
print color_text("Failed to determine repo name from origin",'red',True)
repo = m.group(1)
# process arguments
if len(args):
ret = fetch(args[0])
else:
ret = show()
sys.exit(ret)
"""Nicely display info about a given pull request
"""
def display(pr):
if(pr['mergeable']):
conflict = ''
else:
conflict = color_text('*HAS CONFLICTS!*','red',True)
print "%s - %s %s" % (color_text('REQUEST %s' % pr['number'],'green'),pr['title'],conflict)
print " %s" % (color_text(pr['head']['label'],'yellow'))
print " by %s (%s)" % (pr['user']['name'],pr['user']['login'])
print " %s" % (color_text(pr['html_url'],'blue'))
print
"""List open pull requests
Queries the github API for open pull requests in the current repo
"""
def show():
global repo
print "loading open pull requests for %s..." % (repo)
print
url = "http://github.com/api/v2/json/pulls/%s/open" % (repo)
req = urllib2.Request(url)
response = urllib2.urlopen(req)
data = response.read()
if (data == ''):
print "failed to speak with github."
return 3
data = json.loads(data)
#print json.dumps(data,sort_keys=True, indent=4)
for pr in data['pulls']:
display(pr)
return 0
def fetch(pullreq):
global repo
print "loading pull request info for request %s..." % (pullreq)
print
url = "http://github.com/api/v2/json/pulls/%s/%s" % (repo, pullreq)
req = urllib2.Request(url)
response = urllib2.urlopen(req)
data = response.read()
if (data == ''):
print "failed to speak with github."
return 3
data = json.loads(data)
#print json.dumps(data,sort_keys=True, indent=4)
pr = data['pull']
display(pr)
local = 'pull-request-%s' % (pullreq)
branch = os.popen("git branch|grep '^*'|awk '{print $2}'").read().strip();
if(branch != pr['base']['ref'] and branch != local):
print color_text("The pull request is based on branch '%s' but you're on '%s' currently" % \
(pr['base']['ref'], branch),'red',True)
return 4
ret = os.system('git branch %s' % (local));
ret = os.system('git checkout %s' % (local));
if(ret != 0):
print "Failed to create/switch branch"
return 5
print "pulling from %s (%s)" % (pr['head']['repository']['url'], pr['head']['ref']);
ret = os.system('git pull %s %s' % (pr['head']['repository']['url'], pr['head']['ref']));
print
print color_text("done. examine changes and merge into master if good",'green');
return 0
"""Return the given text in ANSI colors
From http://travelingfrontiers.wordpress.com/2010/08/22/how-to-add-colors-to-linux-command-line-output/
"""
def color_text(text, color_name, bold=False):
colors = (
'black', 'red', 'green', 'yellow',
'blue', 'magenta', 'cyan', 'white'
)
if not sys.stdout.isatty():
return text
if color_name in colors:
return '\033[{0};{1}m{2}\033[0m'.format(
int(bold),
colors.index(color_name) + 30,
text)
else:
return text
if __name__ == "__main__":
main()

View file

@ -1,18 +0,0 @@
#!/bin/sh
set -e # bail on errors
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
DEFAULT_REMOTE=$(git config --get branch.${CURRENT_BRANCH}.remote || true) # don't fail
if [[ -z "$DEFAULT_REMOTE" ]]; then
DEFAULT_REMOTE=$(git config --get branch.master.remote)
fi
REMOTE="${1:-$DEFAULT_REMOTE}"
BRANCH="${2:-$CURRENT_BRANCH}"
git update "$REMOTE" develop
git checkout develop
git merge --no-ff "$BRANCH"
git push
git checkout "$BRANCH"
git push -u "$REMOTE" "$BRANCH"

View file

@ -22,4 +22,3 @@ if [[ -n "$MERGED_BRANCHES" ]]; then
else else
echo "No branches to remove" echo "No branches to remove"
fi fi

View file

@ -1,4 +0,0 @@
#!/bin/sh
FILENAME="$1"
git checkout $(git rev-list -n1 HEAD -- "$FILENAME")^ "$FILENAME"

View file

@ -1,10 +0,0 @@
#!/bin/sh
# Share a read-only git repo real quick
# https://twitter.com/tenderlove/status/579425350590935040
PORT=$1
GIT_DIR=$(git rev-parse --show-toplevel)
git update-server-info
ruby -run -e httpd -- -p "$PORT" "$GIT_DIR"

View file

@ -1,4 +0,0 @@
#!/bin/sh
defaults write com.apple.finder CreateDesktop false
killall Finder

BIN
iPhonePNG

Binary file not shown.

View file

@ -1,8 +0,0 @@
#!/bin/zsh
set -e # bail on errors
IMG_PATH="$1"
QUALITY="${2:-95}"
JPEG_IMG_PATH="${IMG_PATH%.*}.jpg"
convert -quality $QUALITY "$IMG_PATH" "$JPEG_IMG_PATH"

View file

@ -1,14 +0,0 @@
#!/bin/sh
cd "$HOME"
for FILE in config/*; do
pushd "$HOME"
DOTFILE=".${FILE##*/}"
if [[ -e "$DOTFILE" ]]; then
mkdir original-dot-files >/dev/null 2>/dev/null
echo "Existing file found at $DOTFILE, moving to ~/original-dot-files."
mv "$DOTFILE" original-dot-files/
fi
ln -s "$FILE" "$DOTFILE"
popd
done

View file

@ -1,86 +0,0 @@
#!/usr/bin/env ruby
require 'json'
require 'shellwords'
require 'time'
DEBUG = false
def log_file
@log_file ||= begin
at_exit { log_file.close }
File.open(File.expand_path('~/linky-notify.log'), 'a')
end
end
def log(line)
log_file.puts(line) if DEBUG
end
def munge_invalid_encoding(s)
s.chars.map { |c| c >= "\0" && c <= "\176" ? c : '?' }.join
end
def force_utf8(s)
if !s.valid_encoding?
log "forcing encoding of #{s[0..30].inspect}"
s = s.force_encoding('UTF-8')
if !s.valid_encoding?
log "munging #{s[0..30].inspect}"
s = munge_invalid_encoding(s)
end
log "s is now #{s[0..30].inspect}"
end
s
end
def e(s)
Shellwords.escape(force_utf8(s))
end
def notify_command(title, url)
notifier = File.expand_path '~/.rbenv/shims/terminal-notifier'
"#{notifier} -title #{e(title)} -message #{e(url)} -open #{e(url)} -actions 'Open' -closeLabel Ignore 2>&1"
end
def main
dir = ENV['WATCH_DIR']
created = JSON.parse(force_utf8(ENV['WATCH_CREATED']))
log "dir = #{dir}"
log "created = #{created.inspect}"
created.each do |filename|
path = File.join(dir, filename)
next if File.directory? path
lines = File.readlines(path).map { |l| force_utf8(l).strip }
title, url = nil, nil
until (title && url) || lines.empty?
line = lines.shift
next if line == ''
if line =~ /^http/
url ||= line
else
title ||= line
end
end
title ||= filename.sub(/^[0-9]+-/, '').sub(/\.[^.]+$/, '')
if url
command = notify_command(title, url)
log "[#{Time.now.iso8601}] #{command}"
output = `#{command}`
unless $?.success?
exit 1
end
archive_dir = File.join(dir, 'Archive')
Dir.mkdir(archive_dir) unless File.exists?(archive_dir)
File.rename(path, File.join(archive_dir, filename))
else
log "[#{Time.now.iso8601}] Failed to find URL in #{filename}: #{File.read(path)[0..200]}"
end
end
rescue Exception => e
log "#{e.class}: #{e.message}"
log e.backtrace.join("\n")
end
main if $0 == __FILE__

View file

@ -1,30 +0,0 @@
#!/bin/bash
set -e
if ! which northwatcher >/dev/null 2>/dev/null; then
npm install -g northwatcher
fi
if ! which terminal-notifier >/dev/null 2>/dev/null; then
brew install terminal-notifier
fi
machine_name=$(hostname -s)
mkdir -p $HOME/Dropbox/Apps/Linky/$machine_name/Archive
cp $HOME/Dropbox/Apps/Linky/net.samhuri.northwatcher.plist $HOME/Library/LaunchAgents
if [[ ! -e $HOME/.northwatcher ]]; then
echo "+ Dropbox/Apps/Linky/$machine_name ruby /Users/sjs/bin/linky-notify" >$HOME/.northwatcher
fi
if [[ ! -e /var/log/northwatcher.log ]]; then
echo "Enter your password to create /var/log/northwatcher.log."
sudo touch /var/log/northwatcher.log
sudo chown sjs:staff /var/log/northwatcher.log
fi
launchctl load $HOME/Library/LaunchAgents/net.samhuri.northwatcher.plist
echo "* Linky is set up!"

View file

@ -1,45 +0,0 @@
#!/usr/bin/env ruby
def main
output = `ls #{ARGV.map {|a| "\"#{a}\""}.join(' ')}`
lines = output.split("\n")
i = 0
most_commas = 0
number_of_commas = []
new_lines = lines.map do |line|
if line =~ /^[-dl][-rwxsS]{9}[@+\s]?/
size = line.split[4]
if size =~ /^\d+$/
new_size = commaify(size)
new_line = line.sub(size, new_size)
n = new_size.count(',')
number_of_commas << n
most_commas = n if n > most_commas
end
end
unless new_line
number_of_commas << 0
new_line = line
end
i += 1
new_line
end
new_lines.each_with_index do |line, i|
if line =~ /^[-dl][-rwxsS]{9}[@+\s]?/
size = line.split[4]
padded_size = (' ' * (most_commas - number_of_commas[i])) + size
new_lines[i] = line.sub(size, padded_size)
end
end
puts new_lines.join("\n")
end
def commaify(size)
number_with_delimiter(size)
end
def number_with_delimiter(n, delimiter = ',')
n.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimiter}")
end
main if __FILE__ == $0

View file

@ -1,16 +0,0 @@
#!/bin/sh
echo "* Save screenshtots to ~/Dropbox/Pictures/screenshots"
defaults write com.apple.screencapture location ~/Dropbox/Pictures/screenshots
echo "* Disable shadows on screenshots"
defaults write com.apple.screencapture disable-shadow -bool true
echo "* Set screenshot name to \"screenshot\""
defaults write com.apple.screencapture name screenshot
echo "* Show build duration in Xcode"
defaults write com.apple.dt.Xcode ShowBuildOperationDuration YES
echo "* Enable text selection in QuickLook"
defaults write com.apple.finder QLEnableTextSelection -bool YES

BIN
macosver

Binary file not shown.

61
newbox
View file

@ -1,61 +0,0 @@
#!/usr/bin/env bash
set -e # bail on errors
fail() {
echo "error: $@"
exit 1
}
function command_exists() {
which "$1" >/dev/null 2>/dev/null
}
install() {
if command_exists "$1"; then
return
fi
# apt (debian / ubuntu)
if command_exists aptitude; then
sudo aptitude install -y "$1"
# homebrew (os x)
elif command_exists brew; then
brew install "$1"
# rpm (redhat / centos / fedora)
elif command_exists yum; then
sudo yum install -y "$1"
# arch
elif command_exists pacman; then
sudo pacman -S "$1"
else
fail "Don't know how to install $1 on this box. Install $1 and run this again."
fi
}
install zsh || fail "Failed to install zsh."
install git || fail "Failed to install git."
cd ~
if ! [[ -d config ]]; then
git clone git://github.com/samsonjs/config || fail "cannot clone config repo"
fi
cd config
./init.sh
cd ..
echo " * Done!"
# FIXME figure out how to change the shell semi-interactively (only type in password)
if ! grep `id -u` /etc/passwd | grep zsh; then
#chsh -s `which zsh`
echo " *** Use chsh to change your shell to `which zsh`"
fi

View file

@ -1,62 +0,0 @@
#!/bin/sh
[[ $# -lt 1 ]] && exit 1
SCRIPT_DIR=${HOME}/bin
TYPE=$1
case "$TYPE" in
-bash)
TYPE=".bash"
SHEBANG="#!/bin/bash"
shift
;;
-pl)
TYPE=".pl"
SHEBANG="#!/usr/bin/env perl -w\nuse strict;"
shift
;;
-py)
TYPE=".py"
SHEBANG="#!/usr/bin/env python"
shift
;;
-rb)
TYPE=".rb"
SHEBANG="#!/usr/bin/env ruby"
shift
;;
-sh)
TYPE=".sh"
SHEBANG="#!/bin/sh"
shift
;;
-zsh)
TYPE=".zsh"
SHEBANG="#!/usr/bin/env zsh"
shift
;;
*)
TYPE=""
;;
esac
while [[ -n ${1} ]] ; do
SCRIPT=${SCRIPT_DIR}/${1}${TYPE}
if [[ -n ${TYPE} ]] && [[ ! -e ${SCRIPT} ]]; then
echo "${SHEBANG}" > ${SCRIPT}
chmod +x ${SCRIPT}
elif [[ ! -e ${SCRIPT} ]]; then
touch ${SCRIPT}
chmod +x ${SCRIPT}
elif [[ -w ${SCRIPT} ]] ; then
echo "Script ${SCRIPT} already exists, opening to edit anyways." >&2
else
echo "Script ${SCRIPT} is not writable, ignoring." >&2
SCRIPT=""
fi
SCRIPTS="${SCRIPTS} ${SCRIPT}"
shift
done
${EDITOR} ${SCRIPTS}

13
objcrun
View file

@ -1,13 +0,0 @@
#!/usr/bin/env zsh
if [[ -f "$1" ]]; then
NAME="$(basename ${1%.m})"
BINPATH="/tmp/$NAME"
clang -fobjc-arc -framework Foundation "$1" -o "$BINPATH" && "$BINPATH"
elif [[ ! -z "$1" ]]; then
echo "File not found: $1"
exit 2
else
echo "Usage: $(basename $0) <filename.m>"
exit 1
fi

View file

@ -1,19 +0,0 @@
#!/usr/bin/env ruby
def free_pages
`vm_stat`.split(/\n/).grep(/free/).first.scan(/\d+/).first.to_i
end
mega = 1024 * 1024.0
a = []
n = 0
free = free_pages
until free < 100_000
a << '-' * (100 * mega)
n += 100
free = free_pages
puts "Occupied #{n} MB, #{(4096 * free / mega).round(2)} MB still free"
end
puts 'full, looping forever...'
loop { sleep 1 }

View file

@ -1,87 +0,0 @@
#!/bin/sh
##
# This is script with usefull tips taken from:
# https://github.com/mathiasbynens/dotfiles/blob/master/.osx
#
echo " * Enable full keyboard access for all controls (e.g. enable Tab in modal dialogs)"
defaults write NSGlobalDomain AppleKeyboardUIMode -int 3
echo " * Enable subpixel font rendering on non-Apple LCDs"
defaults write NSGlobalDomain AppleFontSmoothing -int 2
echo " * Enable the 2D Dock"
defaults write com.apple.dock no-glass -bool true
echo " * Automatically hide and show the Dock"
defaults write com.apple.dock autohide -bool true
# echo " * Make Dock icons of hidden applications translucent"
# defaults write com.apple.dock showhidden -bool true
echo " * Disable menu bar transparency"
defaults write NSGlobalDomain AppleEnableMenuBarTransparency -bool false
echo " * Show all filename extensions in Finder"
defaults write NSGlobalDomain AppleShowAllExtensions -bool true
echo " * Use current directory as default search scope in Finder"
defaults write com.apple.finder FXDefaultSearchScope -string "SCcf"
echo " * Show Path bar in Finder"
defaults write com.apple.finder ShowPathbar -bool true
echo " * Show Status bar in Finder"
defaults write com.apple.finder ShowStatusBar -bool true
echo " * Expand save panel by default"
defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode -bool true
echo " * Disable the “Are you sure you want to open this application?” dialog"
defaults write com.apple.LaunchServices LSQuarantine -bool false
echo " * Disable shadow in screenshots"
defaults write com.apple.screencapture disable-shadow -bool true
echo " * Disable press-and-hold for keys in favor of key repeat"
defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false
echo " * Enable AirDrop over Ethernet and on unsupported Macs running Lion"
defaults write com.apple.NetworkBrowser BrowseAllInterfaces -bool true
echo " * Avoid creating .DS_Store files on network volumes"
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true
echo " * Disable the warning when changing a file extension"
defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false
echo " * Enable snap-to-grid for desktop icons"
/usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist
echo " * Disable the warning before emptying the Trash"
defaults write com.apple.finder WarnOnEmptyTrash -bool false
echo " * Require password 5 seconds after sleep or screen saver begins"
defaults write com.apple.screensaver askForPassword -int 1
defaults write com.apple.screensaver askForPasswordDelay -int 5
echo " * Enable tap to click (Trackpad)"
defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad Clicking -bool true
echo " * Enable Safaris debug menu"
defaults write com.apple.Safari IncludeInternalDebugMenu -bool true
echo " * Add a context menu item for showing the Web Inspector in web views"
defaults write NSGlobalDomain WebKitDeveloperExtras -bool true
echo " * Disable the Ping sidebar in iTunes"
defaults write com.apple.iTunes disablePingSidebar -bool true
echo " * Disable all the other Ping stuff in iTunes"
defaults write com.apple.iTunes disablePing -bool true
echo -n "Killing affected applications... "
for app in Safari Finder Dock Mail SystemUIServer; do killall "$app" >/dev/null 2>&1; done
echo "done!"

View file

@ -1,18 +0,0 @@
#!/bin/sh
ORIG_DIR=`basename "${PWD}"`
CODE_DIR="${ORIG_DIR}-project"
ZIP_FILE="${CODE_DIR}.zip"
echo "Zipping project in ${PWD}..."
pushd .. >/dev/null
cp -a "${ORIG_DIR}" "${CODE_DIR}"
pushd "${CODE_DIR}" >/dev/null
rm -rf .git* **/.git* **/build generated/
popd >/dev/null
zip -T -r -y "${ZIP_FILE}" "${CODE_DIR}"
rm -rf "${CODE_DIR}"
popd >/dev/null
echo "done, project is in ${ZIP_FILE}"

14
proj
View file

@ -1,14 +0,0 @@
#!/bin/sh
bail() {
echo "$@" >&2
exit 1
}
p="$HOME/Projects/$1"
[[ -d "$p" ]] && bail "project exists"
mkdir "$p"
cd "$p"
git init
touch Readme.md
$VISUAL .

View file

@ -1,9 +0,0 @@
#!/bin/sh
VOICES=$(say -v '?' | cut -d' ' -f1)
while true; do
VOICE=$(echo "$VOICES" | perl -e 'srand; rand($.) < 1 && ($line = $_) while <>; print $line;')
echo "$VOICE"
say -v "$VOICE" project seven
sleep 0.3
done

33
publish
View file

@ -1,33 +0,0 @@
#!/bin/bash
bail() {
echo fail: $*
exit 1
}
# test
if [[ "$1" = "-t" ]]; then
prefix=echo
shift
fi
[[ "$PUBLISH_HOST" != "" ]] && [[ "$publish_host" = "" ]] && publish_host="$PUBLISH_HOST"
[[ "$PUBLISH_DIR" != "" ]] && [[ "$publish_dir" = "" ]] && publish_dir="$PUBLISH_DIR"
orig_pwd="$PWD"
if [[ ! -f .publish ]]; then
while ! [[ -f .publish ]]; do
[[ "$PWD" = "/" ]] && bail "no .publish file found"
cd ..
done
subdir="${orig_pwd#$PWD/}"
fi
source .publish
cd $orig_pwd
if [[ $# -eq 0 ]]; then
$prefix rsync -aKv * "$publish_host":"${publish_dir}${subdir}"
else
$prefix rsync -aKv "$@" "$publish_host":"${publish_dir}${subdir}"
fi

View file

@ -1,17 +0,0 @@
#!/bin/bash
if [[ -d ~/Projects/web/samhuri.net ]]; then
cd ~/Projects/web/samhuri.net
elif [[ -d ~/samhuri.net ]]; then
cd ~/samhuri.net
else
echo "error: samhuri.net directory not found"
exit 1
fi
cd _blog
git clean -fq
git pull
cd ..
make publish_blog

View file

@ -1,20 +0,0 @@
#!/bin/bash
if [[ -d ~/Projects/web/samhuri.net ]]; then
cd ~/Projects/web/samhuri.net
elif [[ -d ~/samhuri.net ]]; then
cd ~/samhuri.net
else
echo "error: samhuri.net directory not found"
exit 1
fi
cd _blog
git clean -fq
git pull
cd ..
git clean -fq
git pull
make publish

View file

@ -1,5 +0,0 @@
#!/bin/zsh
ps ax | grep 'node discussd' | grep -v grep | awk '{print $1}' | xargs kill
cd ~/discussd
node discussd.js -h 0.0.0.0 -p 8000 >|discussd.log 2>>|discussd.log &!

View file

@ -1,86 +0,0 @@
#!/bin/bash
#
# This script runs a given command over a range of Git revisions. Note that it
# will check past revisions out! Exercise caution if there are important
# untracked files in your working tree.
#
# This came from Gary Bernhardt's dotfiles:
# https://github.com/garybernhardt/dotfiles
#
# Example usage:
# $ run-command-on-git-revisions origin/master master 'python runtests.py'
set -e
if [[ $1 == -v ]]; then
verbose=1
shift
fi
start_ref=$1
end_ref=$2
test_command=$3
main() {
abort_if_dirty_repo
enforce_usage
run_tests
}
abort_if_dirty_repo() {
set +e
git diff-index --quiet --cached HEAD
if [[ $? -ne 0 ]]; then
echo "You have staged but not committed changes that would be lost! Aborting."
exit 1
fi
git diff-files --quiet
if [[ $? -ne 0 ]]; then
echo "You have unstaged changes that would be lost! Aborting."
exit 1
fi
untracked=$(git ls-files --exclude-standard --others)
if [ -n "$untracked" ]; then
echo "You have untracked files that could be overwritten! Aborting."
exit 1
fi
set -e
}
enforce_usage() {
if [ -z "$test_command" ]; then
usage
exit 1
fi
}
usage() {
echo "usage: `basename $0` start_ref end_ref test_command"
}
run_tests() {
revs=`log_command git rev-list --reverse ${start_ref}..${end_ref}`
for rev in $revs; do
debug "Checking out: $(git log --oneline -1 $rev)"
log_command git checkout --quiet $rev
git log -n1
log_command $test_command
log_command git reset --hard --quiet
done
log_command git checkout --quiet $end_ref
debug "OK for all revisions!"
}
log_command() {
debug "=> $*"
eval "$@"
}
debug() {
if [ $verbose ]; then
echo $* >&2
fi
}
main

View file

@ -1,108 +0,0 @@
#!/bin/sh
#
# Speed improvements by using blocks by nitro.tm@gmail.com
#
# This script assumes that you have access to the 'dd' utility
# on both the local and remote host.
# dd transfer blocksize (8192 by default)
blocksize=8192
usage()
{
echo
echo "Usage: `basename $0` -u(pload) \$localfile \$remotefile [\$sshargs]"
echo " `basename $0` -d(ownload) \$remotefile \$localfile [\$sshargs]"
echo
echo " \$remotefile should be in the scp format, i.e.: [user@]host:filename"
echo " \$sshargs are option further ssh options such as a port specification"
echo " (-p 1234) or use of compression (-C)"
echo
echo " -u:"
echo " \$remotefile may be [user@]host: for uploading to your remote home directory"
echo " -d:"
echo " \$localfile may be a period (.) when downloading a remote file to the"
echo " current working directory."
echo
exit 1
}
[ -z "$1" -o -z "$2" -o -z "$3" ] && usage
option=$1
case $option in
-[uU]*)
localfile=$2
remote=$3
shift 3
sshargs="$*"
userhost=${remote%:*}
remotefile=${remote#*:}
if [ ! -f "$localfile" ]; then
echo "!! File not found: $localfile"
usage
fi
if [ x"$userhost" = x"$remote" ]; then usage; fi
if [ x"$remotefile" = x"$remote" -o -z "$remotefile" ]; then remotefile=`basename "$localfile"`; fi
echo "==>> Getting size of remote file:"
localsize=`ls -l "${localfile}" | awk '{ print $5 }'`
remotesize=`ssh $sshargs "$userhost" "[ -f \"${remotefile}\" ] && ls -l \"${remotefile}\"" | awk '{ print $5 }' `
[ -z "$remotesize" ] && remotesize=0
echo "=> Remote filesize: $remotesize bytes"
if [ $localsize -eq $remotesize ]; then
echo "=> Local size equals remote size, nothing to transfer."
exit 0;
fi
remainder=$((remotesize % blocksize))
restartpoint=$((remotesize - remainder))
blockstransferred=$((remotesize / blocksize))
echo "=> Resuming upload of '$localfile'"
echo " at byte: $restartpoint ($blockstransferred blocks x $blocksize bytes/block),"
echo " will overwrite the trailing $remainder bytes."
dd bs=$blocksize skip=$blockstransferred "if=${localfile}" | \
ssh $sshargs "$userhost" "dd bs=$blocksize seek=$blockstransferred of=\"$remotefile\""
echo "done."
;;
-[dD]*)
localfile=$3
remote=$2
shift 3
sshargs="$*"
userhost=${remote%:*}
remotefile=${remote#*:}
if [ x"$localfile" = x"." ]; then localfile=`basename "$remotefile"`; fi
if [ ! -f "$localfile" ]; then
localsize=0;
else
localsize=`ls -l "${localfile}" | awk '{ print $5 }'`
fi
[ x"$remotefile" = x"$remote" ] && usage
[ -z "$localsize" ] && localsize=0
remainder=$((localsize % blocksize))
restartpoint=$((localsize - remainder))
blockstransferred=$((localsize / blocksize))
echo "=> Resuming download of '$localfile'"
echo " at byte: $restartpoint ($blockstransferred blocks x $blocksize bytes/block)"
echo " filesize: $localsize; will overwrite the trailing $remainder bytes."
ssh $sshargs "$userhost" "dd bs=$blocksize skip=$blockstransferred \"if=${remotefile}\"" |
dd bs=$blocksize seek=$blockstransferred "of=$localfile"
;;
*)
usage
;;
esac

202
scrub
View file

@ -1,202 +0,0 @@
#!/usr/bin/env ruby
require 'json'
require 'optparse'
require 'ostruct'
class Scrubber
attr_reader :failures
attr_reader :options
attr_reader :root_dir
attr_reader :status
def self.scrub(root_dir, options = {})
new(root_dir, options).scrub
end
def initialize(root_dir, options = {})
@failures = []
@options = options
@root_dir = File.realpath(root_dir)
@status = :ok
end
def git_repo?(path)
File.exist?(File.join(path, '.git'))
end
def scrub(dir = @root_dir)
scrub_file = scrub_filename(dir)
if File.exist?(File.join(dir, 'noscrub'))
if File.exists?(scrub_file)
File.unlink(scrub_file)
end
return self
end
# restore file records if already scrubbed
existing_file_records = file_records(dir)
new_file_records = {}
# walk the directory
Dir[File.join(dir, '*')].each do |file|
# skip broken symlinks
next if File.symlink?(file) && !File.exist?(file)
# descend into subdirectories
if File.directory?(file)
# ignore git repos as the contents may change and git can fsck itself
scrub(file) unless git_repo?(file)
# scrub this file
else
basename = File.basename(file)
next if basename == 'scrub.json'
file_record = existing_file_records[basename] || {}
# convert old scrub.json records
if file_record.is_a?(String)
puts ">>> converting #{file} in #{scrub_filename(dir)} to new disk format" if options.verbose
# even out the scrubbing load throughout the month
random_timestamp = Time.now.to_i - (rand(30) * 86400)
file_record = { 'hash' => file_record, 'timestamp' => random_timestamp }
end
last_scrubbed = file_record['timestamp'] || 0
# skip files scrubbed in the last 30 days, unless --all was given
if !options.all && last_scrubbed >= Time.now.to_i - (30 * 86400)
puts ">>> skipping #{file} as it has been scrubbed recently (#{Time.at(last_scrubbed)})" if options.verbose
new_file_records[basename] = file_record
next
end
relative_filename = file.sub(@root_dir + '/', '')
result, hash = scrub_file(file, file_record['hash'])
case result
when :ok
file_record['hash'] = hash
puts "[ok] #{hash} - #{relative_filename}" if options.verbose
when :new
file_record['hash'] = hash
puts "[new] #{hash} - #{relative_filename}" if options.verbose
when :fail
# no change in scrub.json, just report the new sha
@failures << {
:filename => relative_filename,
:hash => hash,
:expected_hash => file_record['hash']
}
@status = :fail
puts "[FAIL] #{hash} - #{relative_filename} (previously had sha #{expected_hash})"
end
file_record['timestamp'] = Time.now.to_i
new_file_records[basename] = file_record
end
end
write_file_records(dir, new_file_records)
self
end
# Returns
def scrub_file(file, expected_hash)
basename = File.basename(file)
hash = sha1(file)
result =
if hash == expected_hash
result = :ok
elsif expected_hash
result = :fail
else
result = :new
end
[result, hash]
end
def ok?
@status == :ok
end
def fail?
@status == :fail
end
def sha1(filename)
# holy quoting batman!
`shasum "#{filename.gsub(/(\$)/, '\\\\\\1')}"`.split.first
end
def scrub_filename(dir)
File.join(dir, 'scrub.json')
end
def file_records(dir)
f = scrub_filename(dir)
if File.exist?(f)
JSON.parse(File.read(f))
else
{}
end
end
def write_file_records(dir, records)
return if options.phantom
f = scrub_filename(dir)
if records.size > 0
File.open(f, 'w') { |f| f.puts(JSON.fast_generate(records)) }
elsif File.exists?(f)
File.unlink(f)
end
end
end
def main
options = OpenStruct.new
options.all = false
options.phantom = false
options.verbose = false
OptionParser.new do |opts|
opts.banner = 'Usage: scrub [options] <root-directory>'
opts.on('-a', '--all', 'Scrub all files no matter when they were last scrubbed.') do
options.all = true
end
opts.on('-h', '--help', 'Show this help') do
puts opts
exit
end
opts.on('-p', '--phantom', 'Do everything except write scrub.json files. Useful for testing.') do
options.phantom = true
end
opts.on('-v', '--verbose', 'Log every file that is checked') do
options.verbose = true
end
end.parse!
root_dir = ARGV.shift || '.'
unless File.directory?(root_dir)
puts "error: #{root_dir} is not directory"
exit 1
end
result = Scrubber.scrub(root_dir, options)
# TODO print a summary
# Failures may have been lost in the noise so report them at the
# end as well when -v is given.
if result.fail? && options.verbose
puts
puts "*** Failures:"
# report failures
result.failures.sort do |a,b|
a[:filename] <=> b[:filename]
end.each do |failure|
puts "#{failure[:filename]}: expected #{failure[:expected_hash]}, but got #{failure[:hash]}"
end
exit 1
end
end
main if $0 == __FILE__

View file

@ -1,11 +0,0 @@
#!/bin/sh
for svc in $HOME/Library/LaunchAgents/*; do
echo "* Loading $svc"
launchctl load "$svc"
done
for svc in /Library/LaunchAgents/* /Library/LaunchDaemons/*; do
echo "* Loading $svc"
sudo launchctl load "$svc"
done

View file

@ -1,11 +0,0 @@
#!/bin/sh
for svc in $HOME/Library/LaunchAgents/*; do
echo "* Unloading $svc"
launchctl unload "$svc"
done
for svc in /Library/LaunchAgents/* /Library/LaunchDaemons/*; do
echo "* Unloading $svc"
sudo launchctl unload "$svc"
done

View file

@ -1,4 +0,0 @@
#!/bin/sh
defaults write com.apple.finder CreateDesktop true
killall Finder

View file

@ -1,86 +0,0 @@
#!/usr/bin/env ruby
require 'csv'
def darwin?
@darwin ||= `uname`.strip == 'Darwin'
end
def mktemp
if darwin?
`mktemp -t $$`.strip
else
`mktemp`.strip
end
end
def delimit(n, delimiter = ',')
n.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimiter}")
end
Units = %w[KB MB GB TB]
def human_size(n)
unit = 'bytes'
units = Units.dup
while n > 1024 && units.length > 0
n /= 1024.0
unit = units.shift
end
"#{delimit(n.round(2))} #{unit}"
end
def analyze_rdb(rdbfile, keyfile)
size = human_size(File.stat(rdbfile).size)
puts "Getting key info for #{rdbfile} (#{size}), this can take a while..."
`rdb -c memory #{rdbfile} > #{keyfile}`
keyfile
end
def sort_keys(rdbfile)
keyfile = rdbfile.sub('rdb', 'csv')
sortedkeyfile = rdbfile.sub('.rdb', '-sorted.csv')
if !File.exists?(keyfile)
analyze_rdb(rdbfile, keyfile)
end
lines = File.readlines(keyfile)
lines.shift # drop the header
n = lines.length
print "Munging #{delimit(n)} rows..."
rows = []
while line = lines.shift
row = line.strip.split(',')
size = row[3].to_i
key = row[2].sub(/^"/, '').sub(/"$/, '')
type = row[1]
num_elements = row[5]
len_largest = row[6]
row = [size, key, type, num_elements, len_largest]
rows << row
if rows.length % (n / 50) == 0
print '.'
end
end
puts
puts "Sorting..."
rows = rows.sort { |a,b| b[0] <=> a[0] }
print "Writing..."
CSV.open(sortedkeyfile, 'wb') do |csv|
# header
csv << %w[size key type num_elements len_largest_element]
while row = rows.shift
csv << row
if rows.length % (n / 50) == 0
print '.'
end
end
puts
puts "Done."
end
end
def main
sort_keys(ARGV.shift)
end
main if $0 == __FILE__

View file

@ -1,24 +0,0 @@
#!/usr/bin/env ruby -w
svg_path = ARGV.shift
png_path = ARGV.shift
png_test_path = "/tmp/identify.png"
File.unlink(png_test_path) if File.exist?(png_test_path)
puts `inkscape -z -e '#{png_test_path}' -d 72 '#{svg_path}'`
info = `identify '#{png_test_path}'`
File.unlink(png_test_path) if File.exist?(png_test_path)
dimensions = info.split[2]
width, height = dimensions.split('x').map(&:to_i)
if width == 0 || height == 0
$stderr.puts "Failed to get SVG dimensions"
exit 1
end
name = File.basename(svg_path).sub /\.svg$/, ''
png_2x_path = File.join(png_path, "#{name}@2x.png")
puts `inkscape -z -e '#{png_2x_path}' -w #{2 * width} -h #{2 * height} -d 72 '#{svg_path}'`
png_3x_path = File.join(png_path, "#{name}@3x.png")
puts `inkscape -z -e '#{png_3x_path}' -w #{3 * width} -h #{3 * height} -d 27 '#{svg_path}'`

36
tarscp
View file

@ -1,36 +0,0 @@
#!/bin/sh
#
# usage: tarscp <host> [remote-dir [local-file ...]]
#
# Uses tar, bzip2, and ssh to transfer files to a remote host. It's
# faster than scp -Cr with many small files.
#
# If no files are specified the current directory is copied to
# remote-dir on host. If remote-dir is not specified the name of the
# current directory is used as the remote directory.
#
# You may want to use gzip instead of bzip2 on slower machines,
# bzip2's runtime can be longer than transfer times with fast
# connections.
#
usage() {
echo "usage: $(basename $0) <host> [remote-dir [local-file ...]]"
exit 1
}
[[ $# < 1 ]] && usage
HOST="$1"; shift
DIR="$1"; shift
if [[ "$1" = "" ]]; then
FILES="."
if [[ "$DIR" = "" ]]; then
DIR=$(basename $(dirname $PWD/.))
fi
else
FILES="$@"
fi
tar cjf - "$FILES" | ssh "$HOST" "mkdir -p '${DIR}' && tar xjf - -C '${DIR}'"

View file

@ -1,4 +0,0 @@
#!/bin/sh
launchctl list | grep UIKitApplication | awk '{print $3}' | xargs launchctl remove

View file

@ -1,38 +0,0 @@
#!/bin/zsh
set -e # bail on errors
function filesize() {
stat "$1" | cut -d' ' -f8
}
ORIG_IMG_PATH="$1"
# ignore screenshots created by this script or upload-to-s3
if [[ "$ORIG_IMG_PATH" == *"@1x.png" ]] || [[ "$ORIG_IMG_PATH" == *"@1x.jpg" ]]; then
exit 0
fi
BIG_SIZE=$((666 * 1024))
WEB_IMG_PATH="$ORIG_IMG_PATH"
ls -lh "$WEB_IMG_PATH"
if [[ $(filesize "$ORIG_IMG_PATH") -gt $BIG_SIZE ]]; then
echo "TOO BIG, DERETINA..."
WEB_IMG_PATH="${ORIG_IMG_PATH%.png}@1x.png"
convert -resize "50%" "$ORIG_IMG_PATH" "$WEB_IMG_PATH"
ls -lh "$WEB_IMG_PATH"
if [[ $(filesize "$WEB_IMG_PATH") -gt $BIG_SIZE ]]; then
echo "STILL TOO BIG, COVERTING TO JPEG"
WEB_IMG_PATH="${ORIG_IMG_PATH%.png}@1x.jpg"
convert -quality 95 -resize "50%" "$ORIG_IMG_PATH" "$WEB_IMG_PATH"
ls -lh "$WEB_IMG_PATH"
fi
fi
FILENAME=$(basename "$WEB_IMG_PATH")
FILENAME="${FILENAME// /_}"
IMG_HOST="static.samhuri.net"
URL="http://${IMG_HOST}/${FILENAME}"
echo -n "$URL" | pbcopy
s3cmd put "$WEB_IMG_PATH" "s3://${IMG_HOST}/${FILENAME}"
echo "$URL"

View file

@ -1,62 +0,0 @@
#!/usr/bin/perl -w
use strict;
sub mail_status {
$date = `date +%Y%m%d-%h:%m`;
open(MAIL, "|/usr/lib/sendmail -t");
print MAIL "To: $info{to}\n";
print MAIL "From: $info{from}\n";
print MAIL "Subject: $info{host} status report for $date\n";
print MAIL "$info{host} has been up:\n$info{uptime}\n\n";
print MAIL "memory usage (mb):\n$info{mem}\n\n";
print MAIL "disk usage:\n$info{disk}\n\n";
print MAIL "service status:\n$info{services}\n\n";
close (MAIL);
}
my ($year, $month, $day) = (`date +%Y`, `date +%m`, `date +%d`);
my $logDir = "/var/log";
my @logFiles = qw( messages apache2/access_log apache2/error_log );
my @targetFiles = qw( messages apache_access apache_error );
my $remoteHost = "home.nofxwiki.net";
my $remoteDir = "/home/sjs/log/nofxwiki.net/$year/$month";
my $filePrefix = "$day-";
my @services = qw( apache2 clamd courier-authlib courier-imapd courier-imapd-ssl iptables mysql spamd sshd );
my $file;
my $remoteFile;
for (my $i = 0; $i < @logFiles; $i++) {
$file = $logFiles[$i];
$remoteFile = $torgetFiles[$i];
open $file, "tail -f $logDir/$file |" \
or die "Could not open 'tail -f $file', bailing!\n";
open "ssh-$file", "| ssh $remoteHost 'cat >> $remoteDir/$remoteFile'" \
or die "Could not open 'ssh $remoteHost 'cat >> $remoteDir/$remoteFile\n'', bailing!\n";
}
my $ticks = 0;
my %info;
while (1) {
foreach my $file (@logFiles) {
while (my $line = <$file>) {
print "ssh-$file" $lines;
}
}
sleep 300; # 5 minutes
$ticks++;
if ($ticks == 72) { # 360 min = 6 hr
$ticks = 0;
$info{host} = `hostname --fqdn`;
$info{uptime} = `w`;
$info{mem} = `free -m`;
$info{disk} = `df -h`;
foreach my $svc (@services) {
open SVC, "/etc/init.d/$svc status |";
@info{services} += <SVC>;
close SVC;
}
&mail_status(%info);
}
}

View file

@ -1,964 +0,0 @@
#!/bin/sh
# Author: Olivier HO-A-CHUCK
# Date: June 27th 2013 (update June 12th 2015)
# Last update:
# - fixed -L for years earlier than 2015
# - "/Users/${USER}" changed for "${HOME}" for better compliancy with home directory differents than /Users
# - Add wwdc 2015 video download (+ fixed issue with "Managing 3D Assets with Model I/O" session label).
# - fixed issue with names like I/O
# - adding download of ALL sample code (including those to grab on Apple documentation web site)
# - adding check for network connectivity (bash does not handle connectivity error for you)
# - fixing issue with name using comma in title (like ", part 1") - some might download them twice if using an early script - sorry ;(
#
#
# License: Do what you want with it. But notice that this script comes with no warranty and will not be maintained.
# Usage: wwdcVideoGet-curlVersion.sh
# To get 2013 tech-talks content: ./wwdcVideoGet-curlVersion.sh -e tech-talks
#
# TODO:
# - make 2012 videos download possible (it's feasible but more painful than for 2013 and 2014, so time consuming...)
# - wrong password does not give proper error message!
# - display some statistics: total time of download (+ begin and end), total downloaded size of content
# - check available disk space for possible alert (in particular if HD video are getting donwloaded with less than 60 GB of disk space)
VERSION="1.8.4"
DEFAULT_FORMAT="SD"
DEFAULT_YEAR="2015"
DEFAULT_EVENT="wwdc"
SELECTIVE_SESSION_MODE=false
LIST_MODE=false
VERBOSE=false
LOGIN=false
ITUNES_LOGIN=""
TMP_DIR="/tmp/wwdc-session.tmp"
VIDEO_URL_WWDC="https://developer.apple.com/videos/wwdc"
VIDEO_URL_TECHTALK="https://developer.apple.com/tech-talks/videos/"
SAMPLE_CODE_ROOT_URL="https://developer.apple.com/"
doGetWWDCPost2012 () {
ituneslogin=$1
itunespassword=$2
FORMAT=$3
if [ ${VERBOSE} == true ];
then
echo "Sessions to be downloaded: ${SESSION_WANTED}"
echo "Output directory: ${WWDC_DIRNAME}"
fi
mkdir -p $TMP_DIR
# Processing Authentifcation - depreciated now (but kept for copy/pasters like me that might need to use this as a snippet for other uses)
if [ -z "${ituneslogin}" ];
then
# Dynamically get the key value as this can change (it did change for instance when Apple had to turn down their developer Portal for a week)
if [ ${VERBOSE} == true ];
then
echo "Getting appIDKey..."
fi
key=$(curl -s -L https://developer.apple.com/iphone | grep 'login?&appIdKey=' | sed -e 's/\(.*login?&appIdKey=\)\(.*\)\(&.*\)/\2/' | awk 'NR==1 {print $1}')
if [ ${VERBOSE} == true ];
then
echo "appIDKey: ${key}"
fi
cookies=(--cookies=on --keep-session-cookies)
action=$(curl -s 'https://daw.apple.com/cgi-bin/WebObjects/DSAuthWeb.woa/wa/login?appIdKey='"${key}" | grep '\ action=' | awk '{ print $4 }' | cut -f2 -d"=" | sed -e "s/^.*\"\(.*\)\".*$/\1/")
curl -s --cookie-jar $TMP_DIR/cookies.txt "https://daw.apple.com${action}" -d theAccountName="${ituneslogin}" -d theAccountPW="${itunespassword}" > /dev/null
curl -s --cookie $TMP_DIR/cookies.txt \
--cookie-jar $TMP_DIR/cookies.txt \
${VIDEO_URL} > $TMP_DIR/video.html
else
curl -silent ${VIDEO_URL} > $TMP_DIR/video.html
fi
cat ${TMP_DIR}/video.html | sed -e '/class="thumbnail-title/,/<div class="error">/!d' > $TMP_DIR/video-cleaned.html
if [ -f ${TMP_DIR}/titles.txt ] ; then
rm ${TMP_DIR}/titles.txt
fi
cat ${TMP_DIR}/video-cleaned.html | while read line; do
sessionNum=`echo $line | grep -o -E '<li class="thumbnail-title">(.*)</li><li class="thumbnail-(id|play)">(.*)</li>' | grep -o -E 'Session [0-9]*' | cut -d' ' -f2`
title_array[$sessionNum]=`echo $line | grep -o -E '<li class="thumbnail-title">(.*)</li><li class="thumbnail-(id|play)">(.*)</li>' | cut -d'>' -f2 | sed 's/<\/li$//g'`
echo "$sessionNum,${title_array[$sessionNum]}" >> $TMP_DIR/titles.txt
done
`sed -n '/^,/!p' $TMP_DIR/titles.txt > $TMP_DIR/titles.txt.tmp && mv $TMP_DIR/titles.txt.tmp $TMP_DIR/titles.txt`
while read line
do
sessionNum=`echo $line | cut -d',' -f1`
sessionTitle=`echo $line | cut -d',' -f2`
title_array[$sessionNum]=${sessionTitle}
done < ${TMP_DIR}/titles.txt
if [ ${LIST_MODE} == true ];
then
echo "Available videos:"
echo "-----------------"
cat ${TMP_DIR}/titles.txt | cut -d',' -f1 | while read line; do
echo "${line}: ${title_array[$line]}"
#printf '%s\n' "${title_array[@]}"
done;
exit
fi
echo "******* DOWNLOADING PDF FILES ********"
# PDF
mkdir -p "${WWDC_DIRNAME}"/PDFs
# do the rm *.download only if files exist
FILES_LIST="$(ls "${WWDC_DIRNAME}"/PDFs/*.download 2>/dev/null)"
if [ -z "$FILES_LIST" ]; then
# echo "Hello, de Lu!"
:
else
echo "Some download was aborted last time you ran this script."
rm "${WWDC_DIRNAME}"/PDFs/*.download
echo "Cleaning non fully downloaded files: OK."
fi
i=0
cat ${TMP_DIR}/video.html | grep -o -E 'href="(http:\/\/devstreaming.apple.com\/videos\/wwdc\/'${YEAR}'\/[0-9a-zA-Z]*\/[0-9]{1,5}\/([0-9]{1,5}|[0-9]{1,5}_.*)\.pdf\?dl=1+)"' | cut -d'"' -f2 | sed -e 's/_sd_/_/g' -e 's/.mov/.pdf/g' | while read line; do
filename=`echo ${line} | cut -d'/' -f9 | cut -d'?' -f1`
session_number=`echo $line | grep -o -E '\/([0-9]+|[0-9]+_.*)\.pdf' | grep -o -E "[0-9]{3,4}"`
if [ ${SELECTIVE_SESSION_MODE} == true ];
then
if `echo ${SESSION_WANTED} | grep "${session_number}" 1>/dev/null 2>&1`
then
dest_path="${WWDC_DIRNAME}/PDFs/${session_number} - ${title_array[$session_number]}.pdf"
old_dest_path="${WWDC_DIRNAME}/PDFs/${filename}"
if [ -f "${dest_path}" ];
then
echo "${dest_path} already downloaded (nothing to do!)"
elif [ -f "${old_dest_path}" ];
then
echo "Rename existing file: ${old_dest_path} => ${dest_path}"
mv "${old_dest_path}" "${dest_path}"
else
echo "downloading PDF for session ${session_number}: $line"
curl $line > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
fi
else
dest_path="${WWDC_DIRNAME}/PDFs/${session_number} - ${title_array[$session_number]}.pdf"
old_dest_path="${WWDC_DIRNAME}/PDFs/${filename}"
if [ -f "${dest_path}" ];
then
echo "${dest_path} already downloaded (nothing to do!)"
elif [ -f "${old_dest_path}" ];
then
echo "Rename existing file: ${old_dest_path} => ${dest_path}"
mv "${old_dest_path}" "${dest_path}"
else
echo "downloading PDF for session ${session_number}: $line"
curl $line > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
fi
((i+=1))
done
echo "******* DOWNLOADING ${FORMAT} VIDEOS ********"
# Videos ${FORMAT}
mkdir -p "${WWDC_DIRNAME}"/${FORMAT}-VIDEOs
# do the rm *.download only if files exist
FILES_LIST="$(ls "${WWDC_DIRNAME}"/${FORMAT}-VIDEOs/*.download 2>/dev/null)"
if [ -z "$FILES_LIST" ]; then
#echo "All downloads will go to your Desktop/WWDC-2013 folder!"
:
else
echo "Some download was aborted last time you ran this script."
rm "${WWDC_DIRNAME}"/${FORMAT}-VIDEOs/*.download
echo "Cleaning non fully downloaded files: OK"
fi
i=0
# TODO: / WARNING (for possible future function merge): note that devstreaming url does use hard coded "wwdc" in it, were tech-talks function url is "techtalks" (whithout dash)
if [ ${YEAR} = "2013" ];
then
REGEXFILE="[0-9a-zA-Z]*\/[0-9]{1,5}\/[0-9]{1,5}-${FORMAT}\.mov"
elif [ ${YEAR} = "2014" ];
then
if [ "${FORMAT}" = "HD" ];
then
LC_FORMAT="hd"
else
LC_FORMAT="sd"
fi
REGEXFILE="[0-9a-zA-Z]*\/[0-9]{1,5}\/[0-9]{1,5}_${LC_FORMAT}_.*\.mov"
else
echo "coucou"
fi
cat ${TMP_DIR}/video.html | grep -o -E 'href="(http:\/\/devstreaming.apple.com\/videos\/wwdc\/'${YEAR}'/'${REGEXFILE}'\?dl=1+)"' | cut -d'"' -f2 | while read line; do
#echo $line
filename=`echo ${line} | cut -d'/' -f9 | cut -d'?' -f1`
session_number=`echo $line | grep -o -i -E '/[0-9]+[_-]'${FORMAT}'[^/]*.mov' | grep -o -E '[0-9]+' | head -1`
if [ ${SELECTIVE_SESSION_MODE} == true ];
then
if `echo ${SESSION_WANTED} | grep "${session_number}" 1>/dev/null 2>&1`
then
dest_path="${WWDC_DIRNAME}/${FORMAT}-VIDEOs/${session_number} - ${title_array[$session_number]}-${FORMAT}.mov"
old_dest_path="${WWDC_DIRNAME}/${FORMAT}-VIDEOs/${filename}"
if [ -f "${dest_path}" ]
then
echo "${dest_path} already downloaded (nothing to do!)"
elif [ -f "${old_dest_path}" ];
then
echo "Rename existing file: ${old_dest_path} => ${dest_path}"
mv "${old_dest_path}" "${dest_path}"
else
echo "downloading ${FORMAT} Video for session ${session_number}: $line"
curl $line > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
fi
else
dest_path="${WWDC_DIRNAME}/${FORMAT}-VIDEOs/${session_number} - ${title_array[$session_number]}-${FORMAT}.mov"
old_dest_path="${WWDC_DIRNAME}/${FORMAT}-VIDEOs/${filename}"
if [ -f "${dest_path}" ]
then
echo "${dest_path} already downloaded (nothing to do!)"
elif [ -f "${old_dest_path}" ];
then
echo "Rename existing file: ${old_dest_path} => ${dest_path}"
mv "${old_dest_path}" "${dest_path}"
else
echo "downloading ${FORMAT} Video for session ${session_number}: $line"
curl $line > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
fi
((i+=1))
done
rm -Rf ${TMP_DIR}
}
#**************************************************************************************#
# TECH TALK #
#**************************************************************************************#
doGetTT2013 () {
ituneslogin=$1
itunespassword=$2
FORMAT=$3
if [ ${VERBOSE} == true ];
then
echo "Sessions to be downloaded: ${SESSION_WANTED}"
echo "Output directory: ${WWDC_DIRNAME}"
fi
mkdir -p $TMP_DIR
# Dynamically get the key value as this can change (it did change for instance when Apple had to turn down their developer Portal for a week)
if [ ${VERBOSE} == true ];
then
echo "Getting appIDKey..."
fi
key=$(curl -s -L https://developer.apple.com/iphone | grep 'login?&appIdKey=' | sed -e 's/\(.*login?&appIdKey=\)\(.*\)\(&.*\)/\2/' | awk 'NR==1 {print $1}')
if [ ${VERBOSE} == true ];
then
echo "appIDKey: ${key}"
fi
cookies=(--cookies=on --keep-session-cookies)
action=$(curl -s 'https://daw.apple.com/cgi-bin/WebObjects/DSAuthWeb.woa/wa/login?appIdKey='"${key}" | grep '\ action=' | awk '{ print $4 }' | cut -f2 -d"=" | sed -e "s/^.*\"\(.*\)\".*$/\1/")
curl -s --cookie-jar $TMP_DIR/cookies.txt "https://daw.apple.com${action}" -d theAccountName="${ituneslogin}" -d theAccountPW="${itunespassword}" > /dev/null
curl -s --cookie $TMP_DIR/cookies.txt \
--cookie-jar $TMP_DIR/cookies.txt \
${VIDEO_URL} > $TMP_DIR/video.html
cat ${TMP_DIR}/video.html | sed -e '/class="thumbnail-title/,/<div class="error">/!d' > $TMP_DIR/video-cleaned.html
if [ -f ${TMP_DIR}/titles.txt ] ; then
rm ${TMP_DIR}/titles.txt
fi
cat ${TMP_DIR}/video-cleaned.html | while read line; do
echo $line | grep -o -E '<li class="thumbnail-title">(.*)</li><li class="thumbnail-(id|play)">(.*)</li>' | cut -d'>' -f2 | sed 's/\<\/li$//g' >> $TMP_DIR/titles.txt
done
while read line
do
title_array+=("$line")
done < ${TMP_DIR}/titles.txt
if [ ${LIST_MODE} == true ];
then
echo "Available videos:"
echo "-----------------"
cat ${TMP_DIR}/titles.txt | cut -d';' -f1 | while read line; do
echo "$line: ${title_array[$line]}"
#printf '%s\n' "${title_array[@]}"
done;
exit
fi
echo "******* DOWNLOADING PDF FILES ********"
# PDF
mkdir -p "${WWDC_DIRNAME}"/PDFs
# do the rm *.download only if files exist
FILES_LIST="$(ls "${WWDC_DIRNAME}"/PDFs/*.download 2>/dev/null)"
if [ -z "$FILES_LIST" ]; then
#echo "All downloads will go to your Desktop/WWDC-2013 folder!"
:
else
echo "Some download was aborted last time you ran this script."
rm "${WWDC_DIRNAME}"/PDFs/*.download
echo "Cleaning non fully downloaded files: OK."
fi
i=0
cat ${TMP_DIR}/video.html | grep -o -E 'href="(http:\/\/devstreaming.apple.com\/videos\/techtalks\/2013/[0-9a-zA-Z_\-]*\/[0-9a-zA-Z_\-]*\.pdf\?dl=1+)"' | cut -d'"' -f2 | while read line; do
session_number=`echo $line | grep -o -E '/[0-9]+_' | grep -o -E [0-9]+`
if [ ${SELECTIVE_SESSION_MODE} == true ];
then
if `echo ${SESSION_WANTED} | grep "${session_number}" 1>/dev/null 2>&1`
then
dest_path="${WWDC_DIRNAME}/PDFs/${session_number} - ${title_array[$i]}.pdf"
if [ -f "${dest_path}" ]
then
echo "${dest_path} already downloaded (nothing to do!)"
else
echo "downloading PDF for session ${session_number}: $line"
curl $line > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
fi
else
dest_path="${WWDC_DIRNAME}/PDFs/${session_number} - ${title_array[$i]}.pdf"
if [ -f "${dest_path}" ]
then
echo "${dest_path} already downloaded (nothing to do!)"
else
echo "downloading PDF for session ${session_number}: $line"
curl $line > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
fi
((i+=1))
done
echo "******* DOWNLOADING ${FORMAT} VIDEOS ********"
# Videos ${FORMAT}
mkdir -p "${WWDC_DIRNAME}"/${FORMAT}-VIDEOs
# do the rm *.download only if files exist
FILES_LIST="$(ls "${WWDC_DIRNAME}"/${FORMAT}-VIDEOs/*.download 2>/dev/null)"
if [ -z "$FILES_LIST" ]; then
#echo "All downloads will go to your Desktop/WWDC-2013 folder!"
:
else
echo "Some download was aborted last time you ran this script."
rm "${WWDC_DIRNAME}"/${FORMAT}-VIDEOs/*.download
echo "Cleaning non fully downloaded files: OK."
fi
i=0
# TODO: This extra if then elif test should not be there (duplicated code), but I don't know so far how to use $FORMAT in the grep -o -E regex! :(
# Word boundaries should help like \<$FORMAT\>, but I'm not sure this is compliant with all grep versions. And I don't want to use egrep (non standard).
# I know even with if then, this can be improved in terms or number of code lines. But hey, I'm a Marketing guys. Sorry for the very quick and dirty bit :(((
if [ ${FORMAT} = "HD" ];
then
cat ${TMP_DIR}/video.html | grep -o -E 'href="(http:\/\/devstreaming.apple.com\/videos\/techtalks\/2013/[0-9a-zA-Z_]*\/[0-9a-zA-Z_]*-hd\.mov\?dl=1+)"' | cut -d'"' -f2 | while read line; do
session_number=`echo $line | grep -o -E '/[0-9]+_' | grep -o -E [0-9]+`
if [ ${SELECTIVE_SESSION_MODE} == true ];
then
if `echo ${SESSION_WANTED} | grep "${session_number}" 1>/dev/null 2>&1`
then
dest_path="${WWDC_DIRNAME}/${FORMAT}-VIDEOs/${session_number} - ${title_array[$i]}-${FORMAT}.mov"
if [ -f "${dest_path}" ]
then
echo "${dest_path} already downloaded (nothing to do!)"
else
echo "downloading ${FORMAT} Video for session ${session_number}: $line"
# little trick to be consistant with upercase HD of wwdc file name types
lineWithUperCaseHD="${line/-HD/-hd}"
curl $lineWithUperCaseHD > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
fi
else
dest_path="${WWDC_DIRNAME}/${FORMAT}-VIDEOs/${session_number} - ${title_array[$i]}-${FORMAT}.mov"
if [ -f "${dest_path}" ]
then
echo "${dest_path} already downloaded (nothing to do!)"
else
echo "downloading ${FORMAT} Video for session ${session_number}: $line"
# little trick to be consistant with upercase HD of wwdc file name types
lineWithUperCaseHD="${line/-HD/-hd}"
curl $lineWithUperCaseHD > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
fi
((i+=1))
done
elif [ ${FORMAT} = "SD" ];
then
cat ${TMP_DIR}/video.html | grep -o -E 'href="(http:\/\/devstreaming.apple.com\/videos\/techtalks\/2013/[0-9a-zA-Z_]*\/[0-9a-zA-Z_]*-sd\.mov\?dl=1+)"' | cut -d'"' -f2 | while read line; do
session_number=`echo $line | grep -o -E '/[0-9]+_' | grep -o -E [0-9]+`
if [ ${SELECTIVE_SESSION_MODE} == true ];
then
if `echo ${SESSION_WANTED} | grep "${session_number}" 1>/dev/null 2>&1`
then
dest_path="${WWDC_DIRNAME}/${FORMAT}-VIDEOs/${session_number} - ${title_array[$i]}-${FORMAT}.mov"
if [ -f "${dest_path}" ]
then
echo "${dest_path} already downloaded (nothing to do!)"
else
echo "downloading ${FORMAT} Video for session ${session_number}: $line"
# little trick to be consistant with upercase SD of wwdc file name types
lineWithUperCaseSD="${line/-SD/-sd}"
curl $lineWithUperCaseSD > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
fi
else
dest_path="${WWDC_DIRNAME}/${FORMAT}-VIDEOs/${session_number} - ${title_array[$i]}-${FORMAT}.mov"
if [ -f "${dest_path}" ]
then
echo "${dest_path} already downloaded (nothing to do!)"
else
echo "downloading ${FORMAT} Video for session ${session_number}: $line"
# little trick to be consistant with upercase SD of wwdc file name types
lineWithUperCaseSD="${line/-SD/-sd}"
curl $lineWithUperCaseSD > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
fi
((i+=1))
done
fi
rm -Rf ${TMP_DIR}
}
doGet2012 () {
ituneslogin=$1
itunespassword=$2
FORMAT=$3
#echo "DEBUG: do 2012 (login=${ituneslogin} - password=${itunespassword} - format=${FORMAT})"
TMP_DIR="/tmp/wwdc2012.tmp"
mkdir -p $TMP_DIR
echo ""
echo "======> SORRY: 2012 VIDEO DOWNLOAD NOT YET IMPLEMENTED! <======="
echo ""
rm -Rf ${TMP_DIR}
}
#**************************************************************************************#
# WWDC 2015 #
#**************************************************************************************#
doGetWWDC2015 () {
ituneslogin=$1
itunespassword=$2
FORMAT=$3
if [ ${VERBOSE} == true ];
then
echo "Sessions to be downloaded: ${SESSION_WANTED}"
echo "Output directory: ${WWDC_DIRNAME}"
fi
mkdir -p $TMP_DIR
# Processing Authentifcation - depreciated now (but kept for copy/pasters like me that might need to use this as a snippet for other uses)
if [ -z "${ituneslogin}" ];
then
# Dynamically get the key value as this can change (it did change for instance when Apple had to turn down their developer Portal for a week)
if [ ${VERBOSE} == true ];
then
echo "Getting appIDKey..."
fi
key=$(curl -s -L https://developer.apple.com/iphone | grep 'login?&appIdKey=' | sed -e 's/\(.*login?&appIdKey=\)\(.*\)\(&.*\)/\2/' | awk 'NR==1 {print $1}')
if [ ${VERBOSE} == true ];
then
echo "appIDKey: ${key}"
fi
cookies=(--cookies=on --keep-session-cookies)
action=$(curl -s 'https://daw.apple.com/cgi-bin/WebObjects/DSAuthWeb.woa/wa/login?appIdKey='"${key}" | grep '\ action=' | awk '{ print $4 }' | cut -f2 -d"=" | sed -e "s/^.*\"\(.*\)\".*$/\1/")
curl -s --cookie-jar $TMP_DIR/cookies.txt "https://daw.apple.com${action}" -d theAccountName="${ituneslogin}" -d theAccountPW="${itunespassword}" > /dev/null
curl -s --cookie $TMP_DIR/cookies.txt \
--cookie-jar $TMP_DIR/cookies.txt \
${VIDEO_URL} > $TMP_DIR/video.html
else
curl -silent ${VIDEO_URL} > $TMP_DIR/video.html
fi
cat ${TMP_DIR}/video.html | sed -e '/class="inner_v_section"/,/<\/section>/!d' > $TMP_DIR/video-cleaned.html
if [ -f ${TMP_DIR}/titles.txt ] ; then
rm ${TMP_DIR}/titles.txt
fi
cat ${TMP_DIR}/video-cleaned.html | while read line; do
# domain if for future use ...
#domain=`echo $line | grep -o -E '<h6>(.*)</h6>' | cut -d'<' -f2 | cut -d'>' -f2`
sessionNum=`echo $line | grep -o -E '<a(.*)</a>' | cut -d'=' -f3 | cut -d'"' -f1`
title_array[$sessionNum]=`echo $line | grep -o -E '<a(.*)</a>' | cut -d'>' -f2 | cut -d'<' -f1`
echo "$sessionNum;${title_array[$sessionNum]}" >> $TMP_DIR/titles.txt
done
#`sed -n '/^,/!p' $TMP_DIR/titles.txt > $TMP_DIR/titles.txt.tmp && mv $TMP_DIR/titles.txt.tmp $TMP_DIR/titles.txt`
`sed '/^;/d' $TMP_DIR/titles.txt > $TMP_DIR/titles.txt.tmp && mv $TMP_DIR/titles.txt.tmp $TMP_DIR/titles.txt`
# escape special char for downloading issues (ex: I/O string)
# Ok this is dirty, but quick ! ;)
mv ${TMP_DIR}/titles.txt ${TMP_DIR}/titles-to-be-escaped.txt
sed -e 's/\//\-/g' ${TMP_DIR}/titles-to-be-escaped.txt > ${TMP_DIR}/titles.txt
mv ${TMP_DIR}/titles.txt ${TMP_DIR}/titles-to-be-escaped.txt
sed -e 's/&/AND/g' ${TMP_DIR}/titles-to-be-escaped.txt > ${TMP_DIR}/titles.txt
while read line
do
sessionNum=`echo $line | cut -d';' -f1`
sessionTitle=`echo $line | cut -d';' -f2`
title_array[$sessionNum]=${sessionTitle}
done < ${TMP_DIR}/titles.txt
if [ ${LIST_MODE} == true ];
then
echo "Available videos:"
echo "-----------------"
cat ${TMP_DIR}/titles.txt | cut -d';' -f1 | while read line; do
echo "$line: ${title_array[$line]}"
#printf '%s\n' "${title_array[@]}"
done;
exit
fi
echo "******* DOWNLOADING ${FORMAT} VIDEOS ********"
# Videos ${FORMAT}
mkdir -p "${WWDC_DIRNAME}/${FORMAT}-VIDEOs"
# do the rm *.download only if files exist
FILES_LIST="$(ls "${WWDC_DIRNAME}"/${FORMAT}-VIDEOs/*.download 2>/dev/null)"
if [ -z "$FILES_LIST" ]; then
#echo "All downloads will go to your Desktop/WWDC-2013 folder!"
:
else
echo "Some download was aborted last time you ran this script."
rm "${WWDC_DIRNAME}"/${FORMAT}-VIDEOs/*.download
echo "Cleaning non fully downloaded files: OK"
fi
# Prepare for SAMPLE-CODE
mkdir -p "${WWDC_DIRNAME}/SAMPLE-CODE"
# do the rm *.download only if files exist
FILES_LIST="$(ls "${WWDC_DIRNAME}"/SAMPLE-CODE/*.download 2>/dev/null)"
if [ -z "$FILES_LIST" ]; then
#echo "Hope you like my code? I know there are lot's of improvment I could make. In particular split in functions ..."
:
else
echo "Some sample code files download was aborted last time you ran this script."
rm "${WWDC_DIRNAME}"/SAMPLE-CODE/*.download
echo "Cleaning non fully downloaded sample code zip files: OK"
fi
i=0
# TODO: / WARNING (for possible future function merge): note that devstreaming url does use hard coded "wwdc" in it, were tech-talks function url is "techtalks" (whithout dash)
if [ "${FORMAT}" = "HD" ];
then
LC_FORMAT="hd"
else
LC_FORMAT="sd"
fi
REGEXFILE="[0-9a-zA-Z]*\/[0-9]{1,5}\/[0-9]{1,5}_${LC_FORMAT}_.*\.mp4"
# get individuals video pages
cat ${TMP_DIR}/titles.txt | cut -d';' -f1 | while read line; do
curl -silent "${VIDEO_URL}?id=$line" > "${TMP_DIR}/$line-video.html";
videoURL=`cat ${TMP_DIR}/$line-video.html | grep -o -E 'href="(http:\/\/devstreaming.apple.com\/videos\/wwdc\/'${YEAR}'/'${REGEXFILE}'\?dl=1+)"'| cut -d'"' -f2`
#echo ${line}: ${videoURL}
# Get sample codes
cat ${TMP_DIR}/$line-video.html | grep -o -E '(class="sample-code"|class="playground")(.*)</a>' | cut -d'"' -f4 > "${TMP_DIR}/${line}-sampleCodeURL.txt"
cat ${TMP_DIR}/$line-video.html | grep -o -E '(class="sample-code"|class="playground")(.*)</a>' | cut -d'>' -f3 | cut -d'<' -f1 > "${TMP_DIR}/${line}-sampleCodeName.txt"
paste -d';' "${TMP_DIR}/${line}-sampleCodeName.txt" "${TMP_DIR}/${line}-sampleCodeURL.txt" > "${TMP_DIR}/${line}-sampleCode.txt"
# escape special char for downloading issues (ex: I/O string)
# Ok this is dirty, but it need to be quick ! ;)
mv ${TMP_DIR}/${line}-sampleCode.txt ${TMP_DIR}/${line}-sampleCode-to-be-escaped.txt
sed -e 's/I\/O/I\-O/g' ${TMP_DIR}/${line}-sampleCode-to-be-escaped.txt > ${TMP_DIR}/${line}-sampleCode.txt
mv ${TMP_DIR}/${line}-sampleCode.txt ${TMP_DIR}/${line}-sampleCode-to-be-escaped.txt
sed -e 's/&/AND/g' ${TMP_DIR}/${line}-sampleCode-to-be-escaped.txt > ${TMP_DIR}/${line}-sampleCode.txt
sampleCodeURL=()
sampleCodeName=()
nb_lines=0
while read lineURL; do
sampleCodePATHOnLine=`echo ${lineURL} | cut -d';' -f2`
sampleCodeNameOnLine=`echo ${lineURL} | cut -d';' -f1`
replacement=" -"
sampleCodeNameOnLine="${sampleCodeNameOnLine/:/${replacement}}"
if [[ ! ${lineURL} =~ \.zip$ ]];
then
curl -silent -L "${SAMPLE_CODE_ROOT_URL}/${sampleCodePATHOnLine}/book.json" > "${TMP_DIR}/$line-book.json";
sampleCodeURL[nb_lines]=`cat "${TMP_DIR}/$line-book.json" | grep -o -E '"sampleCode":".*\.zip"' | cut -d'"' -f4`
sampleCodeName[nb_lines]=${sampleCodeNameOnLine}
sampleCodePATH=${sampleCodePATHOnLine}
#echo " (${nb_lines})${sampleCodeName[nb_lines]}: ${SAMPLE_CODE_ROOT_URL}/${sampleCodePATHOnLine}/${sampleCodeURL[nb_lines]}"
else
sampleCodeURL[nb_lines]=${sampleCodePATHOnLine}
#sampleCodeName[nb_lines]=${lineURL%.*}
sampleCodeName[nb_lines]=${sampleCodeNameOnLine}
sampleCodePATH=${sampleCodeURL[nb_lines]}
#echo "==> Direct zip: ${sampleCodeName[nb_lines]}: ${SAMPLE_CODE_ROOT_URL}/${sampleCodeURL[nb_lines]}/${sampleCodeURL[nb_lines]}"
fi
((nb_lines+=1))
done < "${TMP_DIR}/${line}-sampleCode.txt"
if [ ${SELECTIVE_SESSION_MODE} == true ];
then
if `echo ${SESSION_WANTED} | grep "${line}" 1>/dev/null 2>&1`
then
# downloading video files
dest_path="${WWDC_DIRNAME}/${FORMAT}-VIDEOs/${line} - ${title_array[$line]}-${FORMAT}.mov"
if [ -f "${dest_path}" ]
then
echo "${dest_path} already downloaded (nothing to do!)"
else
echo "downloading ${FORMAT} Video for session ${line}: ${title_array[$line]}"
curl "${videoURL}" > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
# downloading sample codes files
for i in "${!sampleCodeURL[@]}"; do
#if [ -n "${sampleCodeURL[$i]}" ]; then
dest_path="${WWDC_DIRNAME}/SAMPLE-CODE/${line} - ${sampleCodeName[$i]}.zip"
if [ -f "${dest_path}" ]
then
echo "${dest_path} already downloaded (nothing to do!)"
else
echo "downloading sample code for session ${line}: ${sampleCodeName[$i]}"
echo "${SAMPLE_CODE_ROOT_URL}/${sampleCodePATH}/${sampleCodeURL[$i]}"
curl -L "${SAMPLE_CODE_ROOT_URL}/${sampleCodePATH}/${sampleCodeURL[$i]}" > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
#fi
done
fi
else
dest_path="${WWDC_DIRNAME}/${FORMAT}-VIDEOs/${line} - ${title_array[$line]}-${FORMAT}.mov"
if [ -f "${dest_path}" ]
then
echo "${dest_path} already downloaded (nothing to do!)"
else
echo "downloading ${FORMAT} Video for session ${line}: ${title_array[$line]}"
curl -L "${videoURL}" > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
# downloading sample codes files
for i in "${!sampleCodeURL[@]}"; do
#if [ -n "${sampleCodeName[$i]}" ]; then
dest_path="${WWDC_DIRNAME}/SAMPLE-CODE/${line} - ${sampleCodeName[$i]}.zip"
if [ -f "${dest_path}" ]
then
echo "${dest_path} already downloaded (nothing to do!)"
else
echo "downloading sample code for session ${line}: ${sampleCodeName[$i]}"
curl -L "${SAMPLE_CODE_ROOT_URL}/${sampleCodePATH}/${sampleCodeURL[$i]}" > "${dest_path}.download"
mv "${dest_path}.download" "${dest_path}"
fi
#fi
done
fi
((i+=1))
done;
rm -Rf ${TMP_DIR}
}
checkNetwork () {
curl -silent -D- -o /dev/null -s http://www.google.com 1>/dev/null 2>&1
if [[ $? == 0 ]]; then
:
#echo "there is netxork"
else
echo "No network connexion! Man, you're here for a long walk!"
exit 1
fi
}
##########################################################################################
####### MAIN ##########
##########################################################################################
#if [ $# -eq "0" ]
#then
# echo "WWDC videos and PDFs downloader (version ${VERSION})" >&2
# echo "Usage: `basename $0` [options] <Apple dev login>"
# echo "Please use -h for more options"
# exit 1
#fi
ituneslogin=${@: -1}
FORMAT=${DEFAULT_FORMAT}
YEAR=${DEFAULT_YEAR}
EVENT=${DEFAULT_EVENT}
while getopts ":hl:y:f:s:vLo:e:" opt; do
case $opt in
h)
echo "WWDC Videos and PDFs downloader (version ${VERSION})" >&2
echo "Author: Olivier HO-A-CHUCK (http://blog.hoachuck.biz)"
echo ""
echo "Usage: `basename $0` [options]"
echo "Try -L option for list of available videos"
echo ""
echo "Options:"
echo " -y <year>: select year (ex: -y 2013). Default year is 2015" >&2
echo " Possible values for year: 2013, 2014 and 2014" >&2
echo " For info: year 2012 videos download is not yet available - to be honest, I'm too lazy to do it!" >&2
echo " -e <event>: select event type between \"wwdc\" and \"tech-talks\"" >&2
echo " default value is \"wwdc\"" >&2
echo " -f <format>: select video format type (SD or HD). Default video format is SD" >&2
echo " -s <comma separated session numbers>: select which sessions you want to download (try -L option for list of avialable videos)" >&2
echo " -v : verbose mode" >&2
echo " -o <output path>: path where to download content (default is /Users/${USER}/Documents/WWDC-<selected year|default=2015>)" >&2
echo " -l [Not needed anymore] <iTunes login>: Give your Developer portal login (so far you don't need to login anymore. If this does change, please use -l option)." >&2
echo " -L : List available video sessions" >&2
echo "" >&2
echo ""
echo "Most common usage:" >&2
echo " - Download all available SD videos for wwdc 2015:" >&2
echo " `basename $0`" >&2
echo ""
echo "Other examples:" >&2
echo " - Download all PDFs and SD videos for wwdc 2014 if Apple change his mind and ask for login:" >&2
echo " `basename $0` -y 2014" >&2
echo " - Download all PDFs and SD videos for tech-talks 2013:" >&2
echo " `basename $0` -y 2013 -e tech-talks" >&2
echo " - Download all HD videos for wwdc 2015:" >&2
echo " `basename $0` -f HD" >&2
echo " - Download only session 201, 400 and 401 with SD videos for wwdc 2015:" >&2
echo " `basename $0` -s 201,400,401" >&2
echo " - Download only session 201 and 400 with HD video for wwdc 2015:" >&2
echo " `basename $0` -s 201,400 -f HD" >&2
echo " - Download all HD videos for wwdc 2015 in /Users/${USER}/Desktop/WWDC-2014 using verbose mode:" >&2
echo " `basename $0` -v -f HD -o /Users/${USER}/Desktop/WWDC-2014" >&2
echo ""
exit 0;
;;
l)
ITUNES_LOGIN=${OPTARG}
LOGIN=true
;;
y)
if [ $OPTARG = "2012" ] || [ $OPTARG = "2013" ] || [ $OPTARG = "2014" ] || [ $OPTARG = "2015" ];
then
YEAR=$OPTARG
else
echo "Unknown specified year. Using default (${YEAR})!"
fi
;;
f)
if [ $OPTARG = "SD" ] || [ $OPTARG = "HD" ];
then
FORMAT=$OPTARG
else
echo "Unknown specified format. Using ${FORMAT} video format!"
fi
;;
s)
if [ $OPTARG > 0 ];
then
SESSION_WANTED=$OPTARG
SELECTIVE_SESSION_MODE=true
else
echo "Session number does not look good!"
fi
;;
v)
echo "Verbose mode on"
VERBOSE=true
;;
L)
LIST_MODE=true
;;
o)
WWDC_DIRNAME=${OPTARG}
;;
e)
if [ $OPTARG = "tech-talks" ] || [ $OPTARG = "wwdc" ] ;
then
EVENT=$OPTARG
else
echo "Unknown event type. Using default (${EVENT})!"
fi
;;
\?)
echo "Invalid option: -$OPTARG" >&2
echo "For help, please use: $0 -h"
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
WWDC_DIRNAME=${WWDC_DIRNAME:-"${HOME}/Documents/WWDC-${YEAR}"}
case "${YEAR}" in
"2012")
if [ -z ${ITUNES_LOGIN} ];
then
read -r -p Login: ituneslogin ; echo
fi
if $LOGIN
then
read -r -s -p Password: itunespassword ; echo
else
echo ""
echo "Using 'no password' mode (this is possible since WWDC 2014 sessions addition => Apple bug ?)!"
echo "try using -l option if download does not work."
echo ""
ituneslogin="<no-login>"
itunespassword="<no-password>"
fi
checkNetwork
doGet2012 ${ituneslogin} ${itunespassword} ${FORMAT}
;;
"2013")
#if [ -z ${ITUNES_LOGIN} ];
#then
# read -r -p Login: ituneslogin ; echo
#fi
checkNetwork
if $LOGIN ;
then
read -r -s -p Password: itunespassword ; echo
else
echo ""
echo "Using 'no password' mode (this is possible since WWDC 2014 sessions addition => Apple bug ?)!"
echo "try using -l option if download does not work."
echo ""
ituneslogin="<no-login>"
itunespassword="<no-password>"
fi
if [ ${EVENT} == "wwdc" ];
then
VIDEO_URL=${VIDEO_URL_WWDC}/2013/
doGetWWDCPost2012 ${ituneslogin} ${itunespassword} ${FORMAT}
elif [ ${EVENT} == "tech-talks" ];
then
VIDEO_URL=${VIDEO_URL_TECHTALK}
doGetTT2013 ${ituneslogin} ${itunespassword} ${FORMAT}
fi
;;
"2014")
if $LOGIN ;
then
read -r -s -p Password: itunespassword ; echo
else
echo ""
echo "Using 'no password' mode (this is possible since WWDC 2014 sessions addition => Apple bug ?)!"
echo "try using -l option if download does not work."
echo ""
ituneslogin="<no-login>"
itunespassword="<no-password>"
fi
if [ ${EVENT} == "wwdc" ];
then
VIDEO_URL=${VIDEO_URL_WWDC}/2014/
doGetWWDCPost2012 ${ituneslogin} ${itunespassword} ${FORMAT}
elif [ ${EVENT} == "tech-talks" ];
then
#VIDEO_URL=${VIDEO_URL_TECHTALK}
#doGetTT2013 ${ituneslogin} ${itunespassword} ${FORMAT}
echo "No yet available session download other than 'wwdc' for 2014! Sorry man."
fi
;;
"2015")
checkNetwork
if $LOGIN ;
then
read -r -s -p Password: itunespassword ; echo
else
echo ""
echo "Using 'no password' mode (this is possible since WWDC 2014 sessions addition)!"
echo "try using -l option if download does not work."
echo ""
ituneslogin="<no-login>"
itunespassword="<no-password>"
fi
if [ ${EVENT} == "wwdc" ];
then
VIDEO_URL=${VIDEO_URL_WWDC}/2015/
doGetWWDC2015 ${ituneslogin} ${itunespassword} ${FORMAT}
elif [ ${EVENT} == "tech-talks" ];
then
echo "There is no TechTalk sessions available yet for 2015! Sorry for that sir."
fi
;;
*)
echo "Sorry: can't process requested year. Please choose between \"2012\", \"2013\" , \"2014\" or \"2015\"."
;;
esac
exit 0

View file

@ -1,80 +0,0 @@
#!/usr/bin/env node
require('batteries').extendNative()
var fs = require('fs')
, http = require('http')
, join = require('path').join
, notify = require('growl').notify
, Downloads = join(process.env.HOME, 'Downloads')
, created = JSON.parse(process.env.WATCH_CREATED)
, torrents = created.grep(/\.torrent$/i)
, skipped = []
, _log = []
, log = function(s) { s = '>>> ' + s; _log.push(s); console.log(s) }
, err = function(s) { s = '!!! ' + s; _log.push(s); console.error(s) }
, writeLog = function() { fs.writeFileSync('/Users/sjs/log/yarrr.log', _log.join('\n')) }
process.on('uncaughtException', function(e) {
err('error: ' + e)
err('bailing')
process.exit(1)
})
torrents.forEach(function(torrent, i) {
log(torrent)
var path = join(Downloads, torrent)
try {
fs.statSync(path)
}
catch (e) {
skipped.push(torrent)
err(path + ' does not exist, skipping')
return
}
var boundary = '48940923YARRRPIRATE3890457293'
, torrentData = fs.readFileSync(path, 'binary')
, torrentSize = torrentData.length
, data = [ '--' + boundary
, 'Content-Disposition: form-data; name="torrent_file"; filename="' + torrent + '"'
, 'Content-Type: application/x-bittorrent'
, ''
, torrentData
, '--' + boundary + '--\r\n'
].join('\r\n')
, opts = {
method: 'POST',
host: 'h.samhuri.net',
port: 8080,
path: '/gui/?action=add-file',
headers: { 'Authorization': 'Basic YWRtaW46YWRtaW4='
, 'Content-Type': 'multipart/form-data; boundary=' + boundary
, 'Content-Length': data.length
}
}
, req = http.request(opts, function(res) {
var responseData = ''
res.on('data', function(chunk) { responseData += chunk })
res.on('end', function() {
if (res.statusCode === 200 && !('error' in JSON.parse(responseData))) {
log('rm ' + path)
fs.unlink(path)
}
else {
err('error ' + res.statusCode)
err(responseData)
}
if (i === torrents.length - 1) {
var n = torrents.length - skipped.length
, s = n === 1 ? '' : 's'
if (n > 0) {
notify(n + ' torrent' + s + ' → µTorrent')
}
//writeLog()
}
})
})
log('torrent size: ' + torrentSize)
log('total size: ' + data.length)
req.end(data, 'binary')
})

View file

@ -1,4 +0,0 @@
#!/bin/bash
java -jar ~/bin/yuicompressor-2.4.7.jar "$1" -o "$2"

Binary file not shown.