File: server.rb

package info (click to toggle)
subtle 0.11.3224-xi-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,600 kB
  • sloc: ansic: 14,699; ruby: 3,101; makefile: 17
file content (517 lines) | stat: -rw-r--r-- 14,386 bytes parent folder | download
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
# -*- encoding: utf-8 -*-
#
# @package sur
#
# @file Server functions
# @author Christoph Kappel <unexist@subforge.org>
# @version $Id: data/sur/server.rb,v 3182 2012/02/04 16:39:33 unexist $
#
# This program can be distributed under the terms of the GNU GPLv2.
# See the file COPYING for details.
#

require "rubygems"
require "fileutils"
require "yaml"
require "sinatra"
require "haml"
require "datamapper"
require "digest/md5"
require "uri"
require "net/http"
require "xmlrpc/marshal"

require "subtle/sur/specification"

module Subtle # {{{
  module Sur # {{{
    # Model classes for datamapper
    module Model # {{{

      # Sublet class database model
      class Sublet # {{{
        include DataMapper::Resource

        property(:id,          Serial)
        property(:name,        String, :unique_index => :name)
        property(:contact,     String, :length => 255)
        property(:description, String, :length => 255)
        property(:version,     String, :unique_index => :name)
        property(:date,        DateTime)
        property(:path,        String, :length => 255)
        property(:digest,      String, :length => 255)
        property(:ip,          String, :length => 255)
        property(:required,    String, :required => false)
        property(:downloads,   Integer, :default => 0)
        property(:annotations, Integer, :default => 0)
        property(:created_at,  DateTime)

        has(n, :authors, :model => "Sur::Model::Assoc::Author")
        has(n, :tags,    :model => "Sur::Model::Assoc::Tag")
      end # }}}

      # Tag class database model
      class Tag # {{{
        include DataMapper::Resource

        property(:id,         Serial)
        property(:name,       String, :length => 255, :unique => true)
        property(:created_at, DateTime)

        has(n, :taggings, :model => "Sur::Model::Assoc::Tag")
      end # }}}

      # User class database model
      class User # {{{
        include DataMapper::Resource

        property(:id,         Serial)
        property(:name,       String, :length => 255, :unique => true)
        property(:created_at, DateTime)
      end # }}}

      # Assoc classes for datamapper
      module Assoc

        # Tagging class database model
        class Author # {{{
          include DataMapper::Resource

          property(:id,         Serial)
          property(:user_id,    Integer, :unique_index => :author)
          property(:sublet_id,  Integer, :unique_index => :author)
          property(:created_at, DateTime)

          belongs_to(:user,   :model => "Sur::Model::User")
          belongs_to(:sublet, :model => "Sur::Model::Sublet")
        end # }}}

        # Tag class database model
        class Tag # {{{
          include DataMapper::Resource

          property(:id,         Serial)
          property(:tag_id,     Integer, :unique_index => :tag)
          property(:sublet_id,  Integer, :unique_index => :tag)
          property(:created_at, DateTime)

          belongs_to(:tag,    :model => "Sur::Model::Tag")
          belongs_to(:sublet, :model => "Sur::Model::Sublet")
        end # }}}

        # Tag class database model
        class Annotate # {{{
          include DataMapper::Resource

          property(:id,         Serial)
          property(:sublet_id,  Integer)
          property(:user_id,    Integer)
          property(:created_at, DateTime)

          belongs_to(:sublet, :model => "Sur::Model::Sublet")
          belongs_to(:user,   :model => "Sur::Model::User")
        end # }}}
      end
    end # }}}

    # Server class for repository management
    class Server # {{{
      # Database file
      DATABASE = Dir.pwd + "/repository.db"

      # Repository storage
      REPOSITORY = Dir.pwd + "/repository"

      # Cache file
      CACHE = Dir.pwd + "/cache.yaml"

      # Identi.ca username
      USERNAME = "subtle"

      # Identi.ca password
      PASSWORD = ""

      ## Sur::Server::initialize {{{
      # Create a new Server object
      #
      # @param [Number]  port  Default port
      # @return [Object] New Sur::Server
      #
      # @since 0.0
      #
      # @example
      #   client = Sur::Server.new
      #   => #<Sur::Server:xxx>

      def initialize(port = 4567)
        DataMapper.setup(:default, "sqlite3://" + DATABASE)
        #DataMapper::Model.raise_on_save_failure = true

        # Create database and store
        DataMapper.auto_migrate!  unless File.exist?(DATABASE)
        Dir.mkdir(REPOSITORY)     unless File.exist?(REPOSITORY)

        # Configure sinatra application
        set :port, port
      end # }}}

      ## Sur::Server::run {{{
      # Run sinatra application
      #
      # @since 0.0
      #
      # @example
      #  Sur::Server.new.run
      #  => nil

      def run
        helpers do # {{{
          def build_cache # :nodoc: {{{
            list = []

            # Fetch sublets from database
            Sur::Model::Sublet.all(:order => [ :name, :version.desc ]).each do |s|

              # Collect authors
              authors = []
              Sur::Model::Assoc::Author.all(:sublet_id => s.id).each do |a|
                authors.push(a.user.name)
              end

              # Collect tags
              tags = []
              Sur::Model::Assoc::Tag.all(:sublet_id => s.id).each do |a|
                tags.push(a.tag.name)
              end

              # Create spec
              spec = Sur::Specification.new do |spec|
                spec.name             = s.name
                spec.authors          = authors
                spec.contact          = s.contact
                spec.description      = s.description
                spec.version          = s.version
                spec.date             = s.date
                spec.tags             = tags
                spec.digest           = s.digest
                spec.required_version = s.required
              end

               list.push(spec)
            end

            # Store cache
            yaml = list.to_yaml
            File.open(Sur::Server::CACHE, "w+") do |out|
              YAML::dump(yaml, out)
            end

            puts ">>> Regenerated sublets cache with #{list.size} sublets"
          end # }}}

          def get_all_sublets_in_interval(args) # :nodoc: {{{
            sublets = []

            # Find sublets in interval
            if 2 == args.size
              Sur::Model::Sublet.all(
                  :created_at.gte => Time.at(args[0]),
                  :created_at.lte => Time.at(args[1])
                  ).each do |s|
                sublets << "%s-%s" % [ s.name, s.version ]
              end
            end

            XMLRPC::Marshal.dump_response(sublets)
          end # }}}
        end # }}}

        # Templates

        template :layout do # {{{
          <<EOF
!!! 1.1
%html
  %head
    %title SUR - Subtle User Repository

    %style{:type => "text/css"}
      :sass
        body
          :color #000000
          :background-color #ffffff
          :font-family Verdana,sans-serif
          :font-size 12px
          :margin 0px
          :padding 0px
        h1
          :color #444444
          :font-size 20px
          :margin 0 0 10px
          :padding 2px 10px 1px 0
        h2
          :color #444444
          :font-size 16px
          :margin 0 0 10px
          :padding 2px 10px 1px 0
        input
          :margin-top 1px
          :margin-bottom 1px
          :vertical-align middle
        input[type="text"]
          :border 1px solid #D7D7D7
        input[type="text"]:focus
          :border 1px solid #888866
        input[type="submit"]
          :background-color #F2F2F2
          :border 1px outset #CCCCCC
          :color #222222
        input[type="submit"]:hover
          :background-color #CCCCBB
        a#download:link, a#download:visited, a#download:active
          :color #000000
          :text-decoration none
          :border-bottom 1px dotted #E4E4E4
        a#download:hover
          :color #000000
          :text-decoration none
        a:link, a:visited, a:active
          :color #59554e
          :text-decoration underline
        a:hover
          :text-decoration none
        .center
          :margin 0px auto
        .italic
          :font-style italic
        .gray
          :color #999999
        #box
          :background-color #FCFCFC
          :border 1px solid #eee9de
          :color #505050
          :line-height 1.5em
          :padding 6px
          :margin-bottom 10px
          :margin-right 10px
          :margin-top 10px
          :float left
          :min-width 280px
          :min-height 240px
        #form
          :width 900px
          :padding 10px 0px 10px 0px
        #frame
          :padding 10px
        #left
          :margin-right 10px
          :margin-top 10px
          :float left
          :width 630px
        #right
          :margin-right 10px
          :margin-top 10px
          :float right
          :width 230px
          :text-align right
        #clear
          :clear both

  %body
    #frame
      =yield
EOF
        end # }}}

        template :index do # {{{
          <<EOF
%h2 Sublets
%p
  Small Ruby scripts written in a
  %a{:target => "_parent", :href => "http://en.wikipedia.org/wiki/Domain_Specific_Language"} DSL
  that provides things like system information for the
  %a{:target => "_parent", :href => "http://subtle.subforge.org"} subtle
  panel.

#form
  #left
    %form{:method => "get", :action => "/search"}
      Search:
      %input{:type => "text", :size => 40, :name => "query"}
      %input{:type => "submit", :name => "submit", :value => "Go"}

  #right
    %a{:target => "_parent", :href => "http://subforge.org/wiki/subtle/Specification"} Sublet specification
    |
    %a{:href => "http://sur.subforge.org/sublets"} All sublets

#clear

#box
  %h2 Latest sublets
  %ul
    -@newest.each do |s|
      %li
        %a#download{:href => "http://sur.subforge.org/get/%s" % [ s.digest ] }
          ="%s-%s" % [ s.name, s.version ]
        ="(%s)" % [ s.tags.map { |t| '<a href="/tag/%s">#%s</a>' % [ t.tag.name, t.tag.name ] }.join(", ") ]

#box
  %h2 Most downloaded
  %ul
    -@most.each do |s|
      %li
        %a#download{:href => "http://sur.subforge.org/get/%s" % [ s.digest ] }
          ="%s-%s" % [ s.name, s.version ]
        ="(%d)" % [ s.downloads ]

#box
  %h2 Never downloaded
  %ul
    -@never.each do |s|
      %li
        %a#download{:href => "http://sur.subforge.org/get/%s" % [ s.digest ] }
          ="%s-%s" % [ s.name, s.version ]
        ="(%s)" % [ s.tags.map { |t| '<a href="/tag/%s">#%s</a>' % [ t.tag.name, t.tag.name ] }.join(", ") ]

  %h2 Just broken
  %ul
    -@worst.each do |s|
      %li
        %a#download{:href => "http://sur.subforge.org/get/%s" % [ s.digest ] }
          ="%s-%s" % [ s.name, s.version ]
        ="(%d)" % [ s.annotations ]
EOF
        end # }}}

        template :tag do # {{{
          <<EOF
#box
  %h2
    Sublets tagged with
    %span.italic= @tag

  %ul
    -if !@list.nil?
      -@list.each do |s|
        %li
          %a#download{:href => "/get/%s" % [ s.digest ] }
            ="%s-%s" % [ s.name, s.version ]
          ="(%s)" % [ s.tags.map { |t| '<a href="/tag/%s">#%s</a>' % [ t.tag.name, t.tag.name ] }.join(", ") ]
#clear

.center
  %a{:href => "javascript:history.back()"} Back
EOF
        end # }}}

        template :sublets do # {{{
          <<EOF
#box
  %h2= "All sublets (%d)" % [ @list.size ]

  %ul
    -@list.each do |s|
      %li
        %a#download{:href => "/get/%s" % [ s.digest ] }
          ="%s-%s" % [ s.name, s.version ]
        ="(%s)" % [ s.tags.map { |t| '<a href="/tag/%s">#%s</a>' % [ t.tag.name, t.tag.name ] }.join(", ") ]
        %span.gray= "(%d downloads)" % [ s.downloads ]
#clear

.center
  %a{:href => "javascript:history.back()"} Back
EOF
        end # }}}

        template :search do # {{{
          <<EOF
#box
  %h2
    Search for
    %span.italic= @query

  %ul
    -@list.each do |s|
      %li
        %a#download{:href => "/get/%s" % [ s.digest ] }
          ="%s-%s" % [ s.name, s.version ]
        ="(%s)" % [ s.tags.map { |t| '<a href="/tag/%s">#%s</a>' % [ t.tag.name, t.tag.name ] }.join(", ") ]
        %span.gray= "(%d downloads)" % [ s.downloads ]
#clear

.center
  %a{:href => "javascript:history.back()"} Back
EOF
        end # }}}

        # Handlers

        get "/" do # {{{
          @newest = Sur::Model::Sublet.all(:order => [ :created_at.desc ], :limit => 10)
          @most   = Sur::Model::Sublet.all(:downloads.gte => 0, :order => [ :downloads.desc ], :limit => 10)
          @never  = Sur::Model::Sublet.all(:downloads => 0, :order => [ :created_at.asc ], :limit => 4)
          @worst  = Sur::Model::Sublet.all(:annotations.gt => 0, :order => [ :annotations.asc ], :limit => 4)

          haml(:index)
        end # }}}



        get "/tag/:tag" do # {{{
          @tag  = params[:tag].capitalize
          @list = Sur::Model::Sublet.all(
            Sur::Model::Sublet.tags.tag.name => params[:tag]
          )

          haml(:tag)
        end # }}}

        get "/sublets" do # {{{
          @list = Sur::Model::Sublet.all(:order => [ :name.asc ])

          haml(:sublets)
        end # }}}

        get "/search" do # {{{
          @query = params[:query]
          @list  = Sur::Model::Sublet.all(
            :name.like => params[:query].gsub(/\*/, "%")
          )

          haml(:search)
        end # }}}

        post "/annotate" do # {{{
          if (s = Sur::Model::Sublet.first(:digest => params[:digest]))
            # Find or create user
            u = Sur::Model::User.first_or_create(
              { :name       => params[:user] },
              { :created_at => Time.now      }
            )

            # Create annotation
            Sur::Model::Assoc::Annotate.create(
              :sublet_id  => s.id,
              :user_id    => u.id,
              :created_at => Time.now
            )

            # Increase annotation count
            s.annotations = s.annotations + 1
            s.save

            puts ">>> Added annotation from `#{u.name}` for `#{s.name}'"
          else
            puts ">>> WARNING: Cannot find sublet with digest `#{params[:digest]}`"
            halt 404
          end
        end # }}}

        Sinatra::Application.run!
      end # }}}
    end # }}}
  end # }}}
end # }}}

# vim:ts=2:bs=2:sw=2:et:fdm=marker