forked from rhomobile/rhomobile-docs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
docs.rb
588 lines (506 loc) · 17.5 KB
/
docs.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
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
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
256
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
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
require 'sinatra'
require 'indextank'
require 'pdfkit'
require 'coderay'
require 'rack/codehighlighter'
require './topic'
require './indicators'
require './api'
require './lib/term.rb'
require './pdfmaker'
require './version.rb'
class Docs < Sinatra::Base
unless development?
PDFKit.configure do |config|
config.wkhtmltopdf = File.expand_path(File.join( File.dirname(__FILE__), 'bin', 'wkhtmltopdf-amd64')).to_s
end
end
use PdfMaker
use Rack::Codehighlighter, :coderay, :markdown => true, :element => "pre>code",
:pattern => /:::(\w+)\s*(\n|
)/i, :logging => false
$LOAD_PATH << File.dirname(__FILE__) + '/lib'
set :app_file, __FILE__
enable :static
not_found do
begin
# puts "/v/2.2#{request.path}"
# puts "****#{request.path.split('/')[1]}:#{request.path.split('/')[2]}"
@alt_url = ''
topic = request.path.split('/')[4]
subpath = request.path.split('/')[3]
@alt_url = "#{request.scheme}://#{request.host}/en/2.2.0/#{subpath}/#{topic}"
# puts @alt_url
docversion = '2.2.0'
if topic.include?('/')
topic_file = topic
elsif subpath
if docversion.nil?
# topic_file = File.join(AppConfig['dirs'][subpath], "#{topic}.md")
else
topic_file = File.join("docs/en/#{docversion}/#{subpath}/", "#{topic}.md")
end
else
if docversion.nil?
topic_file = "#{settings.root}/docs/#{topic}.md"
else
topic_file = "#{settings.root}/docs/en/#{docversion}/#{topic}.md"
end
end
if topic == 'apicompatibility'
source = Indicators.apimatrix_markdown()
else
source = File.read(topic_file)
end
source = source
# puts "SOURCE:#{source}"
topic = Topic.load(topic, source)
@alt_title = topic.title
@alt_content = topic.content
@alt_intro = topic.intro
@alt = true
erb :not_found
rescue Exception => e
puts "ERROR:#{e}"
@alt=false
erb :not_found
end
end
['/en/2.2.0','/en/2.2.0/','/en/2.2.0/home'].each do |path|
get path do
@title = "Home"
@print = 0
@docversion = '2.2.0'
cache_long
erb :oldverhome
end
end
['/'].each do |path|
get path do
puts ENV["RACK_ENV"]
@title = "Home"
@print = 0
if ENV["RACK_ENV"] != 'production'
redirect "en/edge"
else
@docversion = AppConfig['current_version']
end
@docversion = params[:vnum]
if @docversion.nil?
@docversion = AppConfig['current_version']
end
cache_long
@recent_guides = recent_updates(5,'guide OR rhoconnect',@docversion)
@recent_api = recent_updates(5,'api',@docversion)
@recent_blogs = recent_updates(8,'blog','')
erb :index
end
end
['/', '/home', '/en/:vnum', '/en/:vnum/home'].each do |path|
get path do
@title = "Home"
@print = 0
@docversion = nil
@docversion = params[:vnum]
if @docversion.nil?
@docversion = AppConfig['current_version']
end
cache_long
@recent_guides = recent_updates(5,'guide OR rhoconnect',@docversion)
@recent_api = recent_updates(5,'api',@docversion)
@recent_blogs = recent_updates(8,'blog','')
erb :index
end
end
get '/print/home' do
@print = 1
cache_long
erb :index
end
get '/search' do
@print = 0
q = params[:q].gsub(':','\:')
page = params[:page].to_i
category = params[:c]
version = params[:v]
if version.nil? || version == ''
version = Version::CURR_VERSION
end
@docversion = version
total,dum_prev,dumb_next = search_for(q, page, '','')
search, prev_page, next_page = search_for(q, page, params[:c],params[:v])
#searchify object
categories = {}
if !category.nil? && category != ''
catArray = []
catArray = category.split(",")
categories["category"] = catArray
end
if !version.nil? && version != ''
verArray = []
verArray = version.split(",")
categories["version"] = verArray
end
# puts total
erb :search, :locals => {:search => search, :total => total, :query => params[:q], :category => category, :version => version, :prev_page => prev_page, :next_page => next_page, :categories => categories}
end
get '/opensearch' do
content_type 'application/xml', :charset => 'utf-8'
@print = 0
page = params[:page].to_i
search, prev_page, next_page = search_for(params[:q], page, params[:c],params[:v])
xml_string = '<?xml version="1.0" encoding="UTF-8"?>'
xml_string += ' <rss version="2.0" '
xml_string += ' xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/"'
xml_string += ' xmlns:atom="http://www.w3.org/2005/Atom">'
xml_string += ' <channel>'
xml_string += ' <title>RhoMobile Suite Documentation</title>'
xml_string += ' <link>http://docs.rhomobile.com</link>'
xml_string += ' <description>Search results for docs.rhomobile.com</description>'
xml_string += ' <opensearch:totalResults>' + search['matches'].to_s + '</opensearch:totalResults>'
xml_string += ' <opensearch:startIndex>' + ((page + 1) * 10).to_s + '</opensearch:startIndex>'
xml_string += ' <opensearch:itemsPerPage>10</opensearch:itemsPerPage>'
xml_string += ' <opensearch:Query role="request" searchTerms="' + params[:q] + '" startPage="1" />'
search['results'].each do |result|
xml_string += '<item>'
xml_string += ' <title><![CDATA[' + result['title'] + ']]></title>'
xml_string += ' <link>' + request.base_url + '/' + result['docid'] + '</link>'
xml_string += '<pubDate>' + File.mtime('docs/' + result['docid'] + '.md').to_s + '</pubDate>'
xml_string += ' <description><![CDATA['
xml_string += result['snippet_text']
xml_string += ' ]]></description>'
xml_string += ' </item>'
end
xml_string += ' </channel>'
xml_string += ' </rss> '
#<?xml version="1.0" encoding="UTF-8"?>
# <rss version="2.0"
# xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/"
# xmlns:atom="http://www.w3.org/2005/Atom">
# <channel>
# <title>Example.com Search: New York history</title>
# <link>http://example.com/New+York+history</link>
# <description>Search results for "New York history" at Example.com</description>
# <opensearch:totalResults>4230000</opensearch:totalResults>
# <opensearch:startIndex>21</opensearch:startIndex>
# <opensearch:itemsPerPage>10</opensearch:itemsPerPage>
# <atom:link rel="search" type="application/opensearchdescription+xml" href="http://example.com/opensearchdescription.xml"/>
# <opensearch:Query role="request" searchTerms="New York History" startPage="1" />
# <item>
# <title>New York History</title>
# <link>http://www.columbia.edu/cu/lweb/eguids/amerihist/nyc.html</link>
# <description>
# ... Harlem.NYC - A virtual tour and information on
# businesses ... with historic photos of Columbia's own New York
# neighborhood ... Internet Resources for the City's History. ...
# </description>
# </item>
# </channel>
# </rss>
#xml_string = '<?xml version="1.0" encoding="UTF-8"?>'
#xml_string += '<rss version="2.0" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:atom="http://www.w3.org/2005/Atom">'
# xml_string += ' <channel> <title>Example.com Search: New York history</title> <link>http://example.com/New+York+history</link> <description>Search results for "New York history" at Example.com</description> <opensearch:totalResults>4230000</opensearch:totalResults> <opensearch:startIndex>21</opensearch:startIndex> <opensearch:itemsPerPage>10</opensearch:itemsPerPage> <atom:link rel="search" type="application/opensearchdescription+xml" href="http://example.com/opensearchdescription.xml"/> <opensearch:Query role="request" searchTerms="New York History" startPage="1" /> <item> <title>New York History</title> <link>http://www.columbia.edu/cu/lweb/eguids/amerihist/nyc.html</link> <description> ... Harlem.NYC - A virtual tour and information on businesses ... with historic photos of Columbias own New York neighborhood ... Internet Resources for the Citys History. ... </description> </item> </channel> </rss>'
xml_string
end
#get '/:topic' do
# TODO: use proper regex
['/tutorial/:step/:topic/?', '/tutorial/:topic/?','/en/:vnum/tutorial/:step/:topic/?', '/en/:vnum/tutorial/:topic/?'].each do |path|
get path do
cache_long
@docversion = params[:vnum]
if @docversion.nil?
@docversion = AppConfig['current_version']
end
# If the topic ends in ".pdf" or ".print", tell render_topic to use the print view
topic_doc = params[:topic]
if topic_doc != 'welcome'
@tut = TUT.steps(params[:topic])
@doc = @tut[0]
@docTitle = @tut[1]
@baseurl = @tut[3]
@steps = @tut[4]
@topic = params[:topic]
@step = params[:step]
@prevStep = ''
@nextStep = ''
@currindex = -1
@stepTitle = ''
@steps.each do |gitlabel, title|
@currindex += 1 if [email protected]?
@stepTitle = title if [email protected]?
break if @step == gitlabel
end
@prevStep = @steps[@currindex - 1][0] if @currindex > 0
@nextStep = @steps[@currindex + 1][0] if @currindex < @steps.length - 1
@codediffUrl = "#{@baseurl}/compare/#{@prevStep}...#{@step}" if @prevStep != '' && @baseurl != ''
topic_doc += '.' + @step
end
render_topic topic_doc, 'tutorial', 0, @docversion
erb :tutorial
else
render_topic topic_doc, 'tutorial', 0, @docversion
erb :topic, :layout => !pjax?
end
end
end
['/en/:vnum/:topic/?', '/en/:vnum/:subpath/:topic/?'].each do |path|
get path do
# puts params[:vnum]
# puts params[:subpath]
# puts params[:topic]
cache_long
@docversion = nil
# If the topic ends in ".pdf" or ".print", tell render_topic to use the print view
if params[:topic] =~ /(\.pdf|\.print)$/
newtopic = params[:topic].gsub(/(\.pdf|\.print)/,"")
render_topic newtopic, params[:subpath], 1
else
if params[:topic].nil?
render_topic params[:topic], params[:subpath], 0
else
@docversion = params[:vnum]
render_topic params[:topic], params[:subpath], 0, params[:vnum]
end
end
end
end
get '/exists' do
status 200
topic = params[:doc]
if !File.exist?("docs/#{topic}.md")
status 404
end
end
helpers do
def render_topic(topic, subpath = nil, print = 0, docversion = nil)
# puts "#{subpath} :#{topic} : #{docversion}"
if TOC.find("/#{subpath}/#{topic}") == '' && docversion.nil?
#if not in TOC then make it default to 2.2 version
# docversion='2.2'
# @docversion = '2.2'
# redirect "/v/#{docversion}/#{subpath}/#{topic}"
end
@topic_file = topic_file(topic,subpath,docversion)
# puts @topic_file
if topic == 'apicompatibility'
source = Indicators.apimatrix_markdown()
else
source = File.read(topic_file(topic, subpath,docversion))
end
source = source
@topic = Topic.load(topic, source)
@title = @topic.title
@content = @topic.content
@intro = @topic.intro
@indicatorslang = ""
@oslist = ""
if(subpath and topic)
# @title += Indicators.load('/' + subpath + '/' + topic + '/')
@indicatorslang = Indicators.languages('/' + subpath + '/' + topic + '/')
@oslist = Indicators.oslist('/' + subpath + '/' + topic + '/')
end
@toc = @topic.toc
@toc_sub = @topic.toc_sub
@body = @topic.body
@print = print
if subpath.nil? || subpath == ''
@topicmodel = Topic.model('/' + topic)
erb :topic, :layout => !pjax?
else
@topicmodel = Topic.model(subpath + '/' + topic)
if subpath == 'api'
erb :topic_sidebar, :layout => !pjax?
else
erb :topic, :layout => !pjax?
end
end
rescue Errno::ENOENT
status 404
end
def search_for(query, page = 0, category='', version='')
client = IndexTank::Client.new(ENV['SEARCHIFY_API_URL'])
index = client.indexes(AppConfig['index'])
categories = {}
if !category.nil? && category != ''
catArray = []
catArray = category.split(",")
categories["category"] = catArray
categories["chunknum"] = '0'
end
if !version.nil? && version != ''
verArray = []
verArray = version.split(",")
categories["version"] = verArray
end
search = index.search(query, :start => page * 10, :len => 10,
:fetch => 'title,dockey,version,category,docexternal',
:snippet => 'text', :category_filters => categories)
next_page =
if search and search['matches'] and search['matches'] > (page + 1) * 10
page + 1
end
prev_page =
if page > 0
page - 1
end
[search, prev_page, next_page]
end
def recent_updates(count = 5, category='', version='')
client = IndexTank::Client.new(ENV['SEARCHIFY_API_URL'])
index = client.indexes(AppConfig['index'])
query = "category:(#{category})"
categories = {
"version" => version,
"chunknum" => '0'
}
# puts categories
if version != ''
search = index.search(query,
:len => count,
:function => 1,
:fetch => 'title,timestamp,docexternal,dockey',
:category_filters => categories)
else
search = index.search(query,
:len => count,
:function => 1,
:fetch => 'title,timestamp,docexternal,dockey')
end
puts search["matches"]
search
end
def topic_file(topic, subpath = nil,docversion = nil )
# puts "topic_file:#{topic}:#{subpath}:#{docversion}"
if topic.include?('/')
topic
# elsif subpath
# if docversion.nil?
# File.join(AppConfig['dirs'][subpath], "#{topic}.md")
# else
# File.join((AppConfig['dirs'][subpath]).gsub("docs/","v/#{docversion}/docs/"), "#{topic}.md")
# end
else
File.join("docs/en/#{docversion}/#{subpath}/#{topic}.md")
end
end
def topic_path
params[:subpath] ? ['en', params[:vnum], params[:subpath], params[:topic]].join('/') : params[:topic]
end
def cache_long
response['Cache-Control'] = "public, max-age=#{60 * 60}" unless Sinatra::Base.environment == :development
end
def slugify(title)
title.downcase.gsub(/[^a-z0-9 -]/, '').gsub(/ /, '-')
end
def sections
#toc.rb in root will be latest TOC
#doc versions can have unique TOC found in /v/VERSION/toc.rb
TOC.reload(params[:vnum])
TOC.sections
end
def related
#toc.rb in root will be latest TOC
#doc versions can have unique TOC found in /v/VERSION/toc.rb
TOC.related
end
def next_section(current_slug, root=sections)
return sections.first if current_slug.nil?
# root.each_with_index do |(slug, title, group, topics), i|
# if current_slug == slug and i < root.length-1
# return root[i+1]
# elsif topics.any?
# res = next_section(current_slug, topics)
# return res if res
# end
# end
# nil
end
def pjax?
env['HTTP_X_PJAX'] || params['_pjax']
end
alias_method :h, :escape_html
end
end
module TOC
extend self
def reload(docversion)
@sections = []
if docversion.nil?
file = File.dirname(__FILE__) + "/docs/en/#{AppConfig['current_version']}/toc.rb"
else
file = File.dirname(__FILE__) + "/docs/en/#{docversion}/toc.rb"
end
eval File.read(file), binding, file
end
def sections
@sections ||= []
end
# define a section
def section(name, title,group)
sections << [name, title,group, []]
yield if block_given?
end
# define a topic
def topic(name, title)
sections.last.last << [name, title, []]
end
def find(path)
puts "find path: #{path}"
compare = path.dup
compare.slice!(0)
compare.gsub!(/v\/([^\/]+)\//,'')
found=''
# found = @sections[0][0] # Default to first section
@sections.map do |section|
section[3].map do |slug, title, _|
found = section[0] if slug == compare
end
end
puts "Found:#{found}"
found
end
def findGroup(path)
compare = path.dup
compare.slice!(0)
compare.gsub!(/v\/([^\/]+)\//,'')
found = 'Home' # Default to first section
@sections.map do |section|
section[3].map do |slug, title, group, _|
found = section[2] if slug == compare
end
end
found
end
file = File.dirname(__FILE__) + "/docs/en/#{AppConfig['current_version']}/toc.rb"
eval File.read(file), binding, file
end
module TUT
extend self
def tutorials
@tutorials ||= []
end
# define a section
def tutorial(name, title,group,giturl)
tutorials << [name, title,group, giturl, []]
yield if block_given?
end
# define a topic
def gitlabel(name, title)
tutorials.last.last << [name, title, []]
end
def steps(tut)
# puts "#{tut}"
found={}
# found = @tutorials[0][0] # Default to first section
@tutorials.each do |tutsection|
# puts tutsection
if tutsection[0] == tut
found = tutsection
end
end
# puts "Found:#{found}"
found
end
file = File.dirname(__FILE__) + '/tuts.rb'
eval File.read(file), binding, file
end