improve user feedback for AJAX authentication
[coquelicot.git] / tools / migrate_jyraphe.rb
1 #!/usr/bin/env ruby1.8
2
3 $:.unshift File.join(File.dirname(__FILE__), '../lib')
4
5 require 'coquelicot'
6
7 module Coquelicot
8   class Options
9     def random_pass_length
10       16
11     end
12   end
13   class << self
14     def options
15       Options.new
16     end
17   end
18 end
19
20 class JyrapheMigrator
21   def initialize(jyraphe_var)
22     @var = jyraphe_var
23     @redirects = {}
24   end
25
26   def process
27     process_links
28     puts "RewriteEngine on"
29     @redirects.each_pair do |jyraphe, coquelicot|
30       puts "RewriteRule ^file-#{jyraphe}$ #{coquelicot} [L,R=301]"
31     end
32   end
33
34   def process_links
35     Dir.glob("#{@var}/links/*").each do |link_path|
36       link_name = File.basename(link_path)
37       one_time_only = link_name.slice(0, 1) == 'O'
38       File.open(link_path) do |link_file|
39         filename = link_file.readline.strip
40         mime_type = link_file.readline.strip
41         length = link_file.readline.strip.to_i
42         next if length > 10 * 1024 * 1024
43         file_key = link_file.readline.strip
44         if file_key.empty? then
45           random_pass = Coquelicot::gen_random_pass
46         end
47         expire_at = link_file.readline.strip.to_i
48         expire_at = [Time.now + Coquelicot.settings.maximum_expire,
49                      expire_at].min if expire_at <= 0
50         begin
51           coquelicot_link = File.open("#{@var}/files/#{filename}") do |src|
52             Coquelicot::depot.add_file(
53               src, file_key || random_pass,
54               { "Expire-at" => expire_at,
55                 "One-time-only" => one_time_only,
56                 "Filename" => filename,
57                 "Length" => length,
58                 "Content-Type" => mime_type
59               })
60           end
61           @redirects[link_name] = "#{coquelicot_link}"
62           @redirects[link_name] << "-#{random_pass}" if file_key.empty?
63         rescue Errno::ENOENT => ex
64           STDERR.puts "#{ex}"
65         end
66       end
67     end
68   end
69 end
70
71 def usage
72   STDERR.puts "Usage: #{$0} </path/to/jyraphe/var> </path/to/coquelicot/depot>"
73   exit 1
74 end
75
76 def main
77   usage unless ARGV.length == 2
78   jyraphe_var = ARGV[0]
79   coquelicot_depot = ARGV[1]
80
81   unless File.directory? "#{jyraphe_var}/files" and
82          File.directory? "#{jyraphe_var}/links" then
83     STDERR.puts "#{jyraphe_var} is not a Jyraphe 'var' directory."
84     exit 1
85   end
86   unless File.exists? "#{coquelicot_depot}/.links" then
87     STDERR.puts "#{coquelicot_depot} is not a Coquelicot depot."
88     exit 1
89   end
90
91   Coquelicot::Application.set :depot_path, coquelicot_depot
92   JyrapheMigrator.new(jyraphe_var).process
93 end
94
95 main