This repository was archived by the owner on Jul 27, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathexport_pages.rb
103 lines (86 loc) · 2.7 KB
/
export_pages.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
100
101
102
103
require 'csv'
require 'httparty'
require 'dotenv/load'
require 'logger'
require 'bundler/setup'
Bundler.require(:default)
logger = Logger.new('bookstack.log')
class BookStackAPI
include HTTParty
base_uri ENV['BS_URL']
headers 'Authorization' => "Token #{ENV['BS_TOKEN_ID']}:#{ENV['BS_TOKEN_SECRET']}"
format :json
def self.get(path, options = {})
url = "#{base_uri}#{path}"
::Logger.new(STDOUT).info("Making GET request to: #{url}")
::Logger.new(STDOUT).info("Query parameters: #{options[:query]}")
response = super(path, options)
::Logger.new(STDOUT).info("Response status: #{response.code}")
response
end
end
def get_all_items(path)
results = []
page_size = 500
offset = 0
total = 1
while offset < total
sleep(0.5) if offset > 0
response = BookStackAPI.get(path, query: { count: page_size, offset: offset })
total = response['total']
offset += page_size
results.concat(response['data'])
end
::Logger.new(STDOUT).info("Retrieved #{results.count} items from #{path}")
results
end
def generate_csv(pages, books, shelves)
book_map = books.map { |book| [book['id'], book] }.to_h
shelf_map = shelves.map { |shelf| [shelf['id'], shelf] }.to_h
CSV.open('bookstack_data.csv', 'w') do |csv|
csv << ['Type', 'ID', 'Name', 'URL', 'Book ID', 'Book Name', 'Book URL', 'Shelf Name', 'Date Modified', 'Date Created']
pages.each do |page|
book = book_map[page['book_id']]
shelf_name = shelf_map[book['shelf_id']]['name'] if book && shelf_map[book['shelf_id']]
csv << [
'Page',
page['id'],
page['name'],
"=HYPERLINK(\"#{ENV['BS_URL']}/books/#{page['book_id']}/page/#{page['id']}\")",
page['book_id'],
book ? book['name'] : '',
"=HYPERLINK(\"#{ENV['BS_URL']}/books/#{page['book_id']}\")",
shelf_name || '',
page['updated_at'],
page['created_at']
]
end
books.each do |book|
shelf_name = shelf_map[book['shelf_id']]['name'] if shelf_map[book['shelf_id']]
csv << [
'Book',
book['id'],
book['name'],
"=HYPERLINK(\"#{ENV['BS_URL']}/books/#{book['id']}\")",
'',
'',
'',
shelf_name || '',
book['updated_at'],
page['created_at']
]
end
end
end
begin
logger.info('Started generating BookStack data CSV')
logger.info("BookStack URL: #{ENV['BS_URL']}")
pages = get_all_items('/api/pages')
books = get_all_items('/api/books')
shelves = get_all_items('/api/shelves')
generate_csv(pages, books, shelves)
logger.info('CSV file generated: bookstack_data.csv')
rescue StandardError => e
logger.error("Error: #{e.message}")
logger.error(e.backtrace.join("\n"))
end