Class: ShowOff

Inherits:
Sinatra::Application
  • Object
show all
Defined in:
lib/showoff.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app = nil) ⇒ ShowOff

Returns a new instance of ShowOff.



54
55
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
189
190
191
192
193
194
# File 'lib/showoff.rb', line 54

def initialize(app=nil)
  super(app)
  @logger = Logger.new(STDOUT)
  @logger.formatter = proc { |severity,datetime,progname,msg| "#{progname} #{msg}\n" }
  @logger.level = settings.verbose ? Logger::DEBUG : Logger::WARN

  @review  = settings.review
  @execute = settings.execute

  dir = File.expand_path(File.join(File.dirname(__FILE__), '..'))
  @logger.debug(dir)

  showoff_dir = File.expand_path(File.join(File.dirname(__FILE__), '..'))
  settings.pres_dir ||= Dir.pwd
  @root_path = "."

  # Load up the default keymap, then merge in any customizations
  keymapfile   = File.expand_path(File.join('~', '.showoff', 'keymap.json')) rescue nil
  @keymap      = Keymap.default
  @keymap.merge! JSON.parse(File.read(keymapfile)) rescue {}

  # map keys to the labels we're using
  @keycode_dictionary   = Keymap.keycodeDictionary
  @keycode_shifted_keys = Keymap.shiftedKeyDictionary

  settings.pres_dir = File.expand_path(settings.pres_dir)
  if (settings.pres_file)
    ShowOffUtils.presentation_config_file = settings.pres_file
  end

  # Load configuration for page size and template from the
  # configuration JSON file
  if File.exist?(ShowOffUtils.presentation_config_file)
    showoff_json = JSON.parse(File.read(ShowOffUtils.presentation_config_file))
    settings.showoff_config = showoff_json

    # Set options for encoding, template and page size
    settings.encoding      = showoff_json["encoding"]  || 'UTF-8'
    settings.page_size     = showoff_json["page-size"] || "Letter"
    settings.pres_template = showoff_json["templates"]
  end

  # code execution timeout
  settings.showoff_config['timeout'] ||= 15

  # If favicon in presentation root, use it by default
  if File.exist? 'favicon.ico'
    settings.showoff_config['favicon'] ||= 'file/favicon.ico'
  end

  # default protection levels
  if settings.showoff_config.has_key? 'password'
    settings.showoff_config['protected'] ||= ["presenter", "onepage", "print"]
  else
    settings.showoff_config['protected'] ||= Array.new
  end

  if settings.showoff_config.has_key? 'key'
    settings.showoff_config['locked'] ||= ["slides"]
  else
    settings.showoff_config['locked'] ||= Array.new
  end

  # default code parsers (for executable code blocks)
  settings.showoff_config['parsers'] ||= {}
  settings.showoff_config['parsers']['perl']   ||= 'perl'
  settings.showoff_config['parsers']['puppet'] ||= 'puppet apply --color=false'
  settings.showoff_config['parsers']['python'] ||= 'python'
  settings.showoff_config['parsers']['ruby']   ||= 'ruby'
  settings.showoff_config['parsers']['shell']  ||= 'sh'

  # default code validators
  settings.showoff_config['validators'] ||= {}
  settings.showoff_config['validators']['perl']   ||= 'perl -cw'
  settings.showoff_config['validators']['puppet'] ||= 'puppet parser validate'
  settings.showoff_config['validators']['python'] ||= 'python -m py_compile'
  settings.showoff_config['validators']['ruby']   ||= 'ruby -c'
  settings.showoff_config['validators']['shell']  ||= 'sh -n'

  # highlightjs syntax style
  @highlightStyle = settings.showoff_config['highlight'] || 'default'

  # variables used for building section numbering and title
  @slide_count   = 0
  @section_major = 0
  @section_minor = 0
  @section_title = settings.showoff_config['name'] rescue 'Showoff Presentation'

  @logger.debug settings.pres_template

  @cached_image_size = {}
  @logger.debug settings.pres_dir
  @pres_name = settings.pres_dir.split('/').pop
  require_ruby_files

  # Default asset path
  @asset_path = "./"

  # invert the logic to maintain backwards compatibility of interactivity on by default
  @interactive = ! settings.standalone rescue false

  # Create stats directory
  FileUtils.mkdir settings.statsdir unless File.directory? settings.statsdir if @interactive

  # Page view time accumulator. Tracks how often slides are viewed by the audience
  begin
    @@counter = JSON.parse(File.read("#{settings.statsdir}/#{settings.viewstats}"))

    # port old format stats
    unless @@counter.has_key? 'user_agents'
      @@counter = { 'user_agents' => {}, 'pageviews' => @@counter }
    end
  rescue
    @@counter = { 'user_agents' => {}, 'pageviews' => {} }
  end

  # keeps track of form responses. In memory to avoid concurrence issues.
  begin
    @@forms = JSON.parse(File.read("#{settings.statsdir}/#{settings.forms}"))
  rescue
    @@forms = Hash.new
  end

  @@downloads = Hash.new # Track downloadable files
  @@cookie    = nil      # presenter cookie. Identifies the presenter for control messages
  @@current   = Hash.new # The current slide that the presenter is viewing
  @@cache     = nil      # Cache slide content for subsequent hits

  if @interactive
    # flush stats to disk periodically
    Thread.new do
      loop do
        sleep 30
        ShowOff.flush
      end
    end
  end

  # Initialize Markdown Configuration
  MarkdownConfig::setup(settings.pres_dir)
end

Instance Attribute Details

#cached_image_sizeObject (readonly)

Returns the value of attribute cached_image_size.



27
28
29
# File 'lib/showoff.rb', line 27

def cached_image_size
  @cached_image_size
end

Class Method Details

.do_static(args) ⇒ Object



1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
# File 'lib/showoff.rb', line 1125

def self.do_static(args)
  args ||= [] # handle nil arguments
  what   = args[0] || "index"
  opt    = args[1]

  # Sinatra now aliases new to new!
  # https://github.com/sinatra/sinatra/blob/v1.3.3/lib/sinatra/base.rb#L1369
  showoff = ShowOff.new!

  name = showoff.instance_variable_get(:@pres_name)
  path = showoff.instance_variable_get(:@root_path)
  logger = showoff.instance_variable_get(:@logger)

  case what
  when 'supplemental'
    data = showoff.send(what, opt, true)
  when 'pdf'
    opt ||= "#{name}.pdf"
    data = showoff.send(what, opt)
  when 'print'
    opt ||= 'handouts'
    data = showoff.send(what, true, opt)
  else
    data = showoff.send(what, true)
  end

  if data.is_a?(File)
    logger.warn "Generated PDF as #{opt}"
  else
    out = File.expand_path("#{path}/static")
    # First make a directory
    FileUtils.makedirs(out)
    # Then write the html
    file = File.new("#{out}/index.html", "w")
    file.puts(data)
    file.close
    # Now copy all the js and css
    my_path = File.join( File.dirname(__FILE__), '..', 'public')
    ["js", "css"].each { |dir|
      FileUtils.copy_entry("#{my_path}/#{dir}", "#{out}/#{dir}", false, false, true)
    }
    # And copy the directory
    Dir.glob("#{my_path}/#{name}/*").each { |subpath|
      base = File.basename(subpath)
      next if "static" == base
      next unless File.directory?(subpath) || base.match(/\.(css|js)$/)
      FileUtils.copy_entry(subpath, "#{out}/#{base}")
    }

    # Set up file dir
    file_dir = File.join(out, 'file')
    FileUtils.makedirs(file_dir)
    pres_dir = showoff.settings.pres_dir

    # ..., copy all user-defined styles and javascript files
    Dir.glob("#{pres_dir}/*.{css,js}").each { |path|
      FileUtils.copy(path, File.join(file_dir, File.basename(path)))
    }

    # ... and copy all needed image files
    [/img src=[\"\'].\/file\/(.*?)[\"\']/, /style=[\"\']background(?:-image): url\(\'file\/(.*?)'/].each do |regex|
      data.scan(regex).flatten.each do |path|
        dir = File.dirname(path)
        FileUtils.makedirs(File.join(file_dir, dir))
        begin
          FileUtils.copy(File.join(pres_dir, path), File.join(file_dir, path))
        rescue Errno::ENOENT => e
          puts "Missing source file: #{path}"
        end
      end
    end
    # copy images from css too
    Dir.glob("#{pres_dir}/*.css").each do |css_path|
      File.open(css_path) do |file|
        data = file.read
        data.scan(/url\([\"\']?(?!https?:\/\/)(.*?)[\"\']?\)/).flatten.each do |path|
          path.gsub!(/(\#.*)$/, '') # get rid of the anchor
          path.gsub!(/(\?.*)$/, '') # get rid of the query
          logger.debug path
          dir = File.dirname(path)
          FileUtils.makedirs(File.join(file_dir, dir))
          begin
            FileUtils.copy(File.join(pres_dir, path), File.join(file_dir, path))
          rescue Errno::ENOENT => e
            puts "Missing source file: #{path}"
          end
        end
      end
    end
  end
end

.flushObject

save stats to disk



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/showoff.rb', line 197

def self.flush
  begin
    if defined?(@@counter) and not @@counter.empty?
      File.open("#{settings.statsdir}/#{settings.viewstats}", 'w') do |f|
        if settings.verbose then
          f.write(JSON.pretty_generate(@@counter))
        else
          f.write(@@counter.to_json)
        end
      end
    end

    if defined?(@@forms) and not @@forms.empty?
      File.open("#{settings.statsdir}/#{settings.forms}", 'w') do |f|
        if settings.verbose then
          f.write(JSON.pretty_generate(@@forms))
        else
          f.write(@@forms.to_json)
        end
      end
    end
  rescue Errno::ENOENT => e
  end
end

.pres_dir_currentObject



222
223
224
225
# File 'lib/showoff.rb', line 222

def self.pres_dir_current
  opt = {:pres_dir => Dir.pwd}
  ShowOff.set opt
end

Instance Method Details

#authenticate(credentials) ⇒ Object



1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
# File 'lib/showoff.rb', line 1291

def authenticate(credentials)
  auth = Rack::Auth::Basic::Request.new(request.env)

  return false unless auth.provided? && auth.basic? && auth.credentials

  case credentials
  when Array
     auth.credentials == credentials
  when String
    auth.credentials.last == credentials
  else
    false
  end
end

#authorized?Boolean

Returns:

  • (Boolean)


1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
# File 'lib/showoff.rb', line 1267

def authorized?
  # allow localhost if we have no password
  if not settings.showoff_config.has_key? 'password'
    localhost?
  else
    user     = settings.showoff_config['user'] || ''
    password = settings.showoff_config['password']
    authenticate([user, password])
  end
end

#get_code_from_slide(path, index, executable = true) ⇒ Object

Load a slide file from disk, parse it and return the text of a code block by index



1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
# File 'lib/showoff.rb', line 1218

def get_code_from_slide(path, index, executable=true)
  if path =~ /^(.*)(?::)(\d+)$/
    path = $1
    num  = $2.to_i
  else
    num = 1
  end

  classes = executable ? 'code.execute' : 'code'

  slide = "#{path}.md"
  return unless File.exist? slide

  content = File.read(slide)
  if defined? num
    content = content.split(/^\<?!SLIDE/m).reject { |sl| sl.empty? }[num-1]
  end

  html = process_markdown(slide, content, {})
  doc  = Nokogiri::HTML::DocumentFragment.parse(html)

  if index == 'all'
    doc.css(classes).collect do |code|
      classes = code.attr('class').split rescue []
      lang    = classes.shift =~ /language-(\S*)/ ? $1 : nil

      [lang, code.text, classes]
    end
  else
    doc.css(classes)[index.to_i].text rescue 'Invalid code block index'
  end
end

#guidObject



1306
1307
1308
1309
# File 'lib/showoff.rb', line 1306

def guid
  # this is a terrifyingly simple GUID generator
  (0..15).to_a.map{|a| rand(16).to_s(16)}.join
end

#localhost?Boolean

Returns:

  • (Boolean)


1287
1288
1289
# File 'lib/showoff.rb', line 1287

def localhost?
  request.env['REMOTE_HOST'] == 'localhost' or request.ip == '127.0.0.1'
end

#locked!Object



1259
1260
1261
1262
1263
1264
1265
# File 'lib/showoff.rb', line 1259

def locked!
  # check auth first, because if the presenter has logged in with a password, we don't want to prompt again
  unless authorized? or unlocked?
    response['WWW-Authenticate'] = %(Basic realm="#{@title}: Locked Area. A presentation key is required to view.")
    throw(:halt, [401, "Not authorized."])
  end
end

#protected!Object

Basic auth boilerplate



1252
1253
1254
1255
1256
1257
# File 'lib/showoff.rb', line 1252

def protected!
  unless authorized?
    response['WWW-Authenticate'] = %(Basic realm="#{@title}: Protected Area. Please log in.")
    throw(:halt, [401, "Not authorized."])
  end
end

#require_ruby_filesObject



227
228
229
# File 'lib/showoff.rb', line 227

def require_ruby_files
  Dir.glob("#{settings.pres_dir}/*.rb").map { |path| require path }
end

#unlocked?Boolean

Returns:

  • (Boolean)


1278
1279
1280
1281
1282
1283
1284
1285
# File 'lib/showoff.rb', line 1278

def unlocked?
  # allow localhost if we have no key
  if not settings.showoff_config.has_key? 'key'
    localhost?
  else
    authenticate(settings.showoff_config['key'])
  end
end


1311
1312
1313
# File 'lib/showoff.rb', line 1311

def valid_cookie
  (request.cookies['presenter'] == @@cookie)
end