Class: ZMediumFetcher

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

Defined Under Namespace

Classes: Progress

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeZMediumFetcher

Returns a new instance of ZMediumFetcher.



71
72
73
74
# File 'lib/ZMediumFetcher.rb', line 71

def initialize
    @progress = Progress.new()
    @linkParser = LinkParser.new(nil)
end

Instance Attribute Details

#linkParserObject

Returns the value of attribute linkParser.



32
33
34
# File 'lib/ZMediumFetcher.rb', line 32

def linkParser
  @linkParser
end

#progressObject

Returns the value of attribute progress.



32
33
34
# File 'lib/ZMediumFetcher.rb', line 32

def progress
  @progress
end

Instance Method Details

#buildParser(imagePathPolicy) ⇒ Object



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
104
105
106
107
108
109
110
111
# File 'lib/ZMediumFetcher.rb', line 76

def buildParser(imagePathPolicy)
    h1Parser = H1Parser.new()
    h2Parser = H2Parser.new()
        h1Parser.setNext(h2Parser)
    h3Parser = H3Parser.new()
        h2Parser.setNext(h3Parser)
    h4Parser = H4Parser.new()
        h3Parser.setNext(h4Parser)
    ppParser = PParser.new()
        h4Parser.setNext(ppParser)
    uliParser = ULIParser.new()
        ppParser.setNext(uliParser)
    oliParser = OLIParser.new()
        uliParser.setNext(oliParser)
    mixtapeembedParser = MIXTAPEEMBEDParser.new()
        oliParser.setNext(mixtapeembedParser)
    pqParser = PQParser.new()
        mixtapeembedParser.setNext(pqParser)
    iframeParser = IframeParser.new()
    iframeParser.pathPolicy = imagePathPolicy
        pqParser.setNext(iframeParser)
    imgParser = IMGParser.new()
    imgParser.pathPolicy = imagePathPolicy
        iframeParser.setNext(imgParser)
    bqParser = BQParser.new()
        imgParser.setNext(bqParser)
    preParser = PREParser.new()
        bqParser.setNext(preParser)
    codeBlockParser = CodeBlockParser.new()
        preParser.setNext(codeBlockParser)
    fallbackParser = FallbackParser.new()
        codeBlockParser.setNext(fallbackParser)


    h1Parser
end

#downloadPost(postURL, pathPolicy) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/ZMediumFetcher.rb', line 113

def downloadPost(postURL, pathPolicy)
    postID = Post.getPostIDFromPostURLString(postURL)
    postPath = Post.getPostPathFromPostURLString(postURL)

    progress.postPath = postPath
    progress.message = "Downloading Post..."
    progress.printLog()

    postHtml = Request.html(Request.URL(postURL))

    postContent = Post.parsePostContentFromHTML(postHtml)
    if postContent.nil?
        raise "Error: Content is empty! PostURL: #{postURL}"
    end
    
     = Post.parsePostInfoFromPostContent(postContent, postID)

    sourceParagraphs = Post.parsePostParagraphsFromPostContent(postContent, postID)
    if sourceParagraphs.nil?
        raise "Error: Paragraph not found! PostURL: #{postURL}"
    end 
    
    progress.message = "Formatting Data..."
    progress.printLog()

    paragraphs = []
    oliIndex = 0
    previousParagraph = nil
    preTypeParagraphs = []
    sourceParagraphs.each do |sourcParagraph|
        paragraph = Paragraph.new(sourcParagraph, postID, postContent)
        if OLIParser.isOLI(paragraph)
            oliIndex += 1
            paragraph.oliIndex = oliIndex
        else
            oliIndex = 0
        end

        # if previous is OLI or ULI and current is not OLI or ULI
        # than insert a blank paragraph to keep markdown foramt correct
        if (OLIParser.isOLI(previousParagraph) && !OLIParser.isOLI(paragraph)) ||
            (ULIParser.isULI(previousParagraph) && !ULIParser.isULI(paragraph))
            paragraphs.append(Paragraph.makeBlankParagraph(postID))
        end

        # group by PRE paragraph to code block
        # because medium will give continue pre to present code block
        # e.g.
        # type=pre, text=<html>
        # type=pre, text=text
        # type=pre, text=</html>
        
        if !previousParagraph.nil?
            if PREParser.isPRE(paragraph)
                # if current is pre
                preTypeParagraphs.append(paragraph)
            elsif PREParser.isPRE(previousParagraph) && !PREParser.isPRE(paragraph)
                # if current is note pre and previousParagraph is pre and preTypeParagraphs > 1
                if preTypeParagraphs.length > 1
                    lastPreTypeParagraph = preTypeParagraphs.pop

                    # group by preParagraphs text to last preParagraph
                    groupByText = ""
                    preTypeParagraphs.each do |preTypeParagraph|
                        if groupByText != ""
                            groupByText += "\n"
                        end

                        markupParser = MarkupParser.new(postHtml, preTypeParagraph)
                        groupByText += markupParser.parse()
                    end
                    
                    lastPreTypeParagraph.text = "#{groupByText}"
                    lastPreTypeParagraph.type = CodeBlockParser.getTypeString()
                    
                    # remove all preParagraphs
                    preTypeParagraphNames = preTypeParagraphs.map do |preTypeParagraph|
                        preTypeParagraph.name
                    end
                    paragraphs = paragraphs.select do |paragraph| 
                        !preTypeParagraphNames.include? paragraph.name
                    end
                end
                preTypeParagraphs = []
            end
        end

        paragraphs.append(paragraph)
        previousParagraph = paragraph
    end

    postPathPolicy = PathPolicy.new(pathPolicy.getAbsolutePath(nil), "posts")

    imagePathPolicy = PathPolicy.new(postPathPolicy.getAbsolutePath(nil), "images")
    startParser = buildParser(imagePathPolicy)

    progress.totalPostParagraphsLength = paragraphs.length
    progress.currentPostParagraphIndex = 0
    progress.message = "Converting Post..."
    progress.printLog()

    absolutePath = postPathPolicy.getAbsolutePath("#{postPath}.md")
    
    # if markdown file is exists and last modification time is >= latestPublishedAt(last update post time on medium)
    if File.file?(absolutePath) && File.mtime(absolutePath) >= .latestPublishedAt
        # Already downloaded and nothing has changed!, Skip!
        progress.currentPostParagraphIndex = paragraphs.length
        progress.message = "Skip, Post already downloaded and nothing has changed!"
        progress.printLog()
    else
        Helper.createDirIfNotExist(postPathPolicy.getAbsolutePath(nil))
        File.open(absolutePath, "w+") do |file|
            # write postInfo into top
            file.puts(Helper.createPostInfo())
            
            index = 0
            paragraphs.each do |paragraph|
                markupParser = MarkupParser.new(postHtml, paragraph)
                paragraph.text = markupParser.parse()
                result = startParser.parse(paragraph)

                if !linkParser.nil?
                    result = linkParser.parse(result, paragraph.markupLinks)
                end
                
                file.puts(result)

                index += 1
                progress.currentPostParagraphIndex = index
                progress.message = "Converting Post..."
                progress.printLog()
            end

            file.puts(Helper.createWatermark(postURL))
        end
        FileUtils.touch absolutePath, :mtime => .latestPublishedAt

        progress.message = "Post Successfully Downloaded!"
        progress.printLog()
    end
    
    progress.postPath = nil
end

#downloadPostsByUsername(username, pathPolicy) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/ZMediumFetcher.rb', line 257

def downloadPostsByUsername(username, pathPolicy)
    progress.username = username
    progress.message = "Fetching infromation..."
    progress.printLog()

    userID = User.convertToUserIDFromUsername(username)
    if userID.nil?
        raise "Medium's Username:#{username} not found!"
    end

    progress.message = "Fetching posts..."
    progress.printLog()

    postURLS = []
    nextID = nil
    begin
        postPageInfo = User.fetchUserPosts(userID, nextID)
        postPageInfo["postURLs"].each do |postURL|
            postURLS.append(postURL)
        end
        nextID = postPageInfo["nextID"]
    end while !nextID.nil?

    @linkParser = LinkParser.new(postURLS)

    progress.totalPostsLength = postURLS.length
    progress.currentPostIndex = 0
    progress.message = "Downloading posts..."
    progress.printLog()

    userPathPolicy = PathPolicy.new(pathPolicy.getAbsolutePath(nil), "users/#{username}")
    index = 0
    postURLS.each do |postURL|
        downloadPost(postURL, userPathPolicy)

        index += 1
        progress.currentPostIndex = index
        progress.message = "Downloading posts..."
        progress.printLog()
    end

    progress.message = "All posts has been downloaded!, Total posts: #{postURLS.length}"
    progress.printLog()
end