This repository has been archived by the owner on Oct 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
project_import.rb
99 lines (81 loc) · 2.73 KB
/
project_import.rb
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
# frozen_string_literal: true
require 'esa'
require 'json'
require 'yaml'
require 'pp'
# Import to esa.io
class ProjectImporter
def initialize(esa_client)
@client = esa_client
@members = File.open('./data/all_members.txt').readlines.map(&:chomp)
end
attr_accessor :client, :members
def import(dry_run: true, start_index: 0)
data_files = Dir.glob('./data/projects/*.json').sort
# 実在メンバー一覧
members_set = Set.new(members) # Set 利用で検索効率を上げるハズ
File.open(File.path('./results/projects.tsv'), 'w') do |file|
data_files.each_with_index do |data_file, index|
next if index < start_index
article = JSON.parse(File.read(data_file))
# 記事作成者
screen_name = article.dig('user', 'id')&.downcase
# Qiita URL
qiita_url = "https://#{ENV['QIITA_CURRENT_TEAM']}.qiita.com/projects/#{article['id']}"
params = {
name: article['name'],
category: '(unsorted)/projects',
body_md: <<~BODY_MD,
created_at: #{article['created_at']}
qiita_url: #{qiita_url}
archived: #{article['archived']}
#{article['body']}
BODY_MD
wip: false,
message: '[skip notice] Imported from Qiita:Team',
user: members_set.include?(screen_name) ? screen_name : 'esa_bot'
}
if dry_run
puts "***** index: #{index} *****"
puts "Qiita URL: #{qiita_url}"
pp params
puts
next
end
print "[#{Time.now}] index[#{index}] #{article['name']} => "
response = client.create_post(params)
case response.status
when 201
esa_url = response.body['url']
puts "created: #{response.body['full_name']}\t#{esa_url}"
when 429
retry_after = (response.headers['Retry-After'] || 20 * 60).to_i
puts "rate limit exceeded: will retry after #{retry_after} seconds."
wait_for(retry_after)
redo
else
# 失敗しても中断はせずとりあえず結果を吐いて次のレコードへ
puts "failure with status: #{response.status}"
next
end
# 元の URL と esa アップロード後の画像 URL ペアを記録
# idx は記事 idx なので連続することがある
file.puts "#{index}\t#{qiita_url}\t#{esa_url}"
end
end
end
private
def wait_for(seconds)
(seconds / 10).times do
print '.'
sleep 10
end
puts
end
end
esa_client = Esa::Client.new(
access_token: ENV['ESA_ACCESS_TOKEN'],
current_team: ENV['ESA_CURRENT_TEAM']
)
importer = ProjectImporter.new(esa_client)
importer.import(dry_run: true) # default: dry_run