LoginSignup
1
2

More than 5 years have passed since last update.

Qiita:Team の Export data をmarkdownに変換

Last updated at Posted at 2016-02-27

Qiita:Teamでは、契約に対しての人数の制限があるので社内でも他の部門等へ見せたい場合などに少し手間がかかります。Qiita:Teamの機能でデータのExportができますのでその内容(json)を変換したいと思いググってみるとありました。

すこし古い様でQiitaのフォーマットが変わっておりそのままでは動作しなかったので一部修正しました。以下のファイルを Rakefileとして保管する。あとはrakeコマンドで実行する。もしかするとライブラリとか足りないかもしれないのでその時には gem install jsonなどとして導入する。


require 'json'
require 'yaml'
require 'nokogiri'
require 'uri'
require 'faraday'
require 'ostruct'
require 'pry'
require 'time'

def y data
  puts YAML.dump data
end

def fetch_img(item)
  html = Nokogiri::HTML.parse(item.rendered_body)
  html.css('img').each_with_index do |node, i|
    uri = URI.parse(node[:src])
    if uri.host.to_s.match(/qiita-image-store/)
      filename = "#{item.id}-#{i}#{File.extname(uri.path)}"
      File.binwrite("./images/#{filename}", Faraday.get(uri).body)
      item.body.sub!(/#{uri}/, "./images/#{filename}")
    end
  end
end

def fetch_icon(item)
  name = item.user.id
  url = item.user.profile_image_url
  filename = "#{name}#{File.extname(url)}"
  unless File.exists?(filename)
    File.binwrite("./images/#{filename}", Faraday.get(url).body)
  end
  "./images/#{filename}"
end

desc ''
task :default do
  system "rm -rf ./data"
  system "mkdir -p ./data"

  data = JSON.parse(File.read('data.json'), object_class: OpenStruct)

  Dir.chdir('./data') do
    data.articles.each do |article|
      body = ''

      author = article.user.id
      title = article.title.gsub(/[\p{P}]/, '-').gsub(/[[:blank:]]/, '-')
      print("title¥n")
      created_at = Time.parse(article.created_at)
      day = created_at.strftime('%F')
      filename = "%s-%s-%s.md" % [day, author, title]

      year = created_at.year
      month = created_at.month
      system "mkdir -p #{year}/#{month}/images"
      Dir.chdir("#{year}/#{month}") do

        body << "# #{title}\n\n"
        fetch_img(article)
        body << "#{article.body}\n\n"
        icon = fetch_icon(article)
        system "mogrify -resize 32x #{icon}"
        body << "Posted at #{created_at} by <img src=\"#{icon}\"> #{author}\n\n"

        if article.comments.length > 0
          article.comments.each do |comment|
            body << "<hr>\n\n"

            fetch_img(comment)
            body << "#{comment.body}\n\n"

            icon = fetch_icon(comment)
            system "mogrify -resize 32x #{icon}"
            body << "Comment posted by <img src=\"#{icon}\"> #{comment.user.url_name}\n\n"
          end
        end



        File.write(filename, body)
      end
    end
  end
end

必要に応じてドキュメントの構成とかREADME.mdつけたりとかすればよいかと。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2