Module: Rypple

Defined in:
lib/rypple/base.rb,
lib/rypple/setup.rb,
lib/rypple/version.rb

Constant Summary collapse

DefaultConfiguration =
{
  :destinationDir => './test',
  :dropbox => {
    :root => '/',
    :sync => ['**'],
  }
}
DropboxKeyFile =
".dropbox_session.yml"
RyppleConfigFile =
"_rypple.yml"
DefaultCGI =
"#!/usr/bin/ruby\ngemPath = \"%%GEM_PATH\"\nconfigPath = \"%%CONFIG_PATH\"\ninDir = \"%%IN_DIR\"\noutDir = \"%%OUT_DIR\"\n\nif !gemPath.empty?\n  $:.push(gemPath)\n  ENV['GEM_PATH'] = gemPath\nend\n\nrequire 'cgi'\nrequire 'rubygems'\nrequire 'rypple'\nrequire 'jekyll'\n\ncgi = CGI.new\n\nputs cgi.header\n\nputs \"<h1>Rippling . . .</h1>\"\nif Rypple.sync(configPath)\n  puts \"<h1>Generating Static Site</h1>\"\n  puts `%%COMMAND \#{inDir} \#{outDir}`\nend\n"
DefaultUpdateForm =
"<html>\n  <head>\n    <title>Rypple</title>\n  </head>\n  <body>\n    <h1> Throw a stone into a pond..</h1>\n    <form action=\"update.cgi\" method=\"POST\">\n      <input type=\"submit\" value=\"Rypple\">\n    </form>\n  </body>\n</html>\n"
DefaultHTAccess =
"AuthName \"Rypple Updater\"\nAuthType Basic\nAuthUserFile %%AUTH_FILE\nRequire valid-user\n"
VERSION =
"0.0.7"

Class Method Summary collapse

Class Method Details

.buildLoginSessionObject



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/rypple/base.rb', line 66

def Rypple.buildLoginSession()
  puts "A Dropbox API key/secret is required for accessing your sync files."
  puts "You can visit https://www.dropbox.com/developers/apps to generate these."
  print "Please enter your Dropbox API key:"
  key = gets.chomp!
  print "Please enter your Dropbox API secret:"
  secret = gets.chomp!
  access = :app_folder
  print "Should this API access be used in sandbox mode? (Y/n):"
  answer = gets.downcase.chomp
  if !answer.empty? and answer == 'n'
    access = :dropbox
  end

  session = DropboxSession.new(key, secret)
  session.get_request_token
  authorize_url = session.get_authorize_url
  puts "Visit #{authorize_url} to log in to Dropbox. Hit enter when you have done this."
  gets
  session.get_access_token
  return access, session
end

.cleanup(conf, keys, path) ⇒ Object



103
104
105
106
# File 'lib/rypple/base.rb', line 103

def Rypple.cleanup(conf, keys, path)
  Rypple.saveConfig(conf, path)
  Rypple.saveDropbox(keys, path)
end

.connectToDropbox(path) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rypple/base.rb', line 21

def Rypple.connectToDropbox(path)
  session = nil
  dropboxKeys = {:access_type => :app_folder}
  dropConfPath = File.join(path, DropboxKeyFile)
  #Load Dropbox API dropboxKeys from file, if applicable.
  if File.exists?(dropConfPath)
    dropboxKeys = YAML::load(File.read(dropConfPath))
  end

  if dropboxKeys.has_key?(:session)
    session = DropboxSession.deserialize(dropboxKeys[:session])
  else
    dropboxKeys[:access_type], session = Rypple.buildLoginSession()
  end

  if session.nil?
    return nil, nil, nil
  end

  if !dropboxKeys.has_key?(:session)
    dropboxKeys[:session] = session.serialize()
  end

  client = DropboxClient.new(session, dropboxKeys[:access_type])

  if client.nil?
    return nil, nil, nil
  else
    return session, client, dropboxKeys
  end
end

.loadConfiguration(path) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rypple/base.rb', line 53

def Rypple.loadConfiguration(path)
  conf = Rypple::DefaultConfiguration.dup 

  rypConf = File.join(path, RyppleConfigFile)
  # Load configuration and override any values that differ from the default.
  if File.exists?(rypConf)
    loadedConf = YAML::load(File.read(rypConf))
    conf.merge!(loadedConf)
  end

  return conf
end

.saveConfig(conf, path) ⇒ Object



96
97
98
99
100
101
# File 'lib/rypple/base.rb', line 96

def Rypple.saveConfig(conf, path)
  ryppleConf = File.join(path, RyppleConfigFile)
  File.open(ryppleConf, 'w') do |file|
    file.puts conf.to_yaml
  end
end

.saveDropbox(keys, path) ⇒ Object



89
90
91
92
93
94
# File 'lib/rypple/base.rb', line 89

def Rypple.saveDropbox(keys, path)
  dropConfig = File.join(path, DropboxKeyFile)
  File.open(dropConfig, 'w') do|file|
    file.puts keys.to_yaml
  end
end

.SetupObject

Returns false if installation fails



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/rypple/setup.rb', line 56

def Rypple.Setup()
  puts "Configuring the Rypple update script for web use."
  if File.exists?(ENV["HOME"])
    configBase = File.join(ENV["HOME"], 'ryppleSite')
    puts "Please enter directory for Rypple Site. Default:", configBase
  else
    puts "Please enter directory for the new Rypple site."
  end
  directory = gets.chomp!
 
  if !directory.empty?
    configBase = File.expand_path(configBase)
  end

  if !File.exists?(configBase)
    begin
      Dir.mkdir(configBase)
    rescue SystemCallError
      puts "Cannot create directory", configBase, "aborting."
      return false
    end
  end

  conf = Rypple.loadConfiguration(configBase)
  conf[:destinationDir] = File.expand_path(directory)
  session, client, keys = Rypple.connectToDropbox(configBase)
  
  if !conf.nil? and !keys.nil?
    Rypple.cleanup(conf, keys, configBase)
  end
 
  baseCGI = DefaultCGI.dup 
  baseCGI.gsub!(/%%CONFIG_PATH/, configBase)
  
  choice = false
  insert = true
  while !choice do
    puts "Is your web host set up to use ruby gems? (y/N)"
    answer = gets.chomp!.downcase!
    if answer.nil? or answer.empty?
      choice = true
    elsif answer == "n" or answer == "y"
      insert = (answer == "n")
      choice = true
    end
  end
  
  if insert
    gemPath = ''
    if ENV.has_key?('GEM_HOME')
      gemPath = ENV['GEM_HOME']  
    else
      puts "Please enter search path for the ruby gems."
      gemPath = gets.chomp!
    end
  
    baseCGI.gsub!(/%%GEM_PATH/, gemPath)
  end
  
  baseCGI.gsub!(/%%IN_DIR/, configBase)
  
  outDir = ""
  while outDir.empty? or !File.exists?(outDir) do
    puts "Where should the static site generator output files?"
    outDir = gets.chomp!

    if !outDir.empty?
      outDir = File.expand_path(outDir)
    else
      puts "Cannot use empty output directory, aborting."
      return false
    end
  
    if !File.exists?(outDir)
      begin
        Dir.mkdir(outDir)
      rescue SystemCallError
        puts "Cannot create output directory", outDir
        next
      end
    end
  end

  baseCGI.gsub!(/%%OUT_DIR/, outDir)
  
  command = File.join("#{ENV["GEM_HOME"]}", 'bin', 'jekyll')
  if File.exists?(command)
    puts "Please enter any arguments to pass to jekyll"
    args = gets.chomp!
    baseCGI.gsub!(/%%COMMAND/, command + ' ' + args)
  end
  
  ryppleDir = File.join(configBase, 'rypple')
  
  if !File.exists?(ryppleDir)
    begin
      Dir.mkdir(ryppleDir)
    rescue SystemCallError
      "Cannot create rypple directory."
    end
  end
  
  File.open(File.join(ryppleDir, 'update.html'), 'w', 0644) { |f| f.puts DefaultUpdateForm }
  
  out = File.join(ryppleDir, 'update.cgi')
  File.open(out, 'w', 0755) { |f| f.puts baseCGI }
  
  puts "Should I enable basic user authentication for the update script? (Y/n):"
  
  answer = gets.chomp!
  if answer.nil? or answer.empty? or answer.downcase! == 'y'
    print "Enter user name for authentication:"
    user = gets.chomp!
    print "Enter password for authentication:"
    chars = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
    salt = chars[rand(chars.size - 1)] + chars[rand(chars.size - 1)]
    pass = gets.chomp!.crypt(salt)
    authFile = File.join(configBase, '.htpasswd')
    File.open(authFile, 'w') { |f| f.puts "#{user}:#{pass}" }
    htaccess = DefaultHTAccess.gsub(/%%AUTH_FILE/, authFile)
    File.open(File.join(ryppleDir, '.htaccess'), 'w') { |f| f.puts htaccess }
  end

  puts "Attempting first update"
  
  if Rypple.sync(configBase)
    puts `jekyll #{configBase} #{outDir}`
  else
    puts "Rypple sync failed."
  end

  return true
end

.sync(path = "") ⇒ Object



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/rypple/base.rb', line 139

def Rypple.sync(path = "")
  conf = Rypple.loadConfiguration(path)
  begin
    session, client, dropboxKeys = Rypple.connectToDropbox(path)
  rescue DropboxAuthError
    puts "Dropbox authorization failed."
    Rypple.cleanup(conf, dropboxKeys, path)
    return
  rescue NameError
    puts "Destination does not exist."
    Rypple.cleanup(conf, dropboxKeys, path)
    return
  end
 
  if session.nil?
    puts "Could not connect to Dropbox."
    Rypple.cleanup(conf, dropboxKeys, path)
    return
  end 

  destDir = conf[:destinationDir]

  oldFileState = dropboxKeys[:files]
  files = Rypple.walkDropbox(client, conf[:dropbox][:root], oldFileState)

  rootLength = conf[:dropbox][:root].length
  if !files.nil?
    files.keys.each { |xx|
      fileDest = xx[rootLength, xx.length]
      matched = false
      conf[:dropbox][:sync].each { |ii|
        if File.fnmatch?(ii, xx, File::FNM_DOTMATCH)
          matched = true
          break
        end
      }
      if matched
        file = client.get_file(xx)
        dest = File.join(destDir, fileDest)
        File.makedirs(File.dirname(dest))
        File.open(dest, 'w') {|f| f.puts file}
      end
    }
  end

  conf[:dropbox][:sync].each { |ii|
    Dir.glob(File.join(destDir, ii)).each { |oo|
      if !File.directory?(oo)
        upName = Pathname.new(oo).relative_path_from(Pathname.new(destDir)).to_s
        upName = File.join("", conf[:dropbox][:root], upName)
        if files.nil? or !files.has_key?(upName)
          File.open(oo) { |f| client.put_file(upName, f, true) }
        end
      end
    }
  }

  dropboxKeys[:files] = Rypple.walkDropbox(client, conf[:dropbox][:root], {})
  Rypple.cleanup(conf, dropboxKeys, path)

  return true
end

.walkDropbox(client, path, oldFileState) ⇒ Object

Iterates over dropbox directory, returing paths and state hash for each file oldFileState should be a hash of paths to state hashes, same as return values



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/rypple/base.rb', line 110

def Rypple.walkDropbox(client, path, oldFileState)
  #Here we need to actually sync newest files.
  begin
    useState = (!oldFileState.nil? and oldFileState.has_key?(path) and oldFileState[path]["path"] == path)
    oldState = useState ? oldFileState[path]["hash"] : nil
    states = client.(path, 10000, true, oldState)
  rescue DropboxNotModified
    puts "Files have not changed."
    return nil
  end

  files = {}
  #State represents a folder
  if states["is_dir"] and states.has_key?("contents")
    states["contents"].each{ |xx|
      useState = (!oldFileState.nil? and oldFileState.has_key?(xx["path"]))
      old = (useState ? oldFileState[xx["path"]] : nil)
      subs = Rypple.walkDropbox(client, xx["path"], old)
      if !subs.nil?
        files.merge!(subs)
      end
    }
  else
    files[states['path']] = states
  end
  
  return files
end