public
Description: SimplePaste web application
Homepage: http://atdot.net/sp
Clone URL: git://github.com/ko1/simplepaste.git
simplepaste / simplepaste.rb
100755 363 lines (294 sloc) 6.816 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
52
53
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
=begin
SimplePaste:
 
=end
 
require 'cgi'
require 'erb'
require 'yaml/store'
 
class SimplePaste
  class RedirectNotice < Exception
  end
  class RawTextNotice < Exception
  end
 
  def initialize erb_dir, store_dir, backup_dir
    @erb_dir = erb_dir
    SimpleStore.store_dir = store_dir
    SimpleStore.backup_dir = backup_dir
    @cgi = CGI.new
  end
 
  def show type, params = {}
    file = File.read(File.join(@erb_dir, "#{type}.erb"))
    ERB.new(file).result(binding)
  end
 
  def move_to *args
    raise RedirectNotice.new([script_name, *args.map{|e| e.to_s}].join('/'))
  end
 
  def redirect_to url
    raise RedirectNotice.new(url)
  end
 
  def main cmd = nil, *args
    cmd = 'on_' + (cmd || 'info')
 
    if self.respond_to? cmd
      self.__send__ cmd, *args
    else
      raise "unknown command: #{cmd}"
    end
  end
 
  def escape str
    CGI.escapeHTML str
  end
 
  def run
    begin
      @cgi.out{
        main(*(@cgi.path_info || '').split('/')[1..-1])
      }
    rescue RedirectNotice => e
      to = e.message
      @cgi.out("Location"=>to, "status" => "REDIRECT"){
        "<html><body><a href='#{to}'>#{to}</a></body></html>"
      }
    rescue RawTextNotice => e
      @cgi.out('type'=>'text/plain'){
        e.message
      }
    rescue Exception => e
      # $DEBUG = true
      if $DEBUG
        result = ''
        result << "<pre>"
        result << escape("#{e.class}: #{e.to_s}\n---- \n#{e.backtrace.join("\n")}")
        result << "</pre>"
        result << "<pre>"
        ENV.each{|k, v|
          result << escape("#{k}: #{v}\n")
        }
      else
        result = escape("Error: #{e.to_s}")
      end
      @cgi.out{
        result
      }
    end
  end
 
  # utilities
  def query key
    @cgi.params[key][0]
  end
 
  alias q query
  
  def queries key
    @cgi.params[key]
  end
 
  def client_ip_addr
    @cgi.remote_addr
  end
 
  def script_name
    if /\.cgi/ !~ ENV['REQUEST_URI']
      @cgi.script_name.gsub(/.cgi\Z/, '')
    else
      @cgi.script_name
    end
  end
 
  def script_url
    "http://#{@cgi.server_name}#{script_name}"
  end
 
  # Common action
  def on_info
    show :info
  end
 
  def on_make page_id = nil
    page_id = StoreClass.make_id unless page_id
    show :make, :page_id => page_id
  end
 
  def on_commit cmd, page_id = nil, *opts
    case cmd
    when 'new', 'auto'
      store = StoreClass.make(page_id)
      begin
        commit_new_entry store
        store['ipaddr'] = client_ip_addr
        store['time'] = Time.now
        store['option'] = opts.join("\n")
        store.commit
      rescue Exception
        store.delete!
        raise
      end
 
      if cmd == 'new'
        move_to 'view', store.id
      else
        "#{script_url}/view/#{store.id}"
      end
 
    when 'stick'
      store = StoreClass.open(page_id)
      store['stick'] = true
      store.commit
      
      move_to :view, page_id
 
    when 'delete'
      store = StoreClass.open(page_id)
      store.delete
      move_to :view, page_id
    end
  end
 
  def on_check cmd, page_id = nil
    case cmd
    when 'newid'
      StoreClass.make_id
    when 'newidurl'
      script_url + '/view/' + StoreClass.make_id
    when 'exist'
      StoreClass.exist?(page_id) ? 'true' : 'false'
    else
      raise "unknown command: #{cmd}"
    end
  end
 
end
 
class SimpleStore
 
  def self.store_dir=(dir)
    SimpleStore.const_set(:STORE_DIR, dir)
  end
 
  def self.store_dir
    STORE_DIR
  end
 
  def self.store_path sid, prefix=nil
    "#{STORE_DIR}/#{prefix}s.#{sid}"
  end
 
  def self.backup_dir=(dir)
    SimpleStore.const_set(:BACKUP_DIR, dir)
  end
 
  def self.backup_dir
    BACKUP_DIR
  end
 
  def self.backup_path sid
    "#{BACKUP_DIR}/#{sid}"
  end
 
  def check_id pid
    raise "invalid id: #{pid}" unless /\A[\dA-Za-z\-_]{1,32}\Z/ =~ pid
  end
 
  def self.make_place sid
    File.open(store_path(sid), 'wb'){}
  end
 
  def self.make sid = nil
    self.lock{
      sid = make_id unless sid
      raise "already exists: #{sid}" if exist?(sid)
      make_place sid
      self.new sid
    }
  end
 
  def self.make_id
    nid = Time.new.to_i.to_s(36).reverse
 
    lock{
      while exist? nid
        nid = nid.succ
      end
    }
 
    nid
  end
 
  def self.lock
    file = store_path('.lock', '.x.')
 
    File.open(file, 'wb'){|f|
      f.flock(File::LOCK_SH)
      yield
    }
  end
 
  def self.exist? sid
    FileTest.exist?(store_path(sid))
  end
 
  def self.random_suffix(sid)
    "#{sid}.#{Time.now.to_i}.#{rand(100)}"
  end
 
  def self.delete sid
    require 'fileutils'
    FileUtils.mv(store_path(sid), File.join(BACKUP_DIR, random_suffix(sid)))
  end
 
  def self.delete! sid
    require 'fileutils'
    FileUtils.rm(store_path(sid))
  end
 
  def self.open sid
    self.new sid
  end
 
  def initialize sid
    @sid = sid
    raise "Not Found: #{sid}" unless SimpleStore.exist? sid
 
    @db = YAML::Store.new(SimpleStore.store_path(@sid))
    @store = {}
 
    @db.transaction{
      @db.roots.each{|key|
        @store[key] = @db[key]
      }
    }
  end
 
  def [](key)
    @store[key]
  end
 
  def []=(key, value)
    @store[key] = value
  end
 
  def commit
    @db.transaction{
      @store.each{|k, v|
        @db[k] = v
      }
    }
  end
 
  def delete
    if SimpleStore.exist?(@sid)
      SimpleStore.delete(@sid)
    end
  end
 
  def delete!
    if SimpleStore.exist?(@sid)
      SimpleStore.delete!(@sid)
    end
  end
 
  def id
    @sid
  end
end
 
class FileSimpleStore < SimpleStore
  def dir_path
    "#{STORE_DIR}/f.#{@sid}"
  end
  
  def attach name, contents
    dir = dir_path
    file = File.join(dir, 'file.' + name)
 
    Dir.mkdir(dir) unless FileTest.exist? dir
 
    open(file, 'wb'){|f|
      f.write(contents)
    }
 
    file
  end
 
  def attached_files
    Dir.glob(File.join(dir_path, '*')).to_a
  end
 
  def delete
    require 'fileutils'
    if FileTest.exists? dir_path
      FileUtils.mv(dir_path, File.join(BACKUP_DIR, SimpleStore.random_suffix(@sid)))
    end
    super
  end
 
  def delete!
    require 'fileutils'
    if FileTest.exists? dir_path
      FileUtils.rm_r(dir_path)
    end
    super
  end
end
 
if $0 == __FILE__
  SimpleStore.store_dir = 'sp_store'
  SimpleStore.backup_dir = 'sp_backup'
 
  if SimpleStore.exist? 'foo'
    SimpleStore.delete 'foo'
  end
 
  store = SimpleStore.make
  store['a'] = 'x'
  store['b'] = 'y'
  store['c'] = 'z'
 
  p store['a']
  store.commit
 
  system('ls sp_store')
  SimpleStore.delete store.id
  system('ls sp_store')
end