Class: Helper

Inherits:
Object
  • Object
show all
Defined in:
lib/Helper.rb

Constant Summary collapse

INLINE_MARKDOWN_ESCAPE_CHARS =

Characters with inline markdown meaning at any position — they can always trigger syntax (emphasis, code spans, link/image start), so escape them everywhere.

['\\', '`', '*', '_', '[', ']'].freeze
INLINE_MARKDOWN_ESCAPE_REGEX =
/[\\`*_\[\]]/.freeze
LINE_START_ESCAPE_CHARS =

Characters that only have meaning at the start of a paragraph (heading, blockquote, unordered list). Inside a line they’re plain text and don’t need a backslash.

['#', '>', '-', '+'].freeze

Class Method Summary collapse

Class Method Details

.createDirIfNotExist(dirPath) ⇒ Object



70
71
72
73
# File 'lib/Helper.rb', line 70

def self.createDirIfNotExist(dirPath)
    return if dirPath.nil? || dirPath.empty?
    FileUtils.mkdir_p(dirPath)
end

.createPostInfo(postInfo, isPin, isLockedPreviewOnly, isForJekyll) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/Helper.rb', line 127

def self.createPostInfo(, isPin, isLockedPreviewOnly, isForJekyll)
    title = .title&.gsub("[", "")&.gsub("]", "")

    tags = ""
    if !.tags.nil? && .tags.length > 0
        tags = "\"#{.tags.map { |tag| tag&.gsub("\"", "\\\"") }.join("\",\"")}\""
    end

    result = "---\n"
    result += "title: \"#{title&.gsub("\"", "\\\"")}\"\n"
    result += "author: \"#{.creator&.gsub("\"", "\\\"")}\"\n"
    result += "date: #{.firstPublishedAt.strftime('%Y-%m-%dT%H:%M:%S.%L%z')}\n"
    result += "last_modified_at: #{.latestPublishedAt.strftime('%Y-%m-%dT%H:%M:%S.%L%z')}\n"
    result += "categories: [\"#{.collectionName&.gsub("\"", "\\\"")}\"]\n"
    result += "tags: [#{tags}]\n"
    result += "description: \"#{.description&.gsub("\"", "\\\"")}\"\n"
    if !.previewImage.nil?
        result += "image:\r\n"
        result += "  path: /#{.previewImage}\r\n"
    end
    if isPin == true
        result += "pin: true\r\n"
    end
    if isLockedPreviewOnly == true
        result += "lockedPreviewOnly: true\r\n"
    end

    if isForJekyll
        result += "render_with_liquid: false\n"
    end
    result += "---\n"
    result += "\r\n"

    result
end

.createViewFullPost(postURL, isForJekyll) ⇒ Object



210
211
212
213
214
215
216
217
218
# File 'lib/Helper.rb', line 210

def self.createViewFullPost(postURL, isForJekyll)
    jekyllOpen = isForJekyll ? "{:target=\"_blank\"}" : ""

    text = "\r\n\r\n\r\n"
    text += "**This [post](#{postURL})#{jekyllOpen} is behind Medium's paywall, View the full [post](#{postURL})#{jekyllOpen} on Medium, converted by [ZMediumToMarkdown](https://github.com/ZhgChgLi/ZMediumToMarkdown)#{jekyllOpen}.**"
    text += "\r\n"

    text
end

.createWatermark(postURL, isForJekyll) ⇒ Object



200
201
202
203
204
205
206
207
208
# File 'lib/Helper.rb', line 200

def self.createWatermark(postURL, isForJekyll)
    jekyllOpen = isForJekyll ? "{:target=\"_blank\"}" : ""

    text = "\r\n\r\n\r\n"
    text += "_[Post](#{postURL})#{jekyllOpen} converted from Medium by [ZMediumToMarkdown](https://github.com/ZhgChgLi/ZMediumToMarkdown)#{jekyllOpen}._"
    text += "\r\n"

    text
end

.downloadLatestVersionObject



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/Helper.rb', line 92

def self.downloadLatestVersion()
    rootPath = File.expand_path('../', File.dirname(__FILE__))

    if File.file?("#{rootPath}/ZMediumToMarkdown.gemspec")
        apiPath = 'https://api.github.com/repos/ZhgChgLi/ZMediumToMarkdown/releases'
        releases = JSON.parse(Request.URL(apiPath).body)
        version = latestStableRelease(releases)
        return if version.nil?

        zipFilePath = version["zipball_url"]
        puts "Downloading latest version from github..."
        URI.open('latest.zip', 'wb') do |fo|
            fo.print URI.open(zipFilePath).read
        end

        puts "Unzip..."
        Zip::File.open("latest.zip") do |zipfile|
            zipfile.each do |file|
                fileNames = file.name.split("/")
                fileNames.shift
                filePath = fileNames.join("/")
                if filePath != ''
                    puts "Unzip...#{filePath}"
                    zipfile.extract(file, filePath) { true }
                end
            end
        end
        File.delete("latest.zip")

        puts "Update to version #{version["tag_name"]} successfully!"
    else
        system("gem update ZMediumToMarkdown")
    end
end

.escapeHTML(text, toHTMLEntity = true) ⇒ Object



61
62
63
64
65
66
67
68
# File 'lib/Helper.rb', line 61

def self.escapeHTML(text, toHTMLEntity = true)
    if toHTMLEntity
        text = text.gsub('<', '&lt;').gsub('>', '&gt;')
    else
        text = text.gsub('<', '\<').gsub('>', '\>')
    end
    text
end

.escapeMarkdown(text) ⇒ Object

Escape characters that always have inline markdown meaning. Used for standalone text snippets (e.g. fallback embed titles) where there is no surrounding paragraph context.



35
36
37
# File 'lib/Helper.rb', line 35

def self.escapeMarkdown(text)
    text.gsub(INLINE_MARKDOWN_ESCAPE_REGEX) { |c| "\\#{c}" }
end

.fetchOGImage(url) ⇒ Object



25
26
27
28
29
30
# File 'lib/Helper.rb', line 25

def self.fetchOGImage(url)
    html = Request.html(Request.URL(url))
    return "" unless html
    image = html.search("meta[property='og:image']").first
    image ? (image['content'] || "") : ""
end

.getLocalVersionObject



176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/Helper.rb', line 176

def self.getLocalVersion()
    rootPath = File.expand_path('../', File.dirname(__FILE__))

    result = nil
    if File.file?("#{rootPath}/ZMediumToMarkdown.gemspec")
        gemspecContent = File.read("#{rootPath}/ZMediumToMarkdown.gemspec")
        result = gemspecContent[/(gem\.version){1}\s+(\=)\s+(\'){1}(\d+(\.){1}\d+(\.){1}\d+){1}(\'){1}/, 4]
    else
        result = Gem.loaded_specs["ZMediumToMarkdown"].version.version
    end

    result.nil? ? nil : Gem::Version.new(result)
end

.getRemoteVersionFromGithubObject



190
191
192
193
194
195
196
197
198
# File 'lib/Helper.rb', line 190

def self.getRemoteVersionFromGithub()
    apiPath = 'https://api.github.com/repos/ZhgChgLi/ZMediumToMarkdown/releases'
    releases = JSON.parse(Request.URL(apiPath).body)
    version = latestStableRelease(releases)
    return nil if version.nil?

    tagName = version["tag_name"].to_s.downcase.gsub('v', '')
    Gem::Version.new(tagName)
end

.latestStableRelease(releases) ⇒ Object

Pick the latest non-prerelease release from the GitHub releases JSON. Returns nil if ‘releases` isn’t a list (e.g. a rate-limit error body).



87
88
89
90
# File 'lib/Helper.rb', line 87

def self.latestStableRelease(releases)
    return nil unless releases.is_a?(Array)
    releases.sort { |a, b| b["id"] <=> a["id"] }.find { |v| v["prerelease"] == false }
end

.makeWarningText(message) ⇒ Object



75
76
77
78
79
80
81
82
83
# File 'lib/Helper.rb', line 75

def self.makeWarningText(message)
    puts "####################################################\n"
    puts "#WARNING:\n"
    puts "##{message}\n"
    puts "#--------------------------------------------------#\n"
    puts "#Please feel free to open an Issue or submit a fix/contribution via Pull Request on:\n"
    puts "#https://github.com/ZhgChgLi/ZMediumToMarkdown\n"
    puts "####################################################\n"
end

.markdownEscapeNeeded?(char, precedingChars) ⇒ Boolean

Returns true if ‘char` at this position would be re-interpreted as markdown when emitted as-is.

‘precedingChars` is the array of chars (in original order) that appear before `char` in the same paragraph — needed to detect the ordered-list pattern `<digits>.` / `<digits>)` at line start.

Returns:

  • (Boolean)


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/Helper.rb', line 45

def self.markdownEscapeNeeded?(char, precedingChars)
    return true if INLINE_MARKDOWN_ESCAPE_CHARS.include?(char)

    if precedingChars.empty?
        # Block-level marker at the very start of the paragraph.
        return LINE_START_ESCAPE_CHARS.include?(char)
    end

    # Ordered-list marker: only when the entire prefix is digits.
    if (char == '.' || char == ')') && precedingChars.all? { |c| c.match?(/\d/) }
        return true
    end

    false
end

.printNewVersionMessageIfExistsObject



163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/Helper.rb', line 163

def self.printNewVersionMessageIfExists()
    remote = Helper.getRemoteVersionFromGithub()
    local  = Helper.getLocalVersion()
    return if remote.nil? || local.nil?

    if remote > local
        puts "##########################################################"
        puts "#####           New Version Available!!!             #####"
        puts "##### Please type `ZMediumToMarkdown -n` to update!! #####"
        puts "##########################################################"
    end
end