|
| 1 | +class BaseConverter |
| 2 | + def initialize(dry_run:, client:, config:, screen_names: []) |
| 3 | + @dry_run = dry_run |
| 4 | + @client = client |
| 5 | + @screen_names = screen_names |
| 6 | + @config = config |
| 7 | + |
| 8 | + @files = Dir.glob File.expand_path(File.join(config['file_dir'], '*')) |
| 9 | + @images = Dir.glob File.expand_path(File.join(config['image_dir'], '*')) |
| 10 | + end |
| 11 | + attr_reader :dry_run, :client, :screen_names, :config, :files, :images |
| 12 | + |
| 13 | + def convert(content) |
| 14 | + { |
| 15 | + post: post_params(content), |
| 16 | + comments: content['comments'].map { |c| comments_params(c) } |
| 17 | + } |
| 18 | + end |
| 19 | + |
| 20 | + private |
| 21 | + |
| 22 | + def post_params(content) |
| 23 | + raise NotImplementedError.new("You must implement #{self.class}##{__method__}") |
| 24 | + end |
| 25 | + |
| 26 | + def comment_params(comment_content) |
| 27 | + raise NotImplementedError.new("You must implement #{self.class}##{__method__}") |
| 28 | + end |
| 29 | + |
| 30 | + def screen_name_for(name) |
| 31 | + return name if screen_names.include?(name) |
| 32 | + 'esa_bot' |
| 33 | + end |
| 34 | + |
| 35 | + def reupload(text) |
| 36 | + return text unless text |
| 37 | + |
| 38 | + text.gsub(%r{https://docbase.io/file_attachments/[a-z0-9\-\.]+}) do |match| |
| 39 | + basename = File.basename(match) |
| 40 | + local_file = files.find { |file| File.basename(file).end_with?(basename) } |
| 41 | + new_url_for_attachment(match, local_file, dry_run) |
| 42 | + end.gsub(%r{https://image.docbase.io/uploads/[a-z0-9\-\.]+}) do |match| |
| 43 | + basename = File.basename(match) |
| 44 | + local_file = images.find { |file| File.basename(file).end_with?(basename) } |
| 45 | + new_url_for_attachment(match, local_file, dry_run) |
| 46 | + end.gsub('](/images/file_icons/', '](https://docbase.io/images/file_icons/') |
| 47 | + end |
| 48 | + |
| 49 | + def new_url_for_attachment(match, local_file, dry_run) |
| 50 | + return match if !local_file |
| 51 | + '**will be re-uploaded to esa.io**' if dry_run |
| 52 | + |
| 53 | + # 再アップロード |
| 54 | + resp = client.upload_attachment(local_file) |
| 55 | + return local_file unless resp.status == 200 |
| 56 | + |
| 57 | + resp.body['attachment']['url'] |
| 58 | + end |
| 59 | +end |
0 commit comments