Class: Apollo::CrawlerProgram

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

Constant Summary collapse

@@PROGRAM_DIR =
File.expand_path("~/.apollo-crawler")
@@CONFIG_PATH =
File.join(@@PROGRAM_DIR, "config.rb")

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCrawlerProgram

Initializer - Constructor



62
63
64
65
66
67
# File 'lib/apollo_crawler/program.rb', line 62

def initialize
	@caches = {}
	@crawlers = {}
	@formatter = RbConfig::DEFAULT_FORMATTER
	@formatters = {}
end

Class Method Details

.console_table(headings, rows) ⇒ Object

Show tabular data in form of CLI table



395
396
397
398
# File 'lib/apollo_crawler/program.rb', line 395

def self.console_table(headings, rows)
	table = Terminal::Table.new :headings => headings, :rows => rows
	puts table
end

Instance Method Details

#generate_crawler(name, url = nil, matcher = nil) ⇒ Object



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/apollo_crawler/program.rb', line 346

def generate_crawler(name, url = nil, matcher = nil)
	name = name.titleize.gsub(" ", "")

	if(@options[:verbose])
		puts "Generating new crawler '#{name}'"
	end

	template_path = RbConfig::CRAWLER_TEMPLATE_PATH
	puts template_path
	if(File.exists?(template_path) == false)
		puts "Template file '#{template_path}' does not exists!"
		return -1
	end

	if(@options[:verbose])
		puts "Using template '#{template_path}'"
	end

	dest_path = File.join(Dir.pwd, "#{name.underscore}.rb")

	url = url ? url : "http://some-url-here"
	matcher = matcher ? matcher : "//a"
	
	placeholders = {
		"CRAWLER_CLASS_NAME" => name,
		"CRAWLER_NAME" => name.titleize,
		"CRAWLER_URL"  => url,
		"CRAWLER_MATCHER" => matcher
	}

	puts "Generating crawler '#{name.titleize}', class: '#{name}', path: '#{dest_path}'"

	File.open(template_path, 'r') do |tmpl|
		File.open(dest_path, 'w') do |crawler|  
			while line = tmpl.gets  
				#puts line
				placeholders.each do |k, v|
					line.gsub!(k, v)
				end
				
				crawler.puts line
			end  
		end
	end  

	return 0
end

#get_crawlers(args) ⇒ Object

Get crawlers passd to cmd-line



452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/apollo_crawler/program.rb', line 452

def get_crawlers(args)
	crawlers = []
	if(args.length > 0)
		crawlers << args.shift
	end

	if(@options[:run_all])
		crawlers = @crawlers.keys
	end

	return crawlers
end

#init_formatterObject



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/apollo_crawler/program.rb', line 187

def init_formatter()
	# Set default formatter here
	formatter_name = "json"
	if(@options[:formatter])
		formatter_name = @options[:formatter]
	end

	# Look for specified formatter
	f = @formatters.select { |k, v|
		name = formatter_name.gsub(Apollo::Formatter::BaseFormatter::name_re, "")
		k.downcase == name
	}

	if(f)
		@formatter = f[f.keys[0]] 
	end
end

#init_optionsObject

Initialize command-line options



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

def init_options
	@options = {}
	
	@options[:doc_limit] = nil
	@options[:verbose] = false
	@options[:version] = false
	
	@options[:cache_dirs] = [
		RbConfig::CACHES_DIR
	]
	
	@options[:crawler_dirs] = [
		RbConfig::CRAWLERS_DIR
	]
	
	@options[:formatter_dirs] = [
		RbConfig::FORMATTERS_DIR
	]

	@options[:generate_crawler] = nil

	@optparser = OptionParser.new do | opts |
		opts.banner = "Usage: apollo-crawler [OPTIONS] CRAWLER_NAME [START_URL]"

		opts.separator ""
    			opts.separator "Specific options:"

		# This displays the help screen, all programs are
		# assumed to have this option.
		opts.on('-h', '--help', 'Display this screen') do
			@options[:show_help]
		end

		opts.on('-a', '--all', 'Run all crawlers') do
			@options[:run_all] = true
		end	

		opts.on('-f', '--format [NAME]', "Formatter used") do |name|
			@options[:formatter] = name
		end

		opts.on('-g', '--generate [NAME]', "Generate scaffold for new crawler") do |name|
			@options[:generate_crawler] = name
		end

		opts.on('-i', '--include [PATH]', 'Include additional crawler or crawler directory') do |path|
			@options[:crawler_dirs] << path
		end

		opts.on('-n', '--doc-limit [NUM]', 'Limit count of documents to be processed') do |count|
			@options[:doc_limit] = count.to_i
		end

		opts.on('-v', '--verbose', 'Enable verbose output') do
			@options[:verbose] = true
		end

		opts.on('-V', '--version', 'Show version info') do
			@options[:version] = true
		end

		opts.on('-l', '--list-crawlers', 'List of crawlers') do
			@options[:list_crawlers] = true
		end

		opts.on(nil, '--list-formatters', 'List of formatters available') do
			@options[:list_formatters] = true
		end			

		opts.on('-s', '--silent', 'Silent mode - do not print processed document') do
			@options[:silent] = true
		end	
	end
end

#init_program(args) ⇒ Object

Init program



480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/apollo_crawler/program.rb', line 480

def init_program(args)
	init_options()

	parse_options(args)

	init_program_directory()

	load_config_file()

	register_modules()

	res = process_options(args)
	if res != nil
		return res
	end

	init_formatter()
end

#init_program_directoryObject



465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/apollo_crawler/program.rb', line 465

def init_program_directory()
	dir = File.expand_path("~/.apollo-crawler")
	if(File.directory?(dir) == false)
		FileUtils.mkpath(dir)
	end

	config_path = File.join(File.dirname(__FILE__), 'config_user.trb')
	dest_path = File.join(dir, 'config.rb')

	if(File.exists?(config_path) && File.exists?(dest_path) == false)
		FileUtils.cp(config_path, dest_path)
	end
end

#list_crawlersObject

List available crawlers



401
402
403
404
# File 'lib/apollo_crawler/program.rb', line 401

def list_crawlers()
	CrawlerProgram.console_table(['name', 'class'], @crawlers)
	return
end

#list_formattersObject

List available formatters



407
408
409
410
# File 'lib/apollo_crawler/program.rb', line 407

def list_formatters()
	CrawlerProgram.console_table(['name', 'class'], @formatters)
	return
end

#load_config_fileObject

Load global options first Merge it with local options (if they exists)



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/apollo_crawler/program.rb', line 207

def load_config_file()
	config = @@CONFIG_PATH

	if(File.exists?(config))
		if(@options[:verbose])
			puts "Loading config '#{config}'"
		end
		
		require config
	else
		if(@options[:verbose])
			# TODO: Add support for initial rake task generation
			#          Something like this:
			#          rake config:init # Initializes config files with
			#            their defaults (if not exists already)        
			puts "Default config does not exist, skipping - '#{config}'"
		end
	end
end

#parse_options(args = ARGV) ⇒ Object

Parse the options passed to command-line



146
147
148
149
150
151
152
153
# File 'lib/apollo_crawler/program.rb', line 146

def parse_options(args = ARGV)
	# Parse the command-line. Remember there are two forms
	# of the parse method. The 'parse' method simply parses
	# ARGV, while the 'parse!' method parses ARGV and removes
	# any options found there, as well as any parameters for
	# the options. What's left is the list of files to resize.
	@optparser.parse!(args)
end

#process_options(args) ⇒ Object



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
# File 'lib/apollo_crawler/program.rb', line 155

def process_options(args)
	if(@options[:version])
		puts Apollo::VERSION
		return 0
	end

	if(@options[:show_help])
		puts @optparser
		return 0
	end

	if(@options[:generate_crawler])
		name = @options[:generate_crawler]
		url = args.length > 0 ? args[0] : nil
		matcher = args.length > 1 ? args[1] : nil
		
		return self.generate_crawler(name, url, matcher)
	end

	if(@options[:list_formatters])
		list_formatters()
		return 0
	end

	if(@options[:list_crawlers])
		list_crawlers()
		return 0
	end

	return nil
end

#register_cache(dir) ⇒ Object

Register caches



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
256
257
258
259
# File 'lib/apollo_crawler/program.rb', line 228

def register_cache(dir)			
	if(@options[:verbose]) 
		puts "Registering caches - '#{dir}'"
	end

	files = File.join(dir, "**", "*.rb")
	Dir.glob(files).each do |file|
		require file
	end

	tmp = Apollo::Cache.constants.select { |c| 
		Class === Apollo::Cache.const_get(c)
	}

	tmp.each do |x| 
		klass = Object.const_get('Apollo').const_get('Cache').const_get(x)
		@caches.merge!({ x.downcase.to_s => klass})
	end

	if(@options[:verbose])
		@caches.each do |cache, klass|
			name = klass

			# klass.ancestors.include?(Apollo::Caches::Cache)
			if  name == "Apollo::Caches::Cache"
				next
			end

			puts "Registered cache '#{cache}' -> '#{name}'"
		end
	end
end

#register_crawlers(dir) ⇒ Object

Register crawlers



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
# File 'lib/apollo_crawler/program.rb', line 262

def register_crawlers(dir)			
	if(@options[:verbose]) 
		puts "Registering crawlers - '#{dir}'"
	end

	files = File.join(dir, "**", "*.rb")
	Dir.glob(files).each do |file|
		require file
	end

	tmp = Apollo::Crawler.constants.select { |c| 
		Class === Apollo::Crawler.const_get(c)
	}

	tmp.each do |x| 
		klass = Object.const_get('Apollo').const_get('Crawler').const_get(x)
		name = x.to_s.downcase.gsub(Apollo::Crawler::BaseCrawler.name_re,"")
		@crawlers.merge!({ name => klass})
	end

	if(@options[:verbose])
		@crawlers.each do |crawler, klass|
			name = klass.new.class.name

			if  name == "Apollo::Crawler::Crawler"
				next
			end

			puts "Registered crawler '#{crawler}' -> '#{name}'"
		end
	end
end

#register_formatters(dir) ⇒ Object

Register formatters



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/apollo_crawler/program.rb', line 296

def register_formatters(dir)			
	if(@options[:verbose]) 
		puts "Registering formatters - '#{dir}'"
	end

	files = File.join(dir, "**", "*.rb")
	Dir.glob(files).each do |file|
		require file
	end

	tmp = Apollo::Formatter.constants.select { |c| 
		Class === Apollo::Formatter.const_get(c)
	}

	tmp.each do |x| 
		klass = Object.const_get('Apollo').const_get('Formatter').const_get(x)
		name = x.to_s.downcase.gsub(Apollo::Formatter::BaseFormatter.name_re,"")
		@formatters.merge!({ name => klass})
	end

	if(@options[:verbose])
		@formatters.each do |formatter, klass|
			name = klass.new.class.name

			if  name == "Apollo::Formatters::Formatter"
				next
			end

			puts "Registered formatter '#{formatter}' -> '#{name}'"
		end
	end
end

#register_modulesObject



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/apollo_crawler/program.rb', line 329

def register_modules()
	# Register caches which can be used
	@options[:cache_dirs].each do |dir|
		register_cache(dir)
	end

	# Register sites which can be crawled
	@options[:crawler_dirs].each do |dir|
		register_crawlers(dir)
	end

	# Register sites which can be crawled
	@options[:formatter_dirs].each do |dir|
		register_formatters(dir)
	end
end

#run(args = ARGV) ⇒ Object

Run Program



500
501
502
503
504
505
506
507
508
509
510
# File 'lib/apollo_crawler/program.rb', line 500

def run(args = ARGV)
	init_program(args)

	crawlers = get_crawlers(args)
	if(crawlers.empty?)
		puts @optparser
		return 0
	end

	return run_crawlers(crawlers, args)
end

#run_crawlers(crawlers, args) ⇒ Object



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/apollo_crawler/program.rb', line 412

def run_crawlers(crawlers, args)
	crawlers.each do |name|
		crawler_name = name.downcase.gsub(Apollo::Crawler::BaseCrawler.name_re, "")

		crawler = @crawlers[crawler_name]
		if(crawler == nil)
			puts "Invalid crawler name - '#{name}'"
			puts "See program help"
			return 0
		end

		if(@options[:verbose])
			puts "Running '#{crawler}'"
		end

		opts = {
			:doc_limit => @options[:doc_limit]
		}

		res = crawler.new.etl(args, opts) { | docs |
			if(docs.nil?)
				next
			end

			if(docs.kind_of?(Array) == false)
				docs = [docs]
			end

			if @options[:silent] != true
				docs.each do |doc|
					puts @formatter.format(doc)
				end
			end
		}
	end

	return 0
end