This repository has been archived by the owner on Jan 28, 2022. It is now read-only.
/
discourse_markdown.rb
82 lines (67 loc) · 1.98 KB
/
discourse_markdown.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
# frozen_string_literal: true
require 'faker'
require 'net/http'
require 'json'
module Faker
class DiscourseMarkdown < Markdown
class << self
attr_writer(:user_id)
def user_id
@user_id || ::Discourse::SYSTEM_USER_ID
end
def with_user(user_id)
current_user_id = self.user_id
self.user_id = user_id
begin
yield
ensure
self.user_id = current_user_id
end
end
def image
image = next_image
image_file = load_image(image)
upload = ::UploadCreator.new(
image_file,
image[:filename],
origin: image[:url]
).create_for(user_id)
::UploadMarkdown.new(upload).to_markdown
end
private
def next_image
if @images.blank?
@next_page = (@next_page || 0) + 1
url = URI("https://picsum.photos/v2/list?page=#{@next_page}&limit=100")
response = Net::HTTP.get(url)
json = JSON.parse(response)
@images = json.sort_by { |image| image["id"] }
end
image = @images.pop
{ filename: "#{image['id']}.jpg", url: "#{image['download_url']}.jpg" }
end
def image_cache_dir
@image_cache_dir ||= ::File.join(Rails.root, "tmp", "discourse_dev", "images")
end
def load_image(image)
cache_path = ::File.join(image_cache_dir, image[:filename])
if !::File.exists?(cache_path)
FileUtils.mkdir_p(image_cache_dir)
temp_file = ::FileHelper.download(
image[:url],
max_file_size: [SiteSetting.max_image_size_kb.kilobytes, 10.megabytes].max,
tmp_file_name: "image",
follow_redirect: true
)
FileUtils.cp(temp_file, cache_path)
end
::File.open(cache_path)
end
def available_methods
methods = super
methods << :image if ::DiscourseDev.config.include_images_in_posts
methods
end
end
end
end