CombinedText stringlengths 4 3.42M |
|---|
class Invoice < ActiveRecord::Base
# Aspects
include ApplicationHelper
# Scopes
default_scope order(:due_date)
# Associations
belongs_to :customer, :class_name => 'Person'
belongs_to :company, :class_name => 'Person'
# Validations
validates_date :due_date, :value_date
validates_presence_of :customer, :company, :title, :state
# String
def to_s(format = :default)
return "" if amount.nil?
identifier = title
identifier += " / #{code}" if code.present?
case format
when :reference
return identifier + " (#{customer.to_s})"
when :long
return "%s: %s für %s à %s" % [I18n::localize(value_date), ident, customer, currency_fmt(amount)]
else
return identifier
end
end
before_save :update_code
def update_code
code = value_date.strftime("%y%m")
code += "%04i" % id
self.code = code
end
# Search
# ======
scope :by_text, lambda {|value|
text = '%' + value + '%'
amount = value.delete("'").to_f
if amount == 0.0
amount = nil unless value.match(/^[0.]*$/)
end
date = nil
begin
date = Date.parse(value)
rescue ArgumentError
end
people = Person.by_name(value)
where("title LIKE :text OR code LIKE :text OR remarks LIKE :text OR amount = :amount OR date(value_date) = :date OR date(due_date) = :date OR company_id IN (:people) OR customer_id IN (:people)", :text => text, :amount => amount, :date => date, :people => people)
}
# Attachments
# ===========
has_many :attachments, :as => :object
accepts_nested_attributes_for :attachments, :reject_if => proc { |attributes| attributes['file'].blank? }
# States
# ======
STATES = ['booked', 'canceled', 'paid', 'reactivated', 'reminded', '2xreminded', '3xreminded', 'encashment', 'written_off']
scope :by_state, lambda {|value|
where(:state => value) unless value == 'all'
}
scope :prepared, :conditions => "state = 'prepared'"
scope :canceled, :conditions => "state = 'canceled'"
scope :reactivated, :conditions => "state = 'reactivated'"
scope :active, :conditions => "NOT(state IN ('reactivated', 'canceled'))"
scope :open, :conditions => "NOT(state IN ('reactivated', 'canceled', 'paid'))"
scope :overdue, :conditions => ["(state = 'booked' AND due_date < :today) OR (state = 'reminded' AND reminder_due_date < :today) OR (state = '2xreminded' AND second_reminder_due_date < :today)", {:today => Date.today}]
scope :in_encashment, :conditions => ["state = 'encashment'"]
def active
!(state == 'canceled' or state == 'reactivated' or state == 'written_off')
end
def open
active and !(state == 'paid')
end
def state_adverb
I18n.t state, :scope => 'invoice.state'
end
def state_noun
I18n.t state, :scope => 'invoice.state_noun'
end
def overdue?
return true if state == 'booked' and due_date < Date.today
return true if state == 'reminded' and (reminder_due_date.nil? or reminder_due_date < Date.today)
return true if state == '2xreminded' and (second_reminder_due_date.nil? or second_reminder_due_date < Date.today)
return true if state == '3xreminded' and (third_reminder_due_date.nil? or third_reminder_due_date < Date.today)
return false
end
# Period
# ======
scope :active_at, lambda {|value| Invoice.where("date(duration_from) < :date AND date(duration_to) > :date", :date => value)}
# Bookings
# ========
include HasAccounts::Model
# Build booking
#
# We pass the value_date to the booking
def build_booking(params = {}, template_code = nil)
invoice_params = {:value_date => self.value_date}
template_code ||= self.class.to_s.underscore + ':invoice'
invoice_params.merge!(params)
super(invoice_params, template_code)
end
# Line Items
# ==========
has_many :line_items, :autosave => true
accepts_nested_attributes_for :line_items, :allow_destroy => true, :reject_if => proc { |attributes| attributes['quantity'].blank? or attributes['quantity'] == '0' }
def amount
if line_items.empty?
value = self[:amount]
else
value = line_items.sum('times * price').to_f
end
if value
return value.currency_round
else
return nil
end
end
def overdue?
return true if state == 'booked' and due_date < Date.today
return true if state == 'reminded' and (reminder_due_date.nil? or reminder_due_date < Date.today)
return true if state == '2xreminded' and (second_reminder_due_date.nil? or second_reminder_due_date < Date.today)
return true if state == '3xreminded' and (third_reminder_due_date.nil? or third_reminder_due_date < Date.today)
false
end
end
Drop second, identical Invoice.overdue? method.
class Invoice < ActiveRecord::Base
# Aspects
include ApplicationHelper
# Scopes
default_scope order(:due_date)
# Associations
belongs_to :customer, :class_name => 'Person'
belongs_to :company, :class_name => 'Person'
# Validations
validates_date :due_date, :value_date
validates_presence_of :customer, :company, :title, :state
# String
def to_s(format = :default)
return "" if amount.nil?
identifier = title
identifier += " / #{code}" if code.present?
case format
when :reference
return identifier + " (#{customer.to_s})"
when :long
return "%s: %s für %s à %s" % [I18n::localize(value_date), ident, customer, currency_fmt(amount)]
else
return identifier
end
end
before_save :update_code
def update_code
code = value_date.strftime("%y%m")
code += "%04i" % id
self.code = code
end
# Search
# ======
scope :by_text, lambda {|value|
text = '%' + value + '%'
amount = value.delete("'").to_f
if amount == 0.0
amount = nil unless value.match(/^[0.]*$/)
end
date = nil
begin
date = Date.parse(value)
rescue ArgumentError
end
people = Person.by_name(value)
where("title LIKE :text OR code LIKE :text OR remarks LIKE :text OR amount = :amount OR date(value_date) = :date OR date(due_date) = :date OR company_id IN (:people) OR customer_id IN (:people)", :text => text, :amount => amount, :date => date, :people => people)
}
# Attachments
# ===========
has_many :attachments, :as => :object
accepts_nested_attributes_for :attachments, :reject_if => proc { |attributes| attributes['file'].blank? }
# States
# ======
STATES = ['booked', 'canceled', 'paid', 'reactivated', 'reminded', '2xreminded', '3xreminded', 'encashment', 'written_off']
scope :by_state, lambda {|value|
where(:state => value) unless value == 'all'
}
scope :prepared, :conditions => "state = 'prepared'"
scope :canceled, :conditions => "state = 'canceled'"
scope :reactivated, :conditions => "state = 'reactivated'"
scope :active, :conditions => "NOT(state IN ('reactivated', 'canceled'))"
scope :open, :conditions => "NOT(state IN ('reactivated', 'canceled', 'paid'))"
scope :overdue, :conditions => ["(state = 'booked' AND due_date < :today) OR (state = 'reminded' AND reminder_due_date < :today) OR (state = '2xreminded' AND second_reminder_due_date < :today)", {:today => Date.today}]
scope :in_encashment, :conditions => ["state = 'encashment'"]
def active
!(state == 'canceled' or state == 'reactivated' or state == 'written_off')
end
def open
active and !(state == 'paid')
end
def state_adverb
I18n.t state, :scope => 'invoice.state'
end
def state_noun
I18n.t state, :scope => 'invoice.state_noun'
end
def overdue?
return true if state == 'booked' and due_date < Date.today
return true if state == 'reminded' and (reminder_due_date.nil? or reminder_due_date < Date.today)
return true if state == '2xreminded' and (second_reminder_due_date.nil? or second_reminder_due_date < Date.today)
return true if state == '3xreminded' and (third_reminder_due_date.nil? or third_reminder_due_date < Date.today)
return false
end
# Period
# ======
scope :active_at, lambda {|value| Invoice.where("date(duration_from) < :date AND date(duration_to) > :date", :date => value)}
# Bookings
# ========
include HasAccounts::Model
# Build booking
#
# We pass the value_date to the booking
def build_booking(params = {}, template_code = nil)
invoice_params = {:value_date => self.value_date}
template_code ||= self.class.to_s.underscore + ':invoice'
invoice_params.merge!(params)
super(invoice_params, template_code)
end
# Line Items
# ==========
has_many :line_items, :autosave => true
accepts_nested_attributes_for :line_items, :allow_destroy => true, :reject_if => proc { |attributes| attributes['quantity'].blank? or attributes['quantity'] == '0' }
def amount
if line_items.empty?
value = self[:amount]
else
value = line_items.sum('times * price').to_f
end
if value
return value.currency_round
else
return nil
end
end
end
|
# Who has done the most events? Just counts starts/appearences in results. Not pefect -- some events
# are probably over-counted.
class Ironman < Competition
def friendly_name
'Ironman'
end
# TODO Can't we just iterate through all of a racer's results? Would need to weed out many results
def Ironman.years
years = []
results = connection.select_all(
"select distinct extract(year from date) as year from events where type = 'Ironman'"
)
results.each do |year|
years << year.values.first.to_i
end
years.sort.reverse
end
def Ironman.expire_cache
FileUtils::rm_rf("#{RAILS_ROOT}/public/ironman.html")
FileUtils::rm_rf("#{RAILS_ROOT}/public/ironman")
end
def points_for(source_result)
1
end
def break_ties?
false
end
def source_results(race)
Result.find_by_sql(
%Q{SELECT results.id as id, race_id, racer_id, team_id, place FROM results
LEFT OUTER JOIN races ON races.id = results.race_id
LEFT OUTER JOIN standings ON races.standings_id = standings.id
LEFT OUTER JOIN events ON standings.event_id = events.id
WHERE (races.category_id is not null
and events.type = 'SingleDayEvent'
and standings.ironman = true
and events.date >= '#{year}-01-01'
and events.date <= '#{year}-12-31')
ORDER BY racer_id}
)
end
def expire_cache
Ironman.expire_cache
end
end
Ironman now ignores DNSes
# Who has done the most events? Just counts starts/appearences in results. Not pefect -- some events
# are probably over-counted.
class Ironman < Competition
def friendly_name
'Ironman'
end
# TODO Can't we just iterate through all of a racer's results? Would need to weed out many results
def Ironman.years
years = []
results = connection.select_all(
"select distinct extract(year from date) as year from events where type = 'Ironman'"
)
results.each do |year|
years << year.values.first.to_i
end
years.sort.reverse
end
def Ironman.expire_cache
FileUtils::rm_rf("#{RAILS_ROOT}/public/ironman.html")
FileUtils::rm_rf("#{RAILS_ROOT}/public/ironman")
end
def points_for(source_result)
1
end
def break_ties?
false
end
def source_results(race)
Result.find_by_sql(
%Q{SELECT results.id as id, race_id, racer_id, team_id, place FROM results
LEFT OUTER JOIN races ON races.id = results.race_id
LEFT OUTER JOIN standings ON races.standings_id = standings.id
LEFT OUTER JOIN events ON standings.event_id = events.id
WHERE (place != 'DNS'
and races.category_id is not null
and events.type = 'SingleDayEvent'
and standings.ironman = true
and events.date >= '#{year}-01-01'
and events.date <= '#{year}-12-31')
ORDER BY racer_id}
)
end
def expire_cache
Ironman.expire_cache
end
end |
class Listing < ActiveRecord::Base
attr_accessible :photo, :user_id, :name, :address, :latitude, :longitude, :listing_images_attributes
belongs_to :user
has_many :listing_images, :dependent => :destroy
accepts_nested_attributes_for :listing_images
geocoded_by :address
after_validation :geocode
reverse_geocoded_by :latitude, :longitude do |obj,results|
if geo = results.first
obj.city = geo.city
obj.state = geo.state
end
end
after_validation :reverse_geocode
#Embarrassing... Changing this soon.
def shortenState
case self.state
when /alabama/i
self.state = "AL"
when /alaska/i
self.state = "AK"
end
when /arkansas/i
self.state = "AR"
end
when /california/i
self.state = "CA"
end
when /colorado/i
self.state = "CO"
end
when /connecticut/i
self.state = "CT"
end
when /delaware/i
self.state = "DE"
end
when /DC/i
self.state = "DC"
end
when /florida/i
self.state = "FL"
end
when /georgia/i
self.state = "GA"
end
when /hawaii/i
self.state = "HI"
end
when /idago/i
self.state = "ID"
end
when /illinois/i
self.state = "IL"
end
when /indiana/i
self.state = "IN"
end
when /iowa/i
self.state = "IA"
end
when /kansas/i
self.state = "KS"
end
when /kentucky/i
self.state = "KY"
end
when /louisiana/i
self.state = "LA"
end
when /maine/i
self.state = "ME"
end
when /maryland/i
self.state = "MD"
end
when /massachusetts/i
self.state = "MA"
end
when /michigan/i
self.state = "MI"
end
when /minnesota/i
self.state = "MN"
end
when /mississippi/i
self.state = "MS"
end
when /missouri/i
self.state = "MO"
end
when /montana/i
self.state = "MT"
end
when /nebraska/i
self.state = "NE"
end
when /nevada/i
self.state = "NV"
end
when /new hampshire/i
self.state = "NH"
end
when /new jersey/i
self.state = "NJ"
end
when /new mexico/i
self.state = "NM"
end
when /new york/i
self.state = "NY"
end
when /north carolina/i
self.state = "NC"
end
when /north dakota/i
self.state = "ND"
end
when /ohio/i
self.state = "OH"
end
when /oklahoma/i
self.state = "OK"
end
when /oregon/i
self.state = "OR"
end
when /pennsylvania/i
self.state = "PA"
end
when /rhode island/i
self.state = "RI"
end
when /south carolina/i
self.state = "SC"
end
when /south dakota/i
self.state = "SD"
end
when /tennessee/i
self.state = "TN"
end
when /texas/i
self.state = "TX"
end
when /utah/i
self.state = "UT"
end
when /vermont/i
self.state = "VT"
end
when /virginia/i
self.state = "VA"
end
when /washington/i
self.state = "WA"
end
when /west virginia/i
self.state = "WV"
end
when /wisconsin/i
self.state = "WI"
end
when /wyoming/i
self.state = "WY"
end
end
before_save :shortenState
end
whoops
class Listing < ActiveRecord::Base
attr_accessible :photo, :user_id, :name, :address, :latitude, :longitude, :listing_images_attributes
belongs_to :user
has_many :listing_images, :dependent => :destroy
accepts_nested_attributes_for :listing_images
geocoded_by :address
after_validation :geocode
reverse_geocoded_by :latitude, :longitude do |obj,results|
if geo = results.first
obj.city = geo.city
obj.state = geo.state
end
end
after_validation :reverse_geocode
#Embarrassing... Changing this soon.
def shortenState
case self.state
when /alabama/i
self.state = "AL"
when /alaska/i
self.state = "AK"
when /arkansas/i
self.state = "AR"
when /california/i
self.state = "CA"
when /colorado/i
self.state = "CO"
when /connecticut/i
self.state = "CT"
when /delaware/i
self.state = "DE"
when /DC/i
self.state = "DC"
when /florida/i
self.state = "FL"
when /georgia/i
self.state = "GA"
when /hawaii/i
self.state = "HI"
when /idago/i
self.state = "ID"
when /illinois/i
self.state = "IL"
when /indiana/i
self.state = "IN"
when /iowa/i
self.state = "IA"
when /kansas/i
self.state = "KS"
when /kentucky/i
self.state = "KY"
when /louisiana/i
self.state = "LA"
when /maine/i
self.state = "ME"
when /maryland/i
self.state = "MD"
when /massachusetts/i
self.state = "MA"
when /michigan/i
self.state = "MI"
when /minnesota/i
self.state = "MN"
when /mississippi/i
self.state = "MS"
when /missouri/i
self.state = "MO"
when /montana/i
self.state = "MT"
when /nebraska/i
self.state = "NE"
when /nevada/i
self.state = "NV"
when /new hampshire/i
self.state = "NH"
when /new jersey/i
self.state = "NJ"
when /new mexico/i
self.state = "NM"
when /new york/i
self.state = "NY"
when /north carolina/i
self.state = "NC"
when /north dakota/i
self.state = "ND"
when /ohio/i
self.state = "OH"
when /oklahoma/i
self.state = "OK"
when /oregon/i
self.state = "OR"
when /pennsylvania/i
self.state = "PA"
when /rhode island/i
self.state = "RI"
when /south carolina/i
self.state = "SC"
when /south dakota/i
self.state = "S"
when /tennessee/i
self.state = "TN"
when /texas/i
self.state = "TX"
when /utah/i
self.state = "UT"
when /vermont/i
self.state = "VT"
when /virginia/i
self.state = "VA"
when /washington/i
self.state = "WA"
when /west virginia/i
self.state = "WV"
when /wisconsin/i
self.state = "WI"
when /wyoming/i
self.state = "WY"
end
end
before_save :shortenState
end
|
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'batch-rails2/version'
Gem::Specification.new do |gem|
gem.name = "batch-rails2"
gem.version = BatchRails2::VERSION
gem.authors = ["Marten Klitzke"]
gem.email = ["m.klitzke@gmail.com"]
gem.description = %q{Batch icons as a webfont for rails}
gem.summary = %q{Basic integration for the Batch Webfont Icons}
gem.homepage = "https://github.com/mortik/batch-rails2"
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_development_dependency "bundler", "~> 1.3"
gem.add_development_dependency "rake"
gem.add_development_dependency "mocha"
gem.add_development_dependency "sqlite3"
gem.add_dependency "rails", "~> 3.2.12"
gem.add_dependency "sass-rails", "~> 3.2.6"
end
loosen dependency versions
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'batch-rails2/version'
Gem::Specification.new do |gem|
gem.name = "batch-rails2"
gem.version = BatchRails2::VERSION
gem.authors = ["Marten Klitzke"]
gem.email = ["m.klitzke@gmail.com"]
gem.description = %q{Batch icons as a webfont for rails}
gem.summary = %q{Basic integration for the Batch Webfont Icons}
gem.homepage = "https://github.com/mortik/batch-rails2"
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_development_dependency "bundler", "~> 1.3"
gem.add_development_dependency "rake"
gem.add_development_dependency "mocha"
gem.add_development_dependency "sqlite3"
gem.add_dependency "rails", ">= 3.2.12"
gem.add_dependency "sass-rails", ">= 3.2.6"
end
|
class Listing < ApplicationRecord
def illegal?
Phrase.all.each do |phrase|
if self.description.match(/#{phrase.content}/i)
puts "found one!: #{phrase.content}"
return true
end
end
return false
end
def check_phrase(phrase)
regex = phrase.strip.gsub(' ','\s')
reg_obj = Regexp.new(/#{regex}/i)
if reg_obj.match(self.description)
true
else
false
end
end
def self.discriminatory
Listing.all.select {|listing| listing.discriminatory == true}
end
end
removed unnecessary print commmand
class Listing < ApplicationRecord
def illegal?
Phrase.all.each do |phrase|
if self.description.match(/#{phrase.content}/i)
return true
end
end
return false
end
def check_phrase(phrase)
regex = phrase.strip.gsub(' ','\s')
reg_obj = Regexp.new(/#{regex}/i)
if reg_obj.match(self.description)
true
else
false
end
end
def self.discriminatory
Listing.all.select {|listing| listing.discriminatory == true}
end
end
|
class Mailman < ActionMailer::Base
# bcc BCC addresses for the message
# body Define the body of the message. This is either a Hash
# (in which case it specifies the variables to pass to the template when it is rendered),
# or a string, in which case it specifies the actual text of the message.
# cc CC addresses for the message.
# charset Charset to use for the message. This defaults to the default_charset
# specified for ActionMailer::Base.
# content_type Content type for the message. This defaults to <text/plain in most cases,
# but can be automatically set in some situations.
# from From address for the message.
# reply_to Address (if different than the “from” address) to direct replies to this message.
# headers Additional headers to be added to the message.
# implicit_parts_order Specify the order in which parts should be sorted, based on content-type.
# This defaults to the value for the default_implicit_parts_order.
# mime_version Defaults to “1.0”, but may be explicitly given if needed.
# recipient The recipient addresses for the message, either as a string (for a single address)
# or an array (for multiple addresses).
# sent_on The date on which the message was sent. If not set (the default), the
# header will be set by the delivery agent.
# subject Specify the subject of the message.
# template Specify the template name to use for current message. This is the “base” template name,
# without the extension or directory, and may be used to have multiple mailer methods share
# the same template.
# Method for processing incoming messages
# pre: (Tmail email)
def receive(email)
# Extract out <list>+<thread>@<domain>
s_list, s_topic, s_domain =
email.to.first.match(/^(\w+)\+?([0-9a-e]*)\@([\w\.]+)$/).to_a[1..3]
# Don't storm if using BCC method with To: noreply
# TODO: remove
if(s_list == "mailer" || s_list == "noreply")
exit
end
# Make sure the list exists
unless(List.exists?(:short_name => s_list))
Mailman.deliver_no_such_list(email)
exit
end
list = List.find_by_short_name(s_list)
# Make sure they are in the list (allowed to post)
unless(list.subscribers.exists?(:email => email.from))
Mailman.deliver_cannot_post(list, email)
exit
end
# Check if this is a response to an existing topic or a new message
if(s_topic.length > 0)
unless(Topic.exists?(:key => s_topic))
Mailman.deliver_no_such_topic(list, email)
end
topic = Topic.find_by_key(s_topic)
# Strip out the subject crap
# Can't use gsub! because subject isn't actually a string unless coerced
email.subject = email.subject.gsub(/\[#{list.short_name}\]/, "")
# Clean out RE and FW's
email.subject = email.subject.gsub(/([rR][eE]:\ *){2,}/, "RE: ")
else
topic = list.topics.create(
:name => email.subject
)
end
message = topic.messages.build(:subject => email.subject, :body => email.body)
message.author = Subscriber.find_by_email(email.from)
message.save
list.subscribers.each do |subscriber|
Mailman.deliver_to_mailing_list(topic, email, subscriber)
end
end
# Send a test e-mail to everyone on a given list
# pre: (List list)
def list_test_dispatch(list)
list.subscribers.each do |subscriber|
#recipients "noreply@" + APP_CONFIG[:email_domain]
recipients subscriber.name + " <#{subscriber.email}>"
#bcc list.subscribers.map(&:email)
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "[#{list.name}] Test Mailing"
end
end
protected
# Response to a message posted to a list that doesn't exist
# pre: (TMail email)
def no_such_list(email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "Address does not exist at this server"
end
# Response to a message posted in reply to a tpoic that doesn't exist
# pre: (List list, Tmail email)
def no_such_topic(list, email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "[#{list.name}] The topic you referenced no longer exists"
body :list => list.name
end
# Response to a message sent to a noreply address
# pre: (Tmail email)
def no_reply_address(email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "Replies to this address are not monitored."
body "We're sorry, but the addresses noreply@#{ APP_CONFIG[:email_domain] } and mailer@#{ APP_CONFIG[:email_domain] }
are not monitored for replies. Your message has been discarded."
end
# Reponse to a message posted to a list by a non-member
# pre: (List list, Tmail email)
def cannot_post(list, email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "[#{list.name}] You're not allowed to post to this list"
body :list => list.name
end
# Send an e-mail out to a list
# pre: (Topic topic, Tmail email, Subscriber subscriber)
def to_mailing_list(topic, email, subscriber)
recipients subscriber.name + " <#{subscriber.email}>"
from "#{email.from} <mailer@#{ APP_CONFIG[:email_domain] }>"
reply_to "mailer@#{ APP_CONFIG[:email_domain] } <#{topic.list.short_name}+#{topic.key}+#{subscriber.public_key}@" +
APP_CONFIG[:email_domain] + ">"
subject "[#{topic.list.name}] #{email.subject}"
body email.body
headers 'List-ID' => "#{topic.list.short_name}@#{ APP_CONFIG[:email_domain]}",
'List-Post' => "#{topic.list.short_name}@#{ APP_CONFIG[:email_domain]}",
'List-Unsubscribe' => "http://#{ APP_CONFIG[:email_domain] }/list/#{ topic.list.id }/unsubscribe"
content_type "text/html"
end
end
Another fix
class Mailman < ActionMailer::Base
# bcc BCC addresses for the message
# body Define the body of the message. This is either a Hash
# (in which case it specifies the variables to pass to the template when it is rendered),
# or a string, in which case it specifies the actual text of the message.
# cc CC addresses for the message.
# charset Charset to use for the message. This defaults to the default_charset
# specified for ActionMailer::Base.
# content_type Content type for the message. This defaults to <text/plain in most cases,
# but can be automatically set in some situations.
# from From address for the message.
# reply_to Address (if different than the “from” address) to direct replies to this message.
# headers Additional headers to be added to the message.
# implicit_parts_order Specify the order in which parts should be sorted, based on content-type.
# This defaults to the value for the default_implicit_parts_order.
# mime_version Defaults to “1.0”, but may be explicitly given if needed.
# recipient The recipient addresses for the message, either as a string (for a single address)
# or an array (for multiple addresses).
# sent_on The date on which the message was sent. If not set (the default), the
# header will be set by the delivery agent.
# subject Specify the subject of the message.
# template Specify the template name to use for current message. This is the “base” template name,
# without the extension or directory, and may be used to have multiple mailer methods share
# the same template.
# Method for processing incoming messages
# pre: (Tmail email)
def receive(email)
# Extract out <list>+<thread>@<domain>
s_list, s_topic, s_domain =
email.to.first.match(/^(\w+)\+?([0-9a-e]*)\@([\w\.]+)$/).to_a[1..3]
# Don't storm if using BCC method with To: noreply
# TODO: remove
if(s_list == "mailer" || s_list == "noreply")
exit
end
# Make sure the list exists
unless(List.exists?(:short_name => s_list))
Mailman.deliver_no_such_list(email)
exit
end
list = List.find_by_short_name(s_list)
# Make sure they are in the list (allowed to post)
unless(list.subscribers.exists?(:email => email.from))
Mailman.deliver_cannot_post(list, email)
exit
end
# Check if this is a response to an existing topic or a new message
if(s_topic.length > 0)
unless(Topic.exists?(:key => s_topic))
Mailman.deliver_no_such_topic(list, email)
exit
end
topic = Topic.find_by_key(s_topic)
# Strip out the subject crap
# Can't use gsub! because subject isn't actually a string unless coerced
email.subject = email.subject.gsub(/\[#{list.short_name}\]/, "")
# Clean out RE and FW's
email.subject = email.subject.gsub(/([rR][eE]:\ *){2,}/, "RE: ")
else
topic = list.topics.create(
:name => email.subject
)
end
message = topic.messages.build(:subject => email.subject, :body => email.body)
message.author = Subscriber.find_by_email(email.from)
message.save
list.subscribers.each do |subscriber|
Mailman.deliver_to_mailing_list(topic, email, subscriber)
end
end
# Send a test e-mail to everyone on a given list
# pre: (List list)
def list_test_dispatch(list)
list.subscribers.each do |subscriber|
#recipients "noreply@" + APP_CONFIG[:email_domain]
recipients subscriber.name + " <#{subscriber.email}>"
#bcc list.subscribers.map(&:email)
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "[#{list.name}] Test Mailing"
end
end
protected
# Response to a message posted to a list that doesn't exist
# pre: (TMail email)
def no_such_list(email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "Address does not exist at this server"
end
# Response to a message posted in reply to a tpoic that doesn't exist
# pre: (List list, Tmail email)
def no_such_topic(list, email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "[#{list.name}] The topic you referenced no longer exists"
body :list => list.name
end
# Response to a message sent to a noreply address
# pre: (Tmail email)
def no_reply_address(email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "Replies to this address are not monitored."
body "We're sorry, but the addresses noreply@#{ APP_CONFIG[:email_domain] } and mailer@#{ APP_CONFIG[:email_domain] }
are not monitored for replies. Your message has been discarded."
end
# Reponse to a message posted to a list by a non-member
# pre: (List list, Tmail email)
def cannot_post(list, email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "[#{list.name}] You're not allowed to post to this list"
body :list => list.name
end
# Send an e-mail out to a list
# pre: (Topic topic, Tmail email, Subscriber subscriber)
def to_mailing_list(topic, email, subscriber)
recipients subscriber.name + " <#{subscriber.email}>"
from "#{email.from} <mailer@#{ APP_CONFIG[:email_domain] }>"
reply_to "mailer@#{ APP_CONFIG[:email_domain] } <#{topic.list.short_name}+#{topic.key}+#{subscriber.public_key}@" +
APP_CONFIG[:email_domain] + ">"
subject "[#{topic.list.name}] #{email.subject}"
body email.body
headers 'List-ID' => "#{topic.list.short_name}@#{ APP_CONFIG[:email_domain]}",
'List-Post' => "#{topic.list.short_name}@#{ APP_CONFIG[:email_domain]}",
'List-Unsubscribe' => "http://#{ APP_CONFIG[:email_domain] }/list/#{ topic.list.id }/unsubscribe"
content_type "text/html"
end
end
|
class Mailman < ActionMailer::Base
# bcc Specify the BCC addresses for the message
# body Define the body of the message. This is either a Hash
# (in which case it specifies the variables to pass to the template when it is rendered),
# or a string, in which case it specifies the actual text of the message.
# cc Specify the CC addresses for the message.
# charset Specify the charset to use for the message. This defaults to the default_charset specified for ActionMailer::Base.
# content_type Specify the content type for the message. This defaults to <text/plain in most cases,
# but can be automatically set in some situations.
# from Specify the from address for the message.
# reply_to Specify the address (if different than the “from” address) to direct replies to this message.
# headers Specify additional headers to be added to the message.
# implicit_parts_order Specify the order in which parts should be sorted, based on content-type.
# This defaults to the value for the default_implicit_parts_order.
# mime_version Defaults to “1.0”, but may be explicitly given if needed.
# recipient The recipient addresses for the message, either as a string (for a single address)
# or an array (for multiple addresses).
# sent_on The date on which the message was sent. If not set (the default), the
# header will be set by the delivery agent.
# subject Specify the subject of the message.
# template Specify the template name to use for current message. This is the “base” template name,
# without the extension or directory, and may be used to have multiple mailer methods share the same template.
# Method for processing incoming messages
# pre: (Tmail email)
def receive(email)
# TODO: clean up with regexp and logic
s_pre, s_domain = email.to.first.split(/\@/)
s_list, s_topic = s_pre.split(/\+/)
# Don't storm if using BCC method with To: noreply
# TODO: remove
if(s_list == "mailer" || s_list == "noreply")
exit
end
# Make sure the list exists
unless(List.exists?(:short_name => s_list))
Mailman.deliver_no_such_list(email)
exit
end
list = List.find_by_short_name(s_list)
# Add virtual fields for other functions to use
#email.list = list
# Make sure they are in the list (allowed to post)
unless(list.subscribers.exists?(:email => email.from))
Mailman.deliver_cannot_post(list, email)
exit
end
# Check if this is a response to an existing topic or a new message
if(s_pre =~ /\+/) then
unless(Topic.exists?(:key => s_topic)) then
Mailman.deliver_no_such_topic(list, email)
end
topic = Topic.find_by_key(s_topic)
# Strip out the subject crap
# Can't use gsub! because subject isn't actually a string unless coerced
email.subject = email.subject.gsub(/\[#{list.short_name}\]/, "")
# Clean out RE and FW's
email.subject = email.subject.gsub(/([rR][eE]:\ *){2,}/, "RE: ")
else
topic = list.topics.create(
:name => email.subject
)
end
# Add virtual fields for other functions to use
#email.topic = topic
message = topic.messages.build(:subject => email.subject, :body => email.body)
message.author = Subscriber.find_by_email(email.from)
message.save
list.subscribers.each do |subscriber|
Mailman.deliver_to_mailing_list(topic, email, subscriber)
end
end
# Send a test e-mail to everyone on a given list
# pre: (List list)
def list_test_dispatch(list)
list.subscribers.each do |subscriber|
#recipients "noreply@" + APP_CONFIG[:email_domain]
recipients subscriber.name + " <#{subscriber.email}>"
#bcc list.subscribers.map(&:email)
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "[#{list.name}] Test Mailing"
end
end
protected
# Response to a message posted to a list that doesn't exist
# pre: (TMail email)
def no_such_list(email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "Address does not exist at this server"
end
# Response to a message posted in reply to a tpoic that doesn't exist
# pre: (List list, Tmail email)
def no_such_topic(list, email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "[#{list.name} The topic you referenced no longer exists"
body :list => email.list.name
end
# Response to a message sent to a noreply address
# pre: (Tmail email)
def no_reply_address(email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "Replies to this address are not monitored."
body "We're sorry, but the addresses noreply@#{ APP_CONFIG[:email_domain] } and mailer@#{ APP_CONFIG[:email_domain] }
are not monitored for replies. Your message has been discarded."
end
# Reponse to a message posted to a list by a non-member
# pre: (List list, Tmail email)
def cannot_post(list, email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "[#{list.name}] You're not allowed to post to this list"
body :list => list.name
end
# Send an e-mail out to a list
# pre: (Topic topic, Tmail email, Subscriber subscriber)
def to_mailing_list(topic, email, subscriber)
recipients subscriber.name + " <#{subscriber.email}>"
from "#{email.from} <mailer@#{ APP_CONFIG[:email_domain] }>"
reply_to "mailer@#{ APP_CONFIG[:email_domain] } <#{topic.list.short_name}+#{topic.key}+#{subscriber.public_key}@" +
APP_CONFIG[:email_domain] + ">"
subject "[#{topic.list.name}] #{email.subject}"
body email.body
headers 'List-ID' => "#{topic.list.short_name}@#{ APP_CONFIG[:email_domain]}",
'List-Post' => "#{topic.list.short_name}@#{ APP_CONFIG[:email_domain]}",
'List-Unsubscribe' => "http://#{ APP_CONFIG[:email_domain] }/list/#{ topic.list.id }/unsubscribe"
content_type "text/html"
end
end
Replaced a simple two line mechanism with a complicated regular expression to save one variable name :)
class Mailman < ActionMailer::Base
# bcc Specify the BCC addresses for the message
# body Define the body of the message. This is either a Hash
# (in which case it specifies the variables to pass to the template when it is rendered),
# or a string, in which case it specifies the actual text of the message.
# cc Specify the CC addresses for the message.
# charset Specify the charset to use for the message. This defaults to the default_charset specified for ActionMailer::Base.
# content_type Specify the content type for the message. This defaults to <text/plain in most cases,
# but can be automatically set in some situations.
# from Specify the from address for the message.
# reply_to Specify the address (if different than the “from” address) to direct replies to this message.
# headers Specify additional headers to be added to the message.
# implicit_parts_order Specify the order in which parts should be sorted, based on content-type.
# This defaults to the value for the default_implicit_parts_order.
# mime_version Defaults to “1.0”, but may be explicitly given if needed.
# recipient The recipient addresses for the message, either as a string (for a single address)
# or an array (for multiple addresses).
# sent_on The date on which the message was sent. If not set (the default), the
# header will be set by the delivery agent.
# subject Specify the subject of the message.
# template Specify the template name to use for current message. This is the “base” template name,
# without the extension or directory, and may be used to have multiple mailer methods share the same template.
# Method for processing incoming messages
# pre: (Tmail email)
def receive(email)
# Extract out <list>+<thread>@<domain>
s_list, s_topic, s_domain =
email.to.first.match(/^(\w+)\+?([0-9a-e]*)\@([\w\.]+)$/).to_a[1..3]
# Don't storm if using BCC method with To: noreply
# TODO: remove
if(s_list == "mailer" || s_list == "noreply")
exit
end
# Make sure the list exists
unless(List.exists?(:short_name => s_list))
Mailman.deliver_no_such_list(email)
exit
end
list = List.find_by_short_name(s_list)
# Add virtual fields for other functions to use
#email.list = list
# Make sure they are in the list (allowed to post)
unless(list.subscribers.exists?(:email => email.from))
Mailman.deliver_cannot_post(list, email)
exit
end
# Check if this is a response to an existing topic or a new message
if(s_pre =~ /\+/) then
unless(Topic.exists?(:key => s_topic)) then
Mailman.deliver_no_such_topic(list, email)
end
topic = Topic.find_by_key(s_topic)
# Strip out the subject crap
# Can't use gsub! because subject isn't actually a string unless coerced
email.subject = email.subject.gsub(/\[#{list.short_name}\]/, "")
# Clean out RE and FW's
email.subject = email.subject.gsub(/([rR][eE]:\ *){2,}/, "RE: ")
else
topic = list.topics.create(
:name => email.subject
)
end
# Add virtual fields for other functions to use
#email.topic = topic
message = topic.messages.build(:subject => email.subject, :body => email.body)
message.author = Subscriber.find_by_email(email.from)
message.save
list.subscribers.each do |subscriber|
Mailman.deliver_to_mailing_list(topic, email, subscriber)
end
end
# Send a test e-mail to everyone on a given list
# pre: (List list)
def list_test_dispatch(list)
list.subscribers.each do |subscriber|
#recipients "noreply@" + APP_CONFIG[:email_domain]
recipients subscriber.name + " <#{subscriber.email}>"
#bcc list.subscribers.map(&:email)
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "[#{list.name}] Test Mailing"
end
end
protected
# Response to a message posted to a list that doesn't exist
# pre: (TMail email)
def no_such_list(email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "Address does not exist at this server"
end
# Response to a message posted in reply to a tpoic that doesn't exist
# pre: (List list, Tmail email)
def no_such_topic(list, email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "[#{list.name} The topic you referenced no longer exists"
body :list => email.list.name
end
# Response to a message sent to a noreply address
# pre: (Tmail email)
def no_reply_address(email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "Replies to this address are not monitored."
body "We're sorry, but the addresses noreply@#{ APP_CONFIG[:email_domain] } and mailer@#{ APP_CONFIG[:email_domain] }
are not monitored for replies. Your message has been discarded."
end
# Reponse to a message posted to a list by a non-member
# pre: (List list, Tmail email)
def cannot_post(list, email)
recipients email.from
from "#{ APP_CONFIG[:email_domain] } <mailer@#{ APP_CONFIG[:email_domain] }>"
subject "[#{list.name}] You're not allowed to post to this list"
body :list => list.name
end
# Send an e-mail out to a list
# pre: (Topic topic, Tmail email, Subscriber subscriber)
def to_mailing_list(topic, email, subscriber)
recipients subscriber.name + " <#{subscriber.email}>"
from "#{email.from} <mailer@#{ APP_CONFIG[:email_domain] }>"
reply_to "mailer@#{ APP_CONFIG[:email_domain] } <#{topic.list.short_name}+#{topic.key}+#{subscriber.public_key}@" +
APP_CONFIG[:email_domain] + ">"
subject "[#{topic.list.name}] #{email.subject}"
body email.body
headers 'List-ID' => "#{topic.list.short_name}@#{ APP_CONFIG[:email_domain]}",
'List-Post' => "#{topic.list.short_name}@#{ APP_CONFIG[:email_domain]}",
'List-Unsubscribe' => "http://#{ APP_CONFIG[:email_domain] }/list/#{ topic.list.id }/unsubscribe"
content_type "text/html"
end
end
|
class Message <ActiveRecord::Base
belongs_to :user
def sender
User.find(self.sender_id)
end
def recipe
Recipe.find(self.recipe_id)
end
def recipe_name_short
self.recipe.name.split.first(5).join(" ") + "..."
end
end
added validations to user_id, sender_id and content attributes
class Message <ActiveRecord::Base
belongs_to :user
validates_presence_of :user_id, on: :create
validates_presence_of :sender_id, on: :create
validates_presence_of :content, on: :create
def sender
User.find(self.sender_id)
end
def recipe
Recipe.find(self.recipe_id)
end
def recipe_name_short
self.recipe.name.split.first(5).join(" ") + "..."
end
end
|
class Message < ActiveRecord::Base
belongs_to :creator, class_name: "User"
belongs_to :recipient, class_name: "User"
end
modify message association due to change from polymorphic table
class Message < ActiveRecord::Base
belongs_to :creator, class_name: "User"
belongs_to :messageable, polymorphic: true
end
|
require 'rabl/renderer'
class Message
include AMQPConnector
include Mongoid::Document
include Mongoid::Timestamps
attr_accessor :client_id
belongs_to :author, class_name: "User", :validate => false
belongs_to :topic, polymorphic: true, :validate => false
field :content, type: String
field :device, type: String, default: 'desktop'
index({ _id: 1 }, { unique: true })
index({ topic_id: 1 })
index({ topic_type: 1 })
index({ author_id: 1 })
index({ created_at: 1 })
index({ updated_at: 1 })
validates :content, :presence => true
validates :author_id, :presence => true
def content=(msg)
msg.gsub! /[\u000d\u0009\u000c\u0085\u2028\u2029\n]/, "\\n"
msg.gsub! /<br\/><br\/>/,"\\n"
msg.gsub! /^\s*$/, ""
msg.gsub! /(https\:\/\/www.cloudsdale.org)/i, "http://www.cloudsdale.org"
if (m = msg.match(/^(.*)/i))
msg = m[0].gsub /([a-z]{1,6}\:\/\/)([a-z0-9\.\,\-\_\:]*)(\/?[a-z0-9\!\'\"\.\,\-\_\/\?\:\&\=\#\%\+\(\)]*)/i do
protocol = $1
top_dom = $2
path = $3
url = protocol + top_dom + path
self[:urls] ||= []
self[:urls] << url
url
end
end
if msg.present? && msg.length > 1000
self[:content] = msg[0..999] + "\\n\\n\\nMessage exceeded the 1000 character limit and has been trimmed..."
else
self[:content] = msg
end
end
# Deprecated Attributes
field :urls, type: Array, default: []
field :timestamp, type: Time, default: -> { Time.now }
has_and_belongs_to_many :drops, inverse_of: nil
default_scope -> { includes(:author,:drops) }
scope :old, -> { order_by([:timestamp,:desc]).skip(50) }
after_save :v1_publish
# Deprecated Methods
def utc_timestamp
self[:timestamp].utc
end
private
def v1_publish
rendered_content = Rabl.render(self, 'api/v1/messages/base', :view_path => 'app/views', :format => 'hash')
enqueue! "faye", { channel: "/#{self.topic_type.downcase}s/#{self.topic_id.to_s}/chat/messages", data: rendered_content }
end
end
Do not index _id
require 'rabl/renderer'
class Message
include AMQPConnector
include Mongoid::Document
include Mongoid::Timestamps
attr_accessor :client_id
belongs_to :author, class_name: "User", :validate => false
belongs_to :topic, polymorphic: true, :validate => false
field :content, type: String
field :device, type: String, default: 'desktop'
index({ topic_id: 1 })
index({ topic_type: 1 })
index({ author_id: 1 })
index({ created_at: 1 })
index({ updated_at: 1 })
validates :content, :presence => true
validates :author_id, :presence => true
def content=(msg)
msg.gsub! /[\u000d\u0009\u000c\u0085\u2028\u2029\n]/, "\\n"
msg.gsub! /<br\/><br\/>/,"\\n"
msg.gsub! /^\s*$/, ""
msg.gsub! /(https\:\/\/www.cloudsdale.org)/i, "http://www.cloudsdale.org"
if (m = msg.match(/^(.*)/i))
msg = m[0].gsub /([a-z]{1,6}\:\/\/)([a-z0-9\.\,\-\_\:]*)(\/?[a-z0-9\!\'\"\.\,\-\_\/\?\:\&\=\#\%\+\(\)]*)/i do
protocol = $1
top_dom = $2
path = $3
url = protocol + top_dom + path
self[:urls] ||= []
self[:urls] << url
url
end
end
if msg.present? && msg.length > 1000
self[:content] = msg[0..999] + "\\n\\n\\nMessage exceeded the 1000 character limit and has been trimmed..."
else
self[:content] = msg
end
end
# Deprecated Attributes
field :urls, type: Array, default: []
field :timestamp, type: Time, default: -> { Time.now }
has_and_belongs_to_many :drops, inverse_of: nil
default_scope -> { includes(:author,:drops) }
scope :old, -> { order_by([:timestamp,:desc]).skip(50) }
after_save :v1_publish
# Deprecated Methods
def utc_timestamp
self[:timestamp].utc
end
private
def v1_publish
rendered_content = Rabl.render(self, 'api/v1/messages/base', :view_path => 'app/views', :format => 'hash')
enqueue! "faye", { channel: "/#{self.topic_type.downcase}s/#{self.topic_id.to_s}/chat/messages", data: rendered_content }
end
end
|
class OscJob < ActiveRecord::Base
has_many :osc_job_jobs, dependent: :destroy
has_machete_workflow_of :osc_job_jobs
# Name that defines the template/target dirs
def staging_template_name
"osc_job"
end
# Define tasks to do after staging template directory typically copy over
# uploaded files here
# def after_stage(staged_dir)
# # CODE HERE
# end
# Build an array of Machete jobs that are then submitted to the batch server
def build_jobs(staged_dir, job_list = [])
job_list << OSC::Machete::Job.new(script: staged_dir.join("main.sh"))
end
# Make copy of workflow
def copy
self.dup
end
end
make the staging_template_dir the selected script dir
class OscJob < ActiveRecord::Base
has_many :osc_job_jobs, dependent: :destroy
has_machete_workflow_of :osc_job_jobs
# Name that defines the template/target dirs
def staging_template_name
"osc_job"
end
def staging_template_dir
File.dirname(self.script_path)
end
# Define tasks to do after staging template directory typically copy over
# uploaded files here
# def after_stage(staged_dir)
# # CODE HERE
# end
# Build an array of Machete jobs that are then submitted to the batch server
def build_jobs(staged_dir, job_list = [])
job_list << OSC::Machete::Job.new(script: staged_dir.join("main.sh"))
end
# Make copy of workflow
def copy
self.dup
end
end
|
create product model
class Product < ActiveRecord::Base
has_many :cart_ids
has_many :users, through :cart_ids
validates :name, presence: true
validates :price, presence: true
end |
require 'money'
require './lib/poster_image'
require 'elasticsearch/model'
class Product < ActiveRecord::Base
include Kaminari::ActiveRecordModelExtension
include Elasticsearch::Model
include GlobalID::Identification
include Workflow
DEFAULT_BOUNTY_SIZE=10000
PITCH_WEEK_REQUIRED_BUILDERS=10
DEFAULT_IMAGE_PATH='/assets/app_icon.png'
MARK_SEARCH_THRESHOLD=0.10
extend FriendlyId
friendly_id :slug_candidates, use: :slugged
attr_encryptor :wallet_private_key, :key => ENV["PRODUCT_ENCRYPTION_KEY"], :encode => true, :mode => :per_attribute_iv_and_salt, :unless => Rails.env.test?
attr_accessor :partner_ids
belongs_to :user
belongs_to :evaluator, class_name: 'User'
belongs_to :main_thread, class_name: 'Discussion'
belongs_to :logo, class_name: 'Asset', foreign_key: 'logo_id'
has_one :coin_info
has_one :idea
has_one :product_trend
has_many :activities
has_many :assets
has_many :auto_tip_contracts
has_many :chat_rooms
has_many :contract_holders
has_many :core_team, through: :core_team_memberships, source: :user
has_many :core_team_memberships, -> { where(is_core: true) }, class_name: 'TeamMembership'
has_many :daily_metrics
has_many :discussions
has_many :domains
has_many :event_activities, through: :events, source: :activities
has_many :events, :through => :wips
has_many :expense_claims
has_many :financial_accounts, class_name: 'Financial::Account'
has_many :financial_transactions, class_name: 'Financial::Transaction'
has_many :integrations
has_many :invites, as: :via
has_many :markings, as: :markable
has_many :marks, through: :markings
has_many :milestones
has_many :monthly_metrics
has_many :news_feed_items
has_many :news_feed_item_posts
has_many :pitch_week_applications
has_many :posts
has_many :profit_reports
has_many :proposals
has_many :rooms
has_many :screenshots, through: :assets
has_many :showcase_entries
has_many :showcases, through: :showcase_entries
has_many :status_messages
has_many :stream_events
has_many :subscribers
has_many :tasks
has_many :team_memberships
has_many :transaction_log_entries
has_many :viewings, as: :viewable
has_many :votes, as: :voteable
has_many :watchers, through: :watchings, source: :user
has_many :watchings, as: :watchable
has_many :weekly_metrics
has_many :wip_activities, through: :wips, source: :activities
has_many :wips
has_many :work
has_many :ownership_statuses
PRIVATE = ((ENV['PRIVATE_PRODUCTS'] || '').split(','))
def self.private_ids
@private_ids ||= (PRIVATE.any? ? Product.where(slug: PRIVATE).pluck(:id) : [])
end
def self.meta_id
@meta_id ||= Product.find_by(slug: 'meta').try(:id)
end
default_scope -> { where(deleted_at: nil) }
scope :featured, -> {
where.not(featured_on: nil).order(featured_on: :desc)
}
scope :created_in_month, ->(date) {
where('date(products.created_at) >= ? and date(products.created_at) < ?',
date.beginning_of_month, date.beginning_of_month + 1.month
)
}
scope :created_in_week, ->(date) {
where('date(products.created_at) >= ? and date(products.created_at) < ?',
date.beginning_of_week, date.beginning_of_week + 1.week
)
}
scope :greenlit, -> { public_products.where(state: 'greenlit') }
scope :latest, -> { where(flagged_at: nil).order(updated_at: :desc)}
scope :live, -> { where.not(try_url: [nil, '']) }
scope :no_meta, -> { where.not(id: self.meta_id) }
scope :ordered_by_trend, -> { joins(:product_trend).order('product_trends.score DESC') }
scope :profitable, -> { public_products.where(state: 'profitable') }
scope :public_products, -> { where.not(id: Product.private_ids).where(flagged_at: nil).where.not(state: ['stealth', 'reviewing']) }
scope :repos_gt, ->(count) { where('array_length(repos,1) > ?', count) }
scope :since, ->(time) { where('created_at >= ?', time) }
scope :stealth, -> { where(state: 'stealth') }
scope :tagged_with_any, ->(tags) { where('tags && ARRAY[?]::varchar[]', tags) }
scope :team_building, -> { public_products.where(state: 'team_building') }
scope :untagged, -> { where('array_length(tags, 1) IS NULL') }
scope :validating, -> { where(greenlit_at: nil) }
scope :visible_to, ->(user) { user.nil? ? public_products : where.not(id: Product.private_ids).where(flagged_at: nil) }
scope :waiting_approval, -> { where('submitted_at is not null and evaluated_at is null') }
scope :with_repo, ->(repo) { where('? = ANY(repos)', repo) }
scope :with_logo, ->{ where.not(poster: nil).where.not(poster: '') }
scope :with_mark, -> (name) { joins(:marks).where(marks: { name: name }) }
scope :with_topic, -> (topic) { where('topics @> ARRAY[?]::varchar[]', topic) }
EXCLUSIONS = %w(admin about core hello ideas if owner product script start-conversation)
validates :slug, uniqueness: { allow_nil: true },
exclusion: { in: EXCLUSIONS }
validates :name, presence: true,
length: { minimum: 2, maximum: 255 },
exclusion: { in: EXCLUSIONS }
validates :pitch, presence: true,
length: { maximum: 255 }
before_create :generate_authentication_token
before_validation :generate_asmlytics_key, on: :create
after_commit :retrieve_key_pair, on: :create
after_commit -> { add_to_event_stream }, on: :create
after_commit -> { Indexer.perform_async(:index, Product.to_s, self.id) }, on: :create
after_commit -> { CoinInfo.create_from_product!(self) }, on: :create
after_update :update_elasticsearch
serialize :repos, Repo::Github
INITIAL_COINS = 6000
NON_PROFIT = %w(meta)
INFO_FIELDS = %w(goals key_features target_audience competing_products competitive_advantage monetization_strategy)
store_accessor :info, *INFO_FIELDS.map(&:to_sym)
workflow_column :state
workflow do
state :stealth do
event :submit,
transitions_to: :reviewing
end
state :reviewing do
event :accept,
transitions_to: :team_building
event :reject,
transitions_to: :stealth
end
state :team_building do
event :greenlight,
transitions_to: :greenlit
event :reject,
transitions_to: :stealth
end
state :greenlit do
event :launch,
transitions_to: :profitable
event :remove,
transitions_to: :stealth
end
state :profitable do
event :remove, transitions_to: :stealth end
end
def self.unique_tags
pluck('distinct unnest(tags)').sort_by{|t| t.downcase }
end
def self.active_product_count
joins(:activities).where('activities.created_at > ?', 30.days.ago).group('products.id').having('count(*) > 5').count.count
end
def sum_viewings
Viewing.where(viewable: self).count
end
def most_active_contributor_ids(limit=6)
activities.group('actor_id').order('count_id desc').limit(limit).count('id').keys
end
def most_active_contributors(limit=6)
User.where(id: most_active_contributor_ids(limit))
end
def on_stealth_entry(prev_state, event, *args)
update!(
started_team_building_at: nil,
greenlit_at: nil,
profitable_at: nil
)
end
def on_team_building_entry(prev_state, event, *args)
update!(
started_team_building_at: Time.now,
greenlit_at: nil,
profitable_at: nil
)
end
def on_greenlit_entry(prev_state, event, *args)
update!(
greenlit_at: Time.now,
profitable_at: nil
)
AssemblyCoin::GreenlightProduct.new.perform(self.id)
end
def on_profitable_entry(prev_state, event, *args)
update!(profitable_at: Time.now)
end
def public?
self.flagged_at.nil? &&
!Product.private_ids.include?(self.id) &&
!%w(stealth reviewing).include?(self.state)
end
def wallet_private_key_salt
# http://ruby-doc.org/stdlib-2.1.0/libdoc/openssl/rdoc/OpenSSL/Cipher.html#class-OpenSSL::Cipher-label-Encrypting+and+decrypting+some+data
cipher = OpenSSL::Cipher::AES256.new(:CBC)
cipher.encrypt
cipher.random_key
end
def partners(limit=nil)
TransactionLogEntry.product_partners(self.id).order('sum(cents) desc').limit(limit)
end
def distinct_wallets_unqueued
TransactionLogEntry.product_partners_with_balances_unqueued(self.id)
end
def mark_all_transactions_as_queued
TransactionLogEntry.where(product_id: self.id).where(queue_id: nil).all.each do |a|
a.update!({queue_id: Time.now.to_s})
end
end
def reset_all_transactions_as_unqueued #dont run this command without consulting a lvl 5 wizard or above
TransactionLogEntry.where(product_id: self.id).where.not(queue_id: nil).all.each do |a|
a.update!({queue_id: nil})
end
end
def launched?
current_state >= :team_building
end
def stopped_team_building_at
started_team_building_at + 30.days
end
def team_building_days_left
[(stopped_team_building_at.to_date - Date.today).to_i, 1].max
end
def team_building_percentage
[product.bio_memberships_count, 10].min * 10
end
def founded_at
read_attribute(:founded_at) || created_at
end
def public_at
read_attribute(:public_at) || created_at
end
def for_profit?
not NON_PROFIT.include?(slug)
end
def partners_before_date(date)
partners.where('tle.created_at < ?', date)
end
def partner_ids
partners.pluck(:id)
end
def has_metrics?
for_profit?
end
def contributors(limit=10)
User.where(id: (contributor_ids | [user_id])).take(limit)
end
def contributor_ids
wip_creator_ids | event_creator_ids
end
def contributors_with_no_activity_since(since)
contributors.select do |contributor|
contributor.last_contribution.created_at < since
end
end
def core_team?(user)
return false if user.nil?
team_memberships.core_team.active.find_by(user_id: user.id).present?
end
def member?(user)
return false if user.nil?
team_memberships.active.find_by(user_id: user.id)
end
def partner?(user)
return false if user.nil?
partners.where(id: user.id).exists?
end
def finished_first_steps?
posts.exists? && tasks.count >= 3 && repos.present?
end
def awaiting_approval?
pitch_week_applications.to_review.exists?
end
def open_discussions?
discussions.where(closed_at: nil).exists?
end
def open_discussions_count
discussions.where(closed_at: nil).count
end
def open_tasks?
wips.where(closed_at: nil).exists?
end
def revenue?
profit_reports.any?
end
def open_tasks_count
tasks.where(closed_at: nil).count
end
def voted_for_by?(user)
user && user.voted_for?(self)
end
def number_of_code_tasks
number_of_open_tasks(:code)
end
def number_of_design_tasks
number_of_open_tasks(:design)
end
def number_of_copy_tasks
number_of_open_tasks(:copy)
end
def number_of_other_tasks
number_of_open_tasks(:other)
end
def number_of_open_tasks(deliverable_type)
tasks.where(state: 'open', deliverable: deliverable_type).count
end
def count_contributors
(wip_creator_ids | event_creator_ids).size
end
def love
end
def event_creator_ids
::Event.joins(:wip).where('wips.product_id = ?', self.id).group('events.user_id').count.keys
end
def wip_creator_ids
Wip.where('wips.product_id = ?', self.id).group('wips.user_id').count.keys
end
def submitted?
!!submitted_at
end
def greenlit?
!greenlit_at.nil?
end
def flagged?
!flagged_at.nil?
end
def feature!
touch(:featured_on)
end
def main_chat_room
chat_rooms.first || ChatRoom.general
end
def count_presignups
votes.select(:user_id).distinct.count
end
def slug_candidates
[
:name,
[:creator_username, :name],
]
end
def creator_username
user.username
end
def voted_by?(user)
votes.where(user: user).any?
end
def combined_watchers_and_voters
(votes.map {|vote| vote.user } + watchers).uniq
end
def asset_address
self.coin_info.asset_address
end
def set_asset_address
a = OpenAssets::Transactions.new.get_asset_address(self.wallet_public_address)
self.coin_info.update!({asset_address: a['asset_address']})
end
def assign_asset_address
if self.coin_info
if !self.coin_info.asset_address
set_asset_address
else
if self.coin_info.asset_address.length < 10
set_asset_address
end
end
end
end
def tags_with_count
Wip::Tag.joins(:taggings => :wip).
where('wips.closed_at is null').
where('wips.product_id' => self.id).
group('wip_tags.id').
order('count(*) desc').
count('*').map do |tag_id, count|
[Wip::Tag.find(tag_id), count]
end
end
def to_param
slug || id
end
# following
def watch!(user)
transaction do
Watching.watch!(user, self)
Subscriber.unsubscribe!(self, user)
end
end
# not following, will receive announcements
def announcements!(user)
transaction do
Watching.unwatch!(user, self)
Subscriber.upsert!(self, user)
end
end
# not following
def unwatch!(user)
transaction do
Watching.unwatch!(user, self)
Subscriber.unsubscribe!(self, user)
end
end
def visible_watchers
system_user_ids = User.where(username: 'kernel').pluck(:id)
watchers.where.not(id: system_user_ids)
end
# only people following the product, ie. excludes people on announcements only
def followers
watchers
end
def follower_ids
watchings.pluck(:user_id)
end
def followed_by?(user)
Watching.following?(user, self)
end
def auto_watch!(user)
Watching.auto_watch!(user, self)
end
def watching?(user)
Watching.watched?(user, self)
end
def poster_image
self.logo || PosterImage.new(self)
end
def logo_url
if logo
logo.url
elsif poster
poster_image.url
else
DEFAULT_IMAGE_PATH
end
end
def generate_authentication_token
loop do
self.authentication_token = Devise.friendly_token
break authentication_token unless Product.find_by(authentication_token: authentication_token)
end
end
def generate_asmlytics_key
self.asmlytics_key = Digest::SHA1.hexdigest(ENV['ASMLYTICS_SECRET'].to_s + SecureRandom.uuid)
end
def product
self
end
def average_bounty
bounties = TransactionLogEntry.bounty_values_on_product(product)
return DEFAULT_BOUNTY_SIZE if bounties.none?
bounties.inject(0, &:+) / bounties.size
end
def coins_minted
transaction_log_entries.with_cents.sum(:cents)
end
def profit_last_month
last_report = profit_reports.order('end_at DESC').first
(last_report && last_report.profit) || 0
end
def ownership
ProductOwnership.new(self)
end
def update_partners_count_cache
self.partners_count = ownership.user_cents.size
end
def update_watchings_count!
update! watchings_count: (subscribers.count + followers.count)
end
def tags_string
tags.join(', ')
end
def tags_string=(new_tags_string)
self.tags = new_tags_string.split(',').map(&:strip)
end
def topic=(new_topic)
self.topics = [new_topic]
end
def showcase=(showcase_slug)
Showcase.find_by!(slug: showcase_slug).add!(self)
end
def assembly?
slug == 'asm'
end
def meta?
slug == 'meta'
end
def draft?
self.description.blank? && (self.info || {}).values.all?(&:blank?)
end
def bounty_postings
BountyPosting.joins(:bounty).where('wips.product_id = ?', id)
end
# elasticsearch
def update_elasticsearch
return unless (['name', 'pitch', 'description'] - self.changed).any?
Indexer.perform_async(:index, Product.to_s, self.id)
end
mappings do
indexes :name, type: 'multi_field' do
indexes :name
indexes :raw, analyzer: 'keyword'
end
indexes :pitch, analyzer: 'snowball'
indexes :description, analyzer: 'snowball'
indexes :tech, analyzer: 'keyword'
indexes :marks do
indexes :name
indexes :weight, type: 'float'
end
indexes :suggest, type: 'completion', payloads: true, index_analyzer: 'simple', search_analyzer: 'simple'
end
def as_indexed_json(options={})
as_json(
root: false,
only: [:slug, :name, :pitch, :poster],
methods: [:tech, :hidden, :sanitized_description, :suggest, :trend_score]
).merge(marks: mark_weights, logo_url: full_logo_url, search_tags: tags)
end
def mark_weights
markings.sort_by{|marking| -marking.weight }.
take(5).
map{|marking| { weight: marking.weight, name: marking.mark.name } }
end
def trend_score
product_trend.try(:score).to_i
end
def suggest
{
input: [name, pitch] + name.split(' ') + pitch.split(' '),
output: id,
weight: trend_score,
payload: {
id: id,
slug: slug,
name: name,
pitch: pitch,
logo_url: full_logo_url,
}
}
end
def full_logo_url
# this is a hack to get a full url into elasticsearch, so firesize can resize it correctly.
# DEFAULT_IMAGE_PATH is a relative image path
logo_url == DEFAULT_IMAGE_PATH ? File.join(Rails.application.routes.url_helpers.root_url, DEFAULT_IMAGE_PATH) : logo_url
end
def tech
Search::TechFilter.matching(tags).map(&:slug)
end
def poster_image_url
unless self.logo.nil?
self.logo.url
else
PosterImage.new(self).url
end
end
def hidden
PRIVATE.include?(slug) || flagged?
end
def flagged?
!!flagged_at
end
def sanitized_description
description && Search::Sanitizer.new.sanitize(description)
end
# pusher
def push_channel
slug
end
def retrieve_key_pair
AssemblyCoin::AssignBitcoinKeyPairWorker.perform_async(
self.to_global_id,
:assign_key_pair
)
end
def assign_key_pair(key_pair)
update!(
wallet_public_address: key_pair["public_address"],
wallet_private_key: key_pair["private_key"]
)
end
def unvested_coins
unvested = 10_000_000 - transaction_log_entries.sum(:cents)
if unvested < 0
unvested = 0
end
unvested
end
def mark_vector
my_mark_vector = QueryMarks.new.mark_vector_for_object(self)
end
def normalized_mark_vector()
QueryMarks.new.normalize_mark_vector(self.mark_vector())
end
def majority_owner
total_coins = TransactionLogEntry.where(product: self).sum(:cents)
majority_owner = TransactionLogEntry.where(product: self).group('wallet_id').sum(:cents).sort_by{|k,v| -v}.first
majority_owner[1].to_f / total_coins.to_f >= 0.5
end
def try_url=(new_try_url)
super(new_try_url.presence)
end
protected
def add_to_event_stream
StreamEvent.add_create_event!(actor: user, subject: self)
end
end
fixed missing product id
require 'money'
require './lib/poster_image'
require 'elasticsearch/model'
class Product < ActiveRecord::Base
include ActiveRecord::UUID
include Kaminari::ActiveRecordModelExtension
include Elasticsearch::Model
include GlobalID::Identification
include Workflow
DEFAULT_BOUNTY_SIZE=10000
PITCH_WEEK_REQUIRED_BUILDERS=10
DEFAULT_IMAGE_PATH='/assets/app_icon.png'
MARK_SEARCH_THRESHOLD=0.10
extend FriendlyId
friendly_id :slug_candidates, use: :slugged
attr_encryptor :wallet_private_key, :key => ENV["PRODUCT_ENCRYPTION_KEY"], :encode => true, :mode => :per_attribute_iv_and_salt, :unless => Rails.env.test?
attr_accessor :partner_ids
belongs_to :user
belongs_to :evaluator, class_name: 'User'
belongs_to :main_thread, class_name: 'Discussion'
belongs_to :logo, class_name: 'Asset', foreign_key: 'logo_id'
has_one :coin_info
has_one :idea
has_one :product_trend
has_many :activities
has_many :assets
has_many :auto_tip_contracts
has_many :chat_rooms
has_many :contract_holders
has_many :core_team, through: :core_team_memberships, source: :user
has_many :core_team_memberships, -> { where(is_core: true) }, class_name: 'TeamMembership'
has_many :daily_metrics
has_many :discussions
has_many :domains
has_many :event_activities, through: :events, source: :activities
has_many :events, :through => :wips
has_many :expense_claims
has_many :financial_accounts, class_name: 'Financial::Account'
has_many :financial_transactions, class_name: 'Financial::Transaction'
has_many :integrations
has_many :invites, as: :via
has_many :markings, as: :markable
has_many :marks, through: :markings
has_many :milestones
has_many :monthly_metrics
has_many :news_feed_items
has_many :news_feed_item_posts
has_many :pitch_week_applications
has_many :posts
has_many :profit_reports
has_many :proposals
has_many :rooms
has_many :screenshots, through: :assets
has_many :showcase_entries
has_many :showcases, through: :showcase_entries
has_many :status_messages
has_many :stream_events
has_many :subscribers
has_many :tasks
has_many :team_memberships
has_many :transaction_log_entries
has_many :viewings, as: :viewable
has_many :votes, as: :voteable
has_many :watchers, through: :watchings, source: :user
has_many :watchings, as: :watchable
has_many :weekly_metrics
has_many :wip_activities, through: :wips, source: :activities
has_many :wips
has_many :work
has_many :ownership_statuses
PRIVATE = ((ENV['PRIVATE_PRODUCTS'] || '').split(','))
def self.private_ids
@private_ids ||= (PRIVATE.any? ? Product.where(slug: PRIVATE).pluck(:id) : [])
end
def self.meta_id
@meta_id ||= Product.find_by(slug: 'meta').try(:id)
end
default_scope -> { where(deleted_at: nil) }
scope :featured, -> {
where.not(featured_on: nil).order(featured_on: :desc)
}
scope :created_in_month, ->(date) {
where('date(products.created_at) >= ? and date(products.created_at) < ?',
date.beginning_of_month, date.beginning_of_month + 1.month
)
}
scope :created_in_week, ->(date) {
where('date(products.created_at) >= ? and date(products.created_at) < ?',
date.beginning_of_week, date.beginning_of_week + 1.week
)
}
scope :greenlit, -> { public_products.where(state: 'greenlit') }
scope :latest, -> { where(flagged_at: nil).order(updated_at: :desc)}
scope :live, -> { where.not(try_url: [nil, '']) }
scope :no_meta, -> { where.not(id: self.meta_id) }
scope :ordered_by_trend, -> { joins(:product_trend).order('product_trends.score DESC') }
scope :profitable, -> { public_products.where(state: 'profitable') }
scope :public_products, -> { where.not(id: Product.private_ids).where(flagged_at: nil).where.not(state: ['stealth', 'reviewing']) }
scope :repos_gt, ->(count) { where('array_length(repos,1) > ?', count) }
scope :since, ->(time) { where('created_at >= ?', time) }
scope :stealth, -> { where(state: 'stealth') }
scope :tagged_with_any, ->(tags) { where('tags && ARRAY[?]::varchar[]', tags) }
scope :team_building, -> { public_products.where(state: 'team_building') }
scope :untagged, -> { where('array_length(tags, 1) IS NULL') }
scope :validating, -> { where(greenlit_at: nil) }
scope :visible_to, ->(user) { user.nil? ? public_products : where.not(id: Product.private_ids).where(flagged_at: nil) }
scope :waiting_approval, -> { where('submitted_at is not null and evaluated_at is null') }
scope :with_repo, ->(repo) { where('? = ANY(repos)', repo) }
scope :with_logo, ->{ where.not(poster: nil).where.not(poster: '') }
scope :with_mark, -> (name) { joins(:marks).where(marks: { name: name }) }
scope :with_topic, -> (topic) { where('topics @> ARRAY[?]::varchar[]', topic) }
EXCLUSIONS = %w(admin about core hello ideas if owner product script start-conversation)
validates :slug, uniqueness: { allow_nil: true },
exclusion: { in: EXCLUSIONS }
validates :name, presence: true,
length: { minimum: 2, maximum: 255 },
exclusion: { in: EXCLUSIONS }
validates :pitch, presence: true,
length: { maximum: 255 }
before_create :generate_authentication_token
before_validation :generate_asmlytics_key, on: :create
after_commit :retrieve_key_pair, on: :create
after_commit -> { add_to_event_stream }, on: :create
after_commit -> { Indexer.perform_async(:index, Product.to_s, self.id) }, on: :create
after_commit -> { CoinInfo.create_from_product!(self) }, on: :create
after_update :update_elasticsearch
serialize :repos, Repo::Github
INITIAL_COINS = 6000
NON_PROFIT = %w(meta)
INFO_FIELDS = %w(goals key_features target_audience competing_products competitive_advantage monetization_strategy)
store_accessor :info, *INFO_FIELDS.map(&:to_sym)
workflow_column :state
workflow do
state :stealth do
event :submit,
transitions_to: :reviewing
end
state :reviewing do
event :accept,
transitions_to: :team_building
event :reject,
transitions_to: :stealth
end
state :team_building do
event :greenlight,
transitions_to: :greenlit
event :reject,
transitions_to: :stealth
end
state :greenlit do
event :launch,
transitions_to: :profitable
event :remove,
transitions_to: :stealth
end
state :profitable do
event :remove, transitions_to: :stealth end
end
def self.unique_tags
pluck('distinct unnest(tags)').sort_by{|t| t.downcase }
end
def self.active_product_count
joins(:activities).where('activities.created_at > ?', 30.days.ago).group('products.id').having('count(*) > 5').count.count
end
def sum_viewings
Viewing.where(viewable: self).count
end
def most_active_contributor_ids(limit=6)
activities.group('actor_id').order('count_id desc').limit(limit).count('id').keys
end
def most_active_contributors(limit=6)
User.where(id: most_active_contributor_ids(limit))
end
def on_stealth_entry(prev_state, event, *args)
update!(
started_team_building_at: nil,
greenlit_at: nil,
profitable_at: nil
)
end
def on_team_building_entry(prev_state, event, *args)
update!(
started_team_building_at: Time.now,
greenlit_at: nil,
profitable_at: nil
)
end
def on_greenlit_entry(prev_state, event, *args)
update!(
greenlit_at: Time.now,
profitable_at: nil
)
AssemblyCoin::GreenlightProduct.new.perform(self.id)
end
def on_profitable_entry(prev_state, event, *args)
update!(profitable_at: Time.now)
end
def public?
self.flagged_at.nil? &&
!Product.private_ids.include?(self.id) &&
!%w(stealth reviewing).include?(self.state)
end
def wallet_private_key_salt
# http://ruby-doc.org/stdlib-2.1.0/libdoc/openssl/rdoc/OpenSSL/Cipher.html#class-OpenSSL::Cipher-label-Encrypting+and+decrypting+some+data
cipher = OpenSSL::Cipher::AES256.new(:CBC)
cipher.encrypt
cipher.random_key
end
def partners(limit=nil)
TransactionLogEntry.product_partners(self.id).order('sum(cents) desc').limit(limit)
end
def distinct_wallets_unqueued
TransactionLogEntry.product_partners_with_balances_unqueued(self.id)
end
def mark_all_transactions_as_queued
TransactionLogEntry.where(product_id: self.id).where(queue_id: nil).all.each do |a|
a.update!({queue_id: Time.now.to_s})
end
end
def reset_all_transactions_as_unqueued #dont run this command without consulting a lvl 5 wizard or above
TransactionLogEntry.where(product_id: self.id).where.not(queue_id: nil).all.each do |a|
a.update!({queue_id: nil})
end
end
def launched?
current_state >= :team_building
end
def stopped_team_building_at
started_team_building_at + 30.days
end
def team_building_days_left
[(stopped_team_building_at.to_date - Date.today).to_i, 1].max
end
def team_building_percentage
[product.bio_memberships_count, 10].min * 10
end
def founded_at
read_attribute(:founded_at) || created_at
end
def public_at
read_attribute(:public_at) || created_at
end
def for_profit?
not NON_PROFIT.include?(slug)
end
def partners_before_date(date)
partners.where('tle.created_at < ?', date)
end
def partner_ids
partners.pluck(:id)
end
def has_metrics?
for_profit?
end
def contributors(limit=10)
User.where(id: (contributor_ids | [user_id])).take(limit)
end
def contributor_ids
wip_creator_ids | event_creator_ids
end
def contributors_with_no_activity_since(since)
contributors.select do |contributor|
contributor.last_contribution.created_at < since
end
end
def core_team?(user)
return false if user.nil?
team_memberships.core_team.active.find_by(user_id: user.id).present?
end
def member?(user)
return false if user.nil?
team_memberships.active.find_by(user_id: user.id)
end
def partner?(user)
return false if user.nil?
partners.where(id: user.id).exists?
end
def finished_first_steps?
posts.exists? && tasks.count >= 3 && repos.present?
end
def awaiting_approval?
pitch_week_applications.to_review.exists?
end
def open_discussions?
discussions.where(closed_at: nil).exists?
end
def open_discussions_count
discussions.where(closed_at: nil).count
end
def open_tasks?
wips.where(closed_at: nil).exists?
end
def revenue?
profit_reports.any?
end
def open_tasks_count
tasks.where(closed_at: nil).count
end
def voted_for_by?(user)
user && user.voted_for?(self)
end
def number_of_code_tasks
number_of_open_tasks(:code)
end
def number_of_design_tasks
number_of_open_tasks(:design)
end
def number_of_copy_tasks
number_of_open_tasks(:copy)
end
def number_of_other_tasks
number_of_open_tasks(:other)
end
def number_of_open_tasks(deliverable_type)
tasks.where(state: 'open', deliverable: deliverable_type).count
end
def count_contributors
(wip_creator_ids | event_creator_ids).size
end
def love
end
def event_creator_ids
::Event.joins(:wip).where('wips.product_id = ?', self.id).group('events.user_id').count.keys
end
def wip_creator_ids
Wip.where('wips.product_id = ?', self.id).group('wips.user_id').count.keys
end
def submitted?
!!submitted_at
end
def greenlit?
!greenlit_at.nil?
end
def flagged?
!flagged_at.nil?
end
def feature!
touch(:featured_on)
end
def main_chat_room
chat_rooms.first || ChatRoom.general
end
def count_presignups
votes.select(:user_id).distinct.count
end
def slug_candidates
[
:name,
[:creator_username, :name],
]
end
def creator_username
user.username
end
def voted_by?(user)
votes.where(user: user).any?
end
def combined_watchers_and_voters
(votes.map {|vote| vote.user } + watchers).uniq
end
def asset_address
self.coin_info.asset_address
end
def set_asset_address
a = OpenAssets::Transactions.new.get_asset_address(self.wallet_public_address)
self.coin_info.update!({asset_address: a['asset_address']})
end
def assign_asset_address
if self.coin_info
if !self.coin_info.asset_address
set_asset_address
else
if self.coin_info.asset_address.length < 10
set_asset_address
end
end
end
end
def tags_with_count
Wip::Tag.joins(:taggings => :wip).
where('wips.closed_at is null').
where('wips.product_id' => self.id).
group('wip_tags.id').
order('count(*) desc').
count('*').map do |tag_id, count|
[Wip::Tag.find(tag_id), count]
end
end
def to_param
slug || id
end
# following
def watch!(user)
transaction do
Watching.watch!(user, self)
Subscriber.unsubscribe!(self, user)
end
end
# not following, will receive announcements
def announcements!(user)
transaction do
Watching.unwatch!(user, self)
Subscriber.upsert!(self, user)
end
end
# not following
def unwatch!(user)
transaction do
Watching.unwatch!(user, self)
Subscriber.unsubscribe!(self, user)
end
end
def visible_watchers
system_user_ids = User.where(username: 'kernel').pluck(:id)
watchers.where.not(id: system_user_ids)
end
# only people following the product, ie. excludes people on announcements only
def followers
watchers
end
def follower_ids
watchings.pluck(:user_id)
end
def followed_by?(user)
Watching.following?(user, self)
end
def auto_watch!(user)
Watching.auto_watch!(user, self)
end
def watching?(user)
Watching.watched?(user, self)
end
def poster_image
self.logo || PosterImage.new(self)
end
def logo_url
if logo
logo.url
elsif poster
poster_image.url
else
DEFAULT_IMAGE_PATH
end
end
def generate_authentication_token
loop do
self.authentication_token = Devise.friendly_token
break authentication_token unless Product.find_by(authentication_token: authentication_token)
end
end
def generate_asmlytics_key
self.asmlytics_key = Digest::SHA1.hexdigest(ENV['ASMLYTICS_SECRET'].to_s + SecureRandom.uuid)
end
def product
self
end
def average_bounty
bounties = TransactionLogEntry.bounty_values_on_product(product)
return DEFAULT_BOUNTY_SIZE if bounties.none?
bounties.inject(0, &:+) / bounties.size
end
def coins_minted
transaction_log_entries.with_cents.sum(:cents)
end
def profit_last_month
last_report = profit_reports.order('end_at DESC').first
(last_report && last_report.profit) || 0
end
def ownership
ProductOwnership.new(self)
end
def update_partners_count_cache
self.partners_count = ownership.user_cents.size
end
def update_watchings_count!
update! watchings_count: (subscribers.count + followers.count)
end
def tags_string
tags.join(', ')
end
def tags_string=(new_tags_string)
self.tags = new_tags_string.split(',').map(&:strip)
end
def topic=(new_topic)
self.topics = [new_topic]
end
def showcase=(showcase_slug)
Showcase.find_by!(slug: showcase_slug).add!(self)
end
def assembly?
slug == 'asm'
end
def meta?
slug == 'meta'
end
def draft?
self.description.blank? && (self.info || {}).values.all?(&:blank?)
end
def bounty_postings
BountyPosting.joins(:bounty).where('wips.product_id = ?', id)
end
# elasticsearch
def update_elasticsearch
return unless (['name', 'pitch', 'description'] - self.changed).any?
Indexer.perform_async(:index, Product.to_s, self.id)
end
mappings do
indexes :name, type: 'multi_field' do
indexes :name
indexes :raw, analyzer: 'keyword'
end
indexes :pitch, analyzer: 'snowball'
indexes :description, analyzer: 'snowball'
indexes :tech, analyzer: 'keyword'
indexes :marks do
indexes :name
indexes :weight, type: 'float'
end
indexes :suggest, type: 'completion', payloads: true, index_analyzer: 'simple', search_analyzer: 'simple'
end
def as_indexed_json(options={})
as_json(
root: false,
only: [:slug, :name, :pitch, :poster],
methods: [:tech, :hidden, :sanitized_description, :suggest, :trend_score]
).merge(marks: mark_weights, logo_url: full_logo_url, search_tags: tags)
end
def mark_weights
markings.sort_by{|marking| -marking.weight }.
take(5).
map{|marking| { weight: marking.weight, name: marking.mark.name } }
end
def trend_score
product_trend.try(:score).to_i
end
def suggest
{
input: [name, pitch] + name.split(' ') + pitch.split(' '),
output: id,
weight: trend_score,
payload: {
id: id,
slug: slug,
name: name,
pitch: pitch,
logo_url: full_logo_url,
}
}
end
def full_logo_url
# this is a hack to get a full url into elasticsearch, so firesize can resize it correctly.
# DEFAULT_IMAGE_PATH is a relative image path
logo_url == DEFAULT_IMAGE_PATH ? File.join(Rails.application.routes.url_helpers.root_url, DEFAULT_IMAGE_PATH) : logo_url
end
def tech
Search::TechFilter.matching(tags).map(&:slug)
end
def poster_image_url
unless self.logo.nil?
self.logo.url
else
PosterImage.new(self).url
end
end
def hidden
PRIVATE.include?(slug) || flagged?
end
def flagged?
!!flagged_at
end
def sanitized_description
description && Search::Sanitizer.new.sanitize(description)
end
# pusher
def push_channel
slug
end
def retrieve_key_pair
AssemblyCoin::AssignBitcoinKeyPairWorker.perform_async(
self.to_global_id,
:assign_key_pair
)
end
def assign_key_pair(key_pair)
update!(
wallet_public_address: key_pair["public_address"],
wallet_private_key: key_pair["private_key"]
)
end
def unvested_coins
unvested = 10_000_000 - transaction_log_entries.sum(:cents)
if unvested < 0
unvested = 0
end
unvested
end
def mark_vector
my_mark_vector = QueryMarks.new.mark_vector_for_object(self)
end
def normalized_mark_vector()
QueryMarks.new.normalize_mark_vector(mark_vector)
end
def majority_owner
total_coins = TransactionLogEntry.where(product: self).sum(:cents)
majority_owner = TransactionLogEntry.where(product: self).group('wallet_id').sum(:cents).sort_by{|k,v| -v}.first
majority_owner[1].to_f / total_coins.to_f >= 0.5
end
def try_url=(new_try_url)
super(new_try_url.presence)
end
protected
def add_to_event_stream
StreamEvent.add_create_event!(actor: user, subject: self)
end
end
|
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem"s version:
require "lessonable/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "lessonable"
s.version = Lessonable::VERSION
s.authors = ["Graham Powrie"]
s.email = ["graham@theworkerant.com"]
s.homepage = "theworkerant.com"
s.summary = "Business logic for businesses that provide lessons"
s.description = "Business logic for businesses that provide lessons"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.add_dependency "rails", "~> 4.0.1"
s.add_dependency "cancan"
s.add_dependency "cancan_strong_parameters"
s.add_dependency "stripe"
s.add_development_dependency "mysql2"
s.add_development_dependency "rspec-rails"
s.add_development_dependency "selenium-webdriver"
s.add_development_dependency "capybara"
s.add_development_dependency "factory_girl_rails"
s.add_development_dependency "database_cleaner"
s.add_development_dependency "guard-rspec"
s.add_development_dependency "capybara-webkit"
s.add_development_dependency "timecop"
s.add_development_dependency "json_spec"
s.add_development_dependency "slim"
end
nope, just ruby 2.0 actually
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem"s version:
require "lessonable/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "lessonable"
s.version = Lessonable::VERSION
s.authors = ["Graham Powrie"]
s.email = ["graham@theworkerant.com"]
s.homepage = "theworkerant.com"
s.summary = "Business logic for businesses that provide lessons"
s.description = "Business logic for businesses that provide lessons"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.add_dependency "rails", "~> 4.0.1"
s.add_dependency "cancan"
s.add_dependency "cancan_strong_parameters"
s.add_dependency "stripe"
s.add_development_dependency "mysql2"
s.add_development_dependency "rspec-rails"
s.add_development_dependency "selenium-webdriver"
s.add_development_dependency "capybara"
s.add_development_dependency "factory_girl_rails"
s.add_development_dependency "database_cleaner"
s.add_development_dependency "guard-rspec"
s.add_development_dependency "capybara-webkit"
s.add_development_dependency "timecop"
s.add_development_dependency "json_spec"
s.add_development_dependency "slim"
end
|
class Product < ActiveRecord::Base
belongs_to :category
has_many :line_items
has_many :orders, through: :line_items
before_destroy :ensure_not_referenced_by_any_line_item
validates :title, :description, :image_url, presence: true
validates_length_of :title, :minimum => 5
validates_length_of :title, :maximum => 60
validates :price, numericality: {greater_than_or_equal_to: 0.01}
validates :title, uniqueness: true
validates :image_url, allow_blank: true, format: {
with: %r{\.(gif|jpg|png)\Z}i,
message: 'must be a URL for GIF, JPG or PNG image.'
}
def self.latest
Product.order(:updated_at).last
end
private
def ensure_not_referenced_by_any_line_item
if line_items.empty?
return true
else
errors.add(:base, 'Line items exist')
return false
end
end
end
Link products to main_category (belongs_to)
class Product < ActiveRecord::Base
belongs_to :category
belongs_to :main_category
has_many :line_items
has_many :orders, through: :line_items
before_destroy :ensure_not_referenced_by_any_line_item
validates :title, :description, :image_url, presence: true
validates_length_of :title, :minimum => 5
validates_length_of :title, :maximum => 60
validates :price, numericality: {greater_than_or_equal_to: 0.01}
validates :title, uniqueness: true
validates :image_url, allow_blank: true, format: {
with: %r{\.(gif|jpg|png)\Z}i,
message: 'must be a URL for GIF, JPG or PNG image.'
}
def self.latest
Product.order(:updated_at).last
end
private
def ensure_not_referenced_by_any_line_item
if line_items.empty?
return true
else
errors.add(:base, 'Line items exist')
return false
end
end
end
|
class Product
include ActiveModel::Model
TEMPLATE = "https://raw.githubusercontent.com/AweSim-OSC/rails-application-template/remote_source/awesim.rb"
attr_accessor :name
attr_accessor :found
attr_accessor :title
attr_accessor :description
attr_accessor :git_remote
validates :name, presence: true
validate :app_does_not_exist, on: :create_app
validates :git_remote, presence: true, if: "type == :usr", on: :create_app
validate :manifest_is_valid, on: [:show_app, :list_apps]
validate :gemfile_is_valid, on: :show_app
validate :gems_installed, on: :show_app
def app_does_not_exist
errors.add(:name, "already exists as an app") if !name.empty? && router.path.exist?
end
def manifest_is_valid
errors.add(:manifest, "is missing, add a title and description to fix this") unless app.manifest.exist?
errors.add(:manifest, "is corrupt, please edit the file to fix this") if app.manifest.exist? && !app.manifest.valid?
end
def gemfile_is_valid
unless gemfile.exist? || gemfile_lock.exist?
errors.add(:base, "App is missing <code>Gemfile</code>") unless gemfile.exist?
errors.add(:base, "App is missing <code>Gemfile.lock</code>") unless gemfile_lock.exist?
return
end
errors.add(:base, "Gemfile missing <code>rails_12factor</code> gem") unless gemfile_specs.detect {|s| s.name == "rails_12factor"}
errors.add(:base, "Gemfile missing <code>dotenv-rails</code> gem") unless gemfile_specs.detect {|s| s.name == "dotenv-rails"}
errors.add(:base, "Gemfile missing <code>ood_appkit</code> gem") unless gemfile_specs.detect {|s| s.name == "ood_appkit"}
end
def gems_installed
unless router.path.join("bin", "bundle").exist?
errors.add(:base, "App is missing <code>bin/bundle</code>")
return
end
Dir.chdir(router.path) do
Bundler.with_clean_env do
_, s = Open3.capture2e("bin/bundle", "check")
errors.add(:base, "Install missing gems with <strong>Bundle Install</strong>") unless s.success?
end
end
end
class NotFound < StandardError; end
class << self
def product_types
{
dev: DevProduct,
usr: UsrProduct
}
end
def build(arguments = {})
type = arguments.delete(:type)
raise ArgumentError, "Need to specify type of product" unless type
product_types[type].new arguments
end
def all(type)
product_types[type].all
end
def find(type, name)
product_types[type].find(name)
end
def stage(type)
product_types[type].router.base_path.realdirpath.mkpath
true
rescue Errno::EACCES
false
end
def trash_path
router.base_path.join(".trash")
end
def trash_contents
trash_path.directory? ? trash_path.children : []
end
end
def app
OodApp.new(router)
end
def gemfile
router.path.join("Gemfile")
end
def persisted?
found
end
def new_record?
!persisted?
end
def initialize(attributes={})
super
@found ||= false
if persisted?
@title ||= app.title
@description ||= app.manifest.description
@git_remote ||= get_git_remote
end
end
def save
if self.valid?(:create_app)
stage && write_manifest
else
false
end
end
def update(attributes)
@title = attributes[:title] if attributes[:title]
@description = attributes[:description] if attributes[:description]
@git_remote = attributes[:git_remote] if attributes[:git_remote]
if self.valid?
write_manifest
set_git_remote if git_remote != get_git_remote
true
else
false
end
end
def destroy
trash_path.mkpath
FileUtils.mv router.path, trash_path.join("#{Time.now.localtime.strftime('%Y%m%dT%H%M%S')}_#{name}")
end
def permissions?
true
end
def permissions(context)
Permission.all(context, self)
end
def build_permission(context, attributes = {})
Permission.build(attributes.merge(context: context, product: self))
end
def users
permissions(:user)
end
def groups
permissions(:group)
end
def active_users
@active_users ||= `ps -o uid= -p $(pgrep -f '^Passenger .*#{Regexp.quote(router.path.realdirpath.to_s)}') 2> /dev/null | sort | uniq`.split.map(&:to_i).map do |id|
OodSupport::User.new id
end
end
private
def stage
target = router.path
target.mkpath
if git_remote.blank?
FileUtils.cp_r Rails.root.join("vendor/my_app/."), target
else
unless clone_git_repo(target)
target.rmtree if target.exist?
return false
end
end
FileUtils.chmod 0750, target
true
rescue
router.path.rmtree if router.path.exist?
raise
end
def write_manifest
File.open(router.path.join('manifest.yml'), 'w') do |f|
f.write({
'name' => title,
'description' => description
}.to_yaml)
end if (!title.blank? || !description.blank?) || !router.path.join('manifest.yml').exist?
true
end
def gemfile_lock
router.path.join("Gemfile.lock")
end
def gemfile_specs
@gemfile_specs ||= Bundler::LockfileParser.new(File.read(gemfile_lock)).specs
end
def get_git_remote
`cd #{router.path} 2> /dev/null && HOME="" git config --get remote.origin.url 2> /dev/null`.strip
end
def set_git_remote
`cd #{router.path} 2> /dev/null && HOME="" git remote set-url origin #{git_remote} 2> /dev/null`
end
def clone_git_repo(target)
o, s = Open3.capture2e({"HOME" => ""}, "git", "clone", git_remote, target.to_s)
unless s.success?
errors.add(:git_remote, "was unable to be cloned")
Rails.logger.error(o)
return false
end
true
end
end
fix trash path
class Product
include ActiveModel::Model
TEMPLATE = "https://raw.githubusercontent.com/AweSim-OSC/rails-application-template/remote_source/awesim.rb"
attr_accessor :name
attr_accessor :found
attr_accessor :title
attr_accessor :description
attr_accessor :git_remote
validates :name, presence: true
validate :app_does_not_exist, on: :create_app
validates :git_remote, presence: true, if: "type == :usr", on: :create_app
validate :manifest_is_valid, on: [:show_app, :list_apps]
validate :gemfile_is_valid, on: :show_app
validate :gems_installed, on: :show_app
def app_does_not_exist
errors.add(:name, "already exists as an app") if !name.empty? && router.path.exist?
end
def manifest_is_valid
errors.add(:manifest, "is missing, add a title and description to fix this") unless app.manifest.exist?
errors.add(:manifest, "is corrupt, please edit the file to fix this") if app.manifest.exist? && !app.manifest.valid?
end
def gemfile_is_valid
unless gemfile.exist? || gemfile_lock.exist?
errors.add(:base, "App is missing <code>Gemfile</code>") unless gemfile.exist?
errors.add(:base, "App is missing <code>Gemfile.lock</code>") unless gemfile_lock.exist?
return
end
errors.add(:base, "Gemfile missing <code>rails_12factor</code> gem") unless gemfile_specs.detect {|s| s.name == "rails_12factor"}
errors.add(:base, "Gemfile missing <code>dotenv-rails</code> gem") unless gemfile_specs.detect {|s| s.name == "dotenv-rails"}
errors.add(:base, "Gemfile missing <code>ood_appkit</code> gem") unless gemfile_specs.detect {|s| s.name == "ood_appkit"}
end
def gems_installed
unless router.path.join("bin", "bundle").exist?
errors.add(:base, "App is missing <code>bin/bundle</code>")
return
end
Dir.chdir(router.path) do
Bundler.with_clean_env do
_, s = Open3.capture2e("bin/bundle", "check")
errors.add(:base, "Install missing gems with <strong>Bundle Install</strong>") unless s.success?
end
end
end
class NotFound < StandardError; end
class << self
def product_types
{
dev: DevProduct,
usr: UsrProduct
}
end
def build(arguments = {})
type = arguments.delete(:type)
raise ArgumentError, "Need to specify type of product" unless type
product_types[type].new arguments
end
def all(type)
product_types[type].all
end
def find(type, name)
product_types[type].find(name)
end
def stage(type)
product_types[type].router.base_path.realdirpath.mkpath
true
rescue Errno::EACCES
false
end
def trash_path
router.base_path.join(".trash")
end
def trash_contents
trash_path.directory? ? trash_path.children : []
end
end
def app
OodApp.new(router)
end
def gemfile
router.path.join("Gemfile")
end
def persisted?
found
end
def new_record?
!persisted?
end
def initialize(attributes={})
super
@found ||= false
if persisted?
@title ||= app.title
@description ||= app.manifest.description
@git_remote ||= get_git_remote
end
end
def save
if self.valid?(:create_app)
stage && write_manifest
else
false
end
end
def update(attributes)
@title = attributes[:title] if attributes[:title]
@description = attributes[:description] if attributes[:description]
@git_remote = attributes[:git_remote] if attributes[:git_remote]
if self.valid?
write_manifest
set_git_remote if git_remote != get_git_remote
true
else
false
end
end
def destroy
self.class.trash_path.mkpath
FileUtils.mv router.path, self.class.trash_path.join("#{Time.now.localtime.strftime('%Y%m%dT%H%M%S')}_#{name}")
end
def permissions?
true
end
def permissions(context)
Permission.all(context, self)
end
def build_permission(context, attributes = {})
Permission.build(attributes.merge(context: context, product: self))
end
def users
permissions(:user)
end
def groups
permissions(:group)
end
def active_users
@active_users ||= `ps -o uid= -p $(pgrep -f '^Passenger .*#{Regexp.quote(router.path.realdirpath.to_s)}') 2> /dev/null | sort | uniq`.split.map(&:to_i).map do |id|
OodSupport::User.new id
end
end
private
def stage
target = router.path
target.mkpath
if git_remote.blank?
FileUtils.cp_r Rails.root.join("vendor/my_app/."), target
else
unless clone_git_repo(target)
target.rmtree if target.exist?
return false
end
end
FileUtils.chmod 0750, target
true
rescue
router.path.rmtree if router.path.exist?
raise
end
def write_manifest
File.open(router.path.join('manifest.yml'), 'w') do |f|
f.write({
'name' => title,
'description' => description
}.to_yaml)
end if (!title.blank? || !description.blank?) || !router.path.join('manifest.yml').exist?
true
end
def gemfile_lock
router.path.join("Gemfile.lock")
end
def gemfile_specs
@gemfile_specs ||= Bundler::LockfileParser.new(File.read(gemfile_lock)).specs
end
def get_git_remote
`cd #{router.path} 2> /dev/null && HOME="" git config --get remote.origin.url 2> /dev/null`.strip
end
def set_git_remote
`cd #{router.path} 2> /dev/null && HOME="" git remote set-url origin #{git_remote} 2> /dev/null`
end
def clone_git_repo(target)
o, s = Open3.capture2e({"HOME" => ""}, "git", "clone", git_remote, target.to_s)
unless s.success?
errors.add(:git_remote, "was unable to be cloned")
Rails.logger.error(o)
return false
end
true
end
end
|
class Project < ActiveRecord::Base
belongs_to :company
belongs_to :customer
belongs_to :owner, :class_name => "User", :foreign_key => "user_id"
has_many :users, :through => :project_permissions
has_many :project_permissions, :dependent => :destroy
has_many :pages, :dependent => :destroy
has_many :tasks
has_many :sheets
has_many :work_logs
has_many :activities
has_many :project_files, :dependent => :destroy
has_many :milestones, :dependent => :destroy
has_many :forums, :dependent => :destroy
validates_length_of :name, :maximum=>200
validates_presence_of :name
after_create { |r|
f = Forum.new
f.company_id = r.company_id
f.project_id = r.id
f.name = r.full_name
f.save
}
def full_name
"#{customer.name} / #{name}"
end
def to_css_name
"#{self.name.underscore.dasherize.gsub(/[ \."',]/,'-')} #{self.customer.name.underscore.dasherize.gsub(/[ \.'",]/,'-')}"
end
end
[ClockingIT @ Delete project folders when deleting project]
class Project < ActiveRecord::Base
belongs_to :company
belongs_to :customer
belongs_to :owner, :class_name => "User", :foreign_key => "user_id"
has_many :users, :through => :project_permissions
has_many :project_permissions, :dependent => :destroy
has_many :pages, :dependent => :destroy
has_many :tasks
has_many :sheets
has_many :work_logs
has_many :activities
has_many :project_files, :dependent => :destroy
has_many :project_folders, :dependent => :destroy
has_many :milestones, :dependent => :destroy
has_many :forums, :dependent => :destroy
validates_length_of :name, :maximum=>200
validates_presence_of :name
after_create { |r|
f = Forum.new
f.company_id = r.company_id
f.project_id = r.id
f.name = r.full_name
f.save
}
def full_name
"#{customer.name} / #{name}"
end
def to_css_name
"#{self.name.underscore.dasherize.gsub(/[ \."',]/,'-')} #{self.customer.name.underscore.dasherize.gsub(/[ \.'",]/,'-')}"
end
end
|
# encoding: utf-8
#--
# Copyright (C) 2012-2013 Gitorious AS
# Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies)
# Copyright (C) 2009 Fabio Akita <fabio.akita@gmail.com>
# Copyright (C) 2008 David A. Cuadrado <krawek@gmail.com>
# Copyright (C) 2008 Dag Odenhall <dag.odenhall@gmail.com>
# Copyright (C) 2008 Tim Dysinger <tim@dysinger.net>
# Copyright (C) 2008 Patrick Aljord <patcito@gmail.com>
# Copyright (C) 2008 Tor Arne Vestbø <tavestbo@trolltech.com>
# Copyright (C) 2007, 2008 Johan Sørensen <johan@johansorensen.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#++
class Project < ActiveRecord::Base
acts_as_taggable
include UrlLinting
include Watchable
include Gitorious::Authorization
include Gitorious::Protectable
belongs_to :user
belongs_to :owner, :polymorphic => true
has_many :comments, :dependent => :destroy
has_many :project_memberships, :as => :content
has_many :content_memberships, :as => :content
has_many :repositories, :order => "repositories.created_at asc",
:conditions => ["kind != ?", Repository::KIND_WIKI], :dependent => :destroy
has_one :wiki_repository, :class_name => "Repository",
:conditions => ["kind = ?", Repository::KIND_WIKI], :dependent => :destroy
has_many :cloneable_repositories, :class_name => "Repository",
:conditions => ["kind != ?", Repository::KIND_TRACKING_REPO]
has_many :events, :order => "created_at desc", :dependent => :destroy
has_many :groups
belongs_to :containing_site, :class_name => "Site", :foreign_key => "site_id"
has_many :merge_request_statuses, :order => "id asc", :dependent => :destroy
accepts_nested_attributes_for :merge_request_statuses, :allow_destroy => true
default_scope :conditions => ["projects.suspended_at is null"]
serialize :merge_request_custom_states, Array
attr_accessible(:title, :description, :user, :slug, :license,
:home_url, :mailinglist_url, :bugtracker_url, :owner, :wiki_enabled,
:owner_type, :tag_list, :merge_request_statuses_attributes,
:wiki_permissions, :default_merge_request_status_id, :owner_id)
def self.human_name
I18n.t("activerecord.models.project")
end
def self.per_page() 50 end
def self.top_tags(limit = 10)
tag_counts(:limit => limit, :order => "count desc")
end
# Returns the projects limited by +limit+ who has the most activity within
# the +cutoff+ period
def self.most_active_recently(limit = 10, number_of_days = 3)
projects = select("distinct projects.*, count(events.id) as event_count").
where("events.created_at > ?", number_of_days.days.ago).
joins(:events).
order("count(events.id) desc").
group("projects.id").
limit(limit)
end
def recently_updated_group_repository_clones(limit = 5)
self.repositories.by_groups.order("last_pushed_at desc").limit(limit)
end
def recently_updated_user_repository_clones(limit = 5)
self.repositories.by_users.order("last_pushed_at desc").limit(limit)
end
def to_param
slug
end
def to_param_with_prefix
to_param
end
def site
containing_site || Site.default
end
def committer?(candidate)
owner == User ? owner == candidate : owner.committer?(candidate)
end
def owned_by_group?
["Group","LdapGroup"].include?(owner_type)
end
def home_url=(url)
self[:home_url] = clean_url(url)
end
def mailinglist_url=(url)
self[:mailinglist_url] = clean_url(url)
end
def bugtracker_url=(url)
self[:bugtracker_url] = clean_url(url)
end
# TODO: move this to the view presentation layer
def stripped_description
description.gsub(/<\/?[^>]*>/, "") if description.present?
end
def descriptions_first_paragraph
description[/^([^\n]+)/, 1]
end
def to_xml(opts = {}, mainlines = [], clones = [])
info = Proc.new { |options|
builder = options[:builder]
builder.owner(owner.to_param, :kind => (owned_by_group? ? "Team" : "User"))
builder.repositories(:type => "array") do |repos|
builder.mainlines :type => "array" do
mainlines.each { |repo|
builder.repository do
builder.id repo.id
builder.name repo.name
builder.owner repo.owner.to_param, :kind => (repo.owned_by_group? ? "Team" : "User")
builder.clone_url repo.clone_url
end
}
end
builder.clones :type => "array" do
clones.each { |repo|
builder.repository do
builder.id repo.id
builder.name repo.name
builder.owner repo.owner.to_param, :kind => (repo.owned_by_group? ? "Team" : "User")
builder.clone_url repo.clone_url
end
}
end
end
}
super({
:procs => [info],
:only => [:slug, :title, :description, :license, :home_url, :wiki_enabled,
:created_at, :bugtracker_url, :mailinglist_url, :bugtracker_url],
}.merge(opts))
end
def create_event(action_id, target, user, data = nil, body = nil, date = Time.now.utc)
event = events.create({
:action => action_id,
:target => target,
:user => user,
:body => body,
:data => data,
:created_at => date
})
end
def new_event_required?(action_id, target, user, data)
events_count = events.where("action = :action_id AND target_id = :target_id AND target_type = :target_type AND user_id = :user_id and data = :data AND created_at > :date_threshold",
{
:action_id => action_id,
:target_id => target.id,
:target_type => target.class.name,
:user_id => user.id,
:data => data,
:date_threshold => 1.hour.ago
}).count
return events_count < 1
end
# TODO: Add tests
def oauth_consumer
@oauth_consumer ||= OAuth::Consumer.new(oauth_signoff_key, oauth_signoff_secret, oauth_consumer_options)
end
def oauth_consumer_options
result = {:site => oauth_signoff_site}
unless oauth_path_prefix.blank?
%w(request_token authorize access_token).each do |p|
result[:"#{p}_path"] = File.join("/", oauth_path_prefix, p)
end
end
result
end
def oauth_settings=(options)
self.merge_requests_need_signoff = !options[:site].blank?
self.oauth_path_prefix = options[:path_prefix]
self.oauth_signoff_key = options[:signoff_key]
self.oauth_signoff_secret = options[:signoff_secret]
self.oauth_signoff_site = options[:site]
end
def oauth_settings
{
:path_prefix => oauth_path_prefix,
:signoff_key => oauth_signoff_key,
:site => oauth_signoff_site,
:signoff_secret => oauth_signoff_secret
}
end
def search_repositories(term)
Repository.title_search(term, "project_id", id)
end
def wiki_permissions
wiki_repository.wiki_permissions
end
def wiki_permissions=(perms)
wiki_repository.wiki_permissions = perms
end
# Returns a String representation of the merge request states
def merge_request_states
(has_custom_merge_request_states? ?
merge_request_custom_states :
merge_request_default_states).join("\n")
end
def merge_request_states=(s)
self.merge_request_custom_states = s.split("\n").collect(&:strip)
end
def merge_request_fixed_states
["Merged", "Rejected"]
end
def merge_request_default_states
["Open", "Closed", "Verifying"]
end
def has_custom_merge_request_states?
!merge_request_custom_states.blank?
end
def default_merge_request_status_id
if status = merge_request_statuses.default
status.id
end
end
def default_merge_request_status_id=(status_id)
merge_request_statuses.each do |status|
if status.id == status_id.to_i
status.update_attribute(:default, true)
else
status.update_attribute(:default, false)
end
end
end
def suspended?
!suspended_at.nil?
end
def suspend!
self.suspended_at = Time.now
end
def slug=(slug)
self[:slug] = (slug || "").downcase
end
def uniq?
project = Project.where("lower(slug) = ?", slug).first
project.nil? || project == self
end
def merge_requests
MergeRequest.where("project_id = ?", id).joins(:target_repository)
end
def self.reserved_slugs
@reserved_slugs ||= []
end
def self.reserve_slugs(slugs)
@reserved_slugs ||= []
@reserved_slugs.concat(slugs)
end
def self.private_on_create?(params = {})
return false if !Gitorious.private_repositories?
params[:private] || Gitorious.repositories_default_private?
end
end
Fix warning from Project model
# encoding: utf-8
#--
# Copyright (C) 2012-2013 Gitorious AS
# Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies)
# Copyright (C) 2009 Fabio Akita <fabio.akita@gmail.com>
# Copyright (C) 2008 David A. Cuadrado <krawek@gmail.com>
# Copyright (C) 2008 Dag Odenhall <dag.odenhall@gmail.com>
# Copyright (C) 2008 Tim Dysinger <tim@dysinger.net>
# Copyright (C) 2008 Patrick Aljord <patcito@gmail.com>
# Copyright (C) 2008 Tor Arne Vestbø <tavestbo@trolltech.com>
# Copyright (C) 2007, 2008 Johan Sørensen <johan@johansorensen.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#++
class Project < ActiveRecord::Base
acts_as_taggable
include UrlLinting
include Watchable
include Gitorious::Authorization
include Gitorious::Protectable
belongs_to :user
belongs_to :owner, :polymorphic => true
has_many :comments, :dependent => :destroy
has_many :project_memberships, :as => :content
has_many :content_memberships, :as => :content
has_many :repositories, :order => "repositories.created_at asc",
:conditions => ["kind != ?", Repository::KIND_WIKI], :dependent => :destroy
has_one :wiki_repository, :class_name => "Repository",
:conditions => ["kind = ?", Repository::KIND_WIKI], :dependent => :destroy
has_many :cloneable_repositories, :class_name => "Repository",
:conditions => ["kind != ?", Repository::KIND_TRACKING_REPO]
has_many :events, :order => "created_at desc", :dependent => :destroy
has_many :groups
belongs_to :containing_site, :class_name => "Site", :foreign_key => "site_id"
has_many :merge_request_statuses, :order => "id asc", :dependent => :destroy
accepts_nested_attributes_for :merge_request_statuses, :allow_destroy => true
default_scope :conditions => ["projects.suspended_at is null"]
serialize :merge_request_custom_states, Array
attr_accessible(:title, :description, :user, :slug, :license,
:home_url, :mailinglist_url, :bugtracker_url, :owner, :wiki_enabled,
:owner_type, :tag_list, :merge_request_statuses_attributes,
:wiki_permissions, :default_merge_request_status_id, :owner_id)
def self.human_name
I18n.t("activerecord.models.project")
end
def self.per_page() 50 end
def self.top_tags(limit = 10)
tag_counts(:limit => limit, :order => "count desc")
end
# Returns the projects limited by +limit+ who has the most activity within
# the +cutoff+ period
def self.most_active_recently(limit = 10, number_of_days = 3)
select("distinct projects.*, count(events.id) as event_count").
where("events.created_at > ?", number_of_days.days.ago).
joins(:events).
order("count(events.id) desc").
group("projects.id").
limit(limit)
end
def recently_updated_group_repository_clones(limit = 5)
self.repositories.by_groups.order("last_pushed_at desc").limit(limit)
end
def recently_updated_user_repository_clones(limit = 5)
self.repositories.by_users.order("last_pushed_at desc").limit(limit)
end
def to_param
slug
end
def to_param_with_prefix
to_param
end
def site
containing_site || Site.default
end
def committer?(candidate)
owner == User ? owner == candidate : owner.committer?(candidate)
end
def owned_by_group?
["Group","LdapGroup"].include?(owner_type)
end
def home_url=(url)
self[:home_url] = clean_url(url)
end
def mailinglist_url=(url)
self[:mailinglist_url] = clean_url(url)
end
def bugtracker_url=(url)
self[:bugtracker_url] = clean_url(url)
end
# TODO: move this to the view presentation layer
def stripped_description
description.gsub(/<\/?[^>]*>/, "") if description.present?
end
def descriptions_first_paragraph
description[/^([^\n]+)/, 1]
end
def to_xml(opts = {}, mainlines = [], clones = [])
info = Proc.new { |options|
builder = options[:builder]
builder.owner(owner.to_param, :kind => (owned_by_group? ? "Team" : "User"))
builder.repositories(:type => "array") do |repos|
builder.mainlines :type => "array" do
mainlines.each { |repo|
builder.repository do
builder.id repo.id
builder.name repo.name
builder.owner repo.owner.to_param, :kind => (repo.owned_by_group? ? "Team" : "User")
builder.clone_url repo.clone_url
end
}
end
builder.clones :type => "array" do
clones.each { |repo|
builder.repository do
builder.id repo.id
builder.name repo.name
builder.owner repo.owner.to_param, :kind => (repo.owned_by_group? ? "Team" : "User")
builder.clone_url repo.clone_url
end
}
end
end
}
super({
:procs => [info],
:only => [:slug, :title, :description, :license, :home_url, :wiki_enabled,
:created_at, :bugtracker_url, :mailinglist_url, :bugtracker_url],
}.merge(opts))
end
def create_event(action_id, target, user, data = nil, body = nil, date = Time.now.utc)
event = events.create({
:action => action_id,
:target => target,
:user => user,
:body => body,
:data => data,
:created_at => date
})
end
def new_event_required?(action_id, target, user, data)
events_count = events.where("action = :action_id AND target_id = :target_id AND target_type = :target_type AND user_id = :user_id and data = :data AND created_at > :date_threshold",
{
:action_id => action_id,
:target_id => target.id,
:target_type => target.class.name,
:user_id => user.id,
:data => data,
:date_threshold => 1.hour.ago
}).count
return events_count < 1
end
# TODO: Add tests
def oauth_consumer
@oauth_consumer ||= OAuth::Consumer.new(oauth_signoff_key, oauth_signoff_secret, oauth_consumer_options)
end
def oauth_consumer_options
result = {:site => oauth_signoff_site}
unless oauth_path_prefix.blank?
%w(request_token authorize access_token).each do |p|
result[:"#{p}_path"] = File.join("/", oauth_path_prefix, p)
end
end
result
end
def oauth_settings=(options)
self.merge_requests_need_signoff = !options[:site].blank?
self.oauth_path_prefix = options[:path_prefix]
self.oauth_signoff_key = options[:signoff_key]
self.oauth_signoff_secret = options[:signoff_secret]
self.oauth_signoff_site = options[:site]
end
def oauth_settings
{
:path_prefix => oauth_path_prefix,
:signoff_key => oauth_signoff_key,
:site => oauth_signoff_site,
:signoff_secret => oauth_signoff_secret
}
end
def search_repositories(term)
Repository.title_search(term, "project_id", id)
end
def wiki_permissions
wiki_repository.wiki_permissions
end
def wiki_permissions=(perms)
wiki_repository.wiki_permissions = perms
end
# Returns a String representation of the merge request states
def merge_request_states
(has_custom_merge_request_states? ?
merge_request_custom_states :
merge_request_default_states).join("\n")
end
def merge_request_states=(s)
self.merge_request_custom_states = s.split("\n").collect(&:strip)
end
def merge_request_fixed_states
["Merged", "Rejected"]
end
def merge_request_default_states
["Open", "Closed", "Verifying"]
end
def has_custom_merge_request_states?
!merge_request_custom_states.blank?
end
def default_merge_request_status_id
if status = merge_request_statuses.default
status.id
end
end
def default_merge_request_status_id=(status_id)
merge_request_statuses.each do |status|
if status.id == status_id.to_i
status.update_attribute(:default, true)
else
status.update_attribute(:default, false)
end
end
end
def suspended?
!suspended_at.nil?
end
def suspend!
self.suspended_at = Time.now
end
def slug=(slug)
self[:slug] = (slug || "").downcase
end
def uniq?
project = Project.where("lower(slug) = ?", slug).first
project.nil? || project == self
end
def merge_requests
MergeRequest.where("project_id = ?", id).joins(:target_repository)
end
def self.reserved_slugs
@reserved_slugs ||= []
end
def self.reserve_slugs(slugs)
@reserved_slugs ||= []
@reserved_slugs.concat(slugs)
end
def self.private_on_create?(params = {})
return false if !Gitorious.private_repositories?
params[:private] || Gitorious.repositories_default_private?
end
end
|
class Project < ActiveRecord::Base
validates_presence_of :name, :platform
# validate unique name and platform (case?)
# TODO validate homepage format
def to_param
"#{id}-#{name.parameterize}"
end
def to_s
name
end
has_many :versions
has_one :github_repository
scope :platform, ->(platform) { where platform: platform }
scope :with_repository_url, -> { where("repository_url <> ''") }
scope :with_repo, -> { includes(:github_repository).where('github_repositories.id IS NOT NULL') }
def self.undownloaded_repos
with_repository_url.where('id NOT IN (SELECT DISTINCT(project_id) FROM github_repositories)')
end
def self.search(query)
q = "%#{query}%"
where('name ILIKE ? or keywords ILIKE ?', q, q).order(:created_at)
end
def self.license(license)
where('licenses ILIKE ?', "%#{license}%")
end
def self.licenses
licenses = Project.select('DISTINCT licenses').map(&:licenses).compact
licenses.join(',').split(',')
.map(&:downcase).map(&:strip).reject(&:blank?).uniq.sort
end
def self.popular_platforms(limit = 5)
select('count(*) count, platform')
.group('platform')
.order('count DESC')
.limit(limit)
end
def self.popular_licenses(limit = 8)
where("licenses <> ''")
.where("licenses != 'UNKNOWN'")
.select('count(*) count, licenses')
.group('licenses')
.order('count DESC')
.limit(limit)
end
def github_client
AuthToken.client
end
def update_github_repo
name_with_owner = github_name_with_owner
p name_with_owner
return false unless name_with_owner
begin
r = github_client.repo(name_with_owner).to_hash
g = GithubRepository.find_or_initialize_by(r.slice(:full_name))
g.owner_id = r[:owner][:id]
g.project = self
g.assign_attributes r.slice(*github_keys)
g.save
rescue Octokit::NotFound, Octokit::Forbidden => e
response = Net::HTTP.get_response(URI(github_url))
if response.code.to_i == 301
self.repository_url = URI(response['location']).to_s
update_github_repo
else
p response.code.to_i
p e
end
end
end
def download_github_contributions
return false unless github_repository
github_repository.download_github_contributions
end
def github_keys
[:description, :fork, :created_at, :updated_at, :pushed_at, :homepage,
:size, :stargazers_count, :language, :has_issues, :has_wiki, :has_pages,
:forks_count, :mirror_url, :open_issues_count, :default_branch,
:subscribers_count]
end
def github_url
return false if repository_url.blank?
"https://github.com/#{github_name_with_owner}"
end
def github_name_with_owner
url = repository_url.clone
github_regex = /(((https|http|git)?:\/\/(www\.)?)|git@|scm:git:git@)(github.com|raw.githubusercontent.com)(:|\/)/i
return nil unless url.match(github_regex)
url.gsub!(github_regex, '').strip!
url.gsub!(/(\.git|\/)$/i, '')
url = url.split('/')[0..1]
return nil unless url.length == 2
url.join('/')
end
def bitbucket_url
url = repository_url.clone
github_regex = /^(((https|http|git)?:\/\/(www\.)?)|git@)bitbucket.org(:|\/)/i
return nil unless url.match(github_regex)
url.gsub!(github_regex, '').strip!
url.gsub!(/(\.git|\/)$/i, '')
url = url.split('/')[0..1]
return nil unless url.length == 2
"https://bitbucket.org/#{bitbucket_name_with_owner}"
end
def bitbucket_name_with_owner
github_regex = /^(((https|http|git)?:\/\/(www\.)?)|git@)bitbucket.org(:|\/)/i
return nil unless url.match(github_regex)
url.gsub!(github_regex, '').strip!
url.gsub!(/(\.git|\/)$/i, '')
url = url.split('/')[0..1]
return nil unless url.length == 2
url.join('/')
end
## relations
# versions => dependencies
# repository
# licenses
# users
end
No “OtherLicense” either
class Project < ActiveRecord::Base
validates_presence_of :name, :platform
# validate unique name and platform (case?)
# TODO validate homepage format
def to_param
"#{id}-#{name.parameterize}"
end
def to_s
name
end
has_many :versions
has_one :github_repository
scope :platform, ->(platform) { where platform: platform }
scope :with_repository_url, -> { where("repository_url <> ''") }
scope :with_repo, -> { includes(:github_repository).where('github_repositories.id IS NOT NULL') }
def self.undownloaded_repos
with_repository_url.where('id NOT IN (SELECT DISTINCT(project_id) FROM github_repositories)')
end
def self.search(query)
q = "%#{query}%"
where('name ILIKE ? or keywords ILIKE ?', q, q).order(:created_at)
end
def self.license(license)
where('licenses ILIKE ?', "%#{license}%")
end
def self.licenses
licenses = Project.select('DISTINCT licenses').map(&:licenses).compact
licenses.join(',').split(',')
.map(&:downcase).map(&:strip).reject(&:blank?).uniq.sort
end
def self.popular_platforms(limit = 5)
select('count(*) count, platform')
.group('platform')
.order('count DESC')
.limit(limit)
end
def self.popular_licenses(limit = 8)
where("licenses <> ''")
.where("licenses != 'UNKNOWN'")
.where("licenses != 'OtherLicense'")
.select('count(*) count, licenses')
.group('licenses')
.order('count DESC')
.limit(limit)
end
def github_client
AuthToken.client
end
def update_github_repo
name_with_owner = github_name_with_owner
p name_with_owner
return false unless name_with_owner
begin
r = github_client.repo(name_with_owner).to_hash
g = GithubRepository.find_or_initialize_by(r.slice(:full_name))
g.owner_id = r[:owner][:id]
g.project = self
g.assign_attributes r.slice(*github_keys)
g.save
rescue Octokit::NotFound, Octokit::Forbidden => e
response = Net::HTTP.get_response(URI(github_url))
if response.code.to_i == 301
self.repository_url = URI(response['location']).to_s
update_github_repo
else
p response.code.to_i
p e
end
end
end
def download_github_contributions
return false unless github_repository
github_repository.download_github_contributions
end
def github_keys
[:description, :fork, :created_at, :updated_at, :pushed_at, :homepage,
:size, :stargazers_count, :language, :has_issues, :has_wiki, :has_pages,
:forks_count, :mirror_url, :open_issues_count, :default_branch,
:subscribers_count]
end
def github_url
return false if repository_url.blank?
"https://github.com/#{github_name_with_owner}"
end
def github_name_with_owner
url = repository_url.clone
github_regex = /(((https|http|git)?:\/\/(www\.)?)|git@|scm:git:git@)(github.com|raw.githubusercontent.com)(:|\/)/i
return nil unless url.match(github_regex)
url.gsub!(github_regex, '').strip!
url.gsub!(/(\.git|\/)$/i, '')
url = url.split('/')[0..1]
return nil unless url.length == 2
url.join('/')
end
def bitbucket_url
url = repository_url.clone
github_regex = /^(((https|http|git)?:\/\/(www\.)?)|git@)bitbucket.org(:|\/)/i
return nil unless url.match(github_regex)
url.gsub!(github_regex, '').strip!
url.gsub!(/(\.git|\/)$/i, '')
url = url.split('/')[0..1]
return nil unless url.length == 2
"https://bitbucket.org/#{bitbucket_name_with_owner}"
end
def bitbucket_name_with_owner
github_regex = /^(((https|http|git)?:\/\/(www\.)?)|git@)bitbucket.org(:|\/)/i
return nil unless url.match(github_regex)
url.gsub!(github_regex, '').strip!
url.gsub!(/(\.git|\/)$/i, '')
url = url.split('/')[0..1]
return nil unless url.length == 2
url.join('/')
end
## relations
# versions => dependencies
# repository
# licenses
# users
end
|
# frozen_string_literal: true
# Copyright 2015-2017, the Linux Foundation, IDA, and the
# CII Best Practices badge contributors
# SPDX-License-Identifier: MIT
# rubocop:disable Metrics/ClassLength
class Project < ApplicationRecord
has_many :additional_rights, dependent: :destroy
cattr_accessor :skip_callbacks
# We could add something like this:
# + has_many :users, through: :additional_rights
# but we don't, because we don't use the other information about those users.
# We only need the user_ids and the additional_rights table has that.
using StringRefinements
using SymbolRefinements
include PgSearch::Model # PostgreSQL-specific text search
# When did we add met_justification_required?
STATIC_ANALYSIS_JUSTIFICATION_REQUIRED_DATE =
Time.iso8601('2017-04-25T00:00:00Z')
# When did we first show an explicit license for the data
# (CC-BY-3.0+)?
ENTRY_LICENSE_EXPLICIT_DATE = Time.iso8601('2017-02-20T12:00:00Z')
STATUS_CHOICE = %w[? Met Unmet].freeze
STATUS_CHOICE_NA = (STATUS_CHOICE + %w[N/A]).freeze
MIN_SHOULD_LENGTH = 5
MAX_TEXT_LENGTH = 8192 # Arbitrary maximum to reduce abuse
MAX_SHORT_STRING_LENGTH = 254 # Arbitrary maximum to reduce abuse
# All badge level internal names *including* in_progress
# NOTE: If you add a new level, modify compute_tiered_percentage
BADGE_LEVELS = %w[in_progress passing silver gold].freeze
# All badge level internal names that indicate *completion*,
# so COMPLETED_BADGE_LEVELS[0] is 'passing'.
# Note: This is the *internal* lowercase name, e.g., for field names.
# For *printed* names use t("projects.form_early.level.#{level}")
# Note that drop() does NOT mutate the original value.
COMPLETED_BADGE_LEVELS = BADGE_LEVELS.drop(1).freeze
# All badge levels as IDs. Useful for enumerating "all levels" as:
# Project::LEVEL_IDS.each do |level| ... end
LEVEL_ID_NUMBERS = (0..(COMPLETED_BADGE_LEVELS.length - 1)).freeze
LEVEL_IDS = LEVEL_ID_NUMBERS.map(&:to_s)
PROJECT_OTHER_FIELDS = %i[
name description homepage_url repo_url cpe implementation_languages
license general_comments user_id disabled_reminders lock_version
level additional_rights_changes
].freeze
ALL_CRITERIA_STATUS = Criteria.all.map(&:status).freeze
ALL_CRITERIA_JUSTIFICATION = Criteria.all.map(&:justification).freeze
PROJECT_PERMITTED_FIELDS = (PROJECT_OTHER_FIELDS + ALL_CRITERIA_STATUS +
ALL_CRITERIA_JUSTIFICATION).freeze
default_scope { order(:created_at) }
scope :created_since, (
lambda do |time|
where(Project.arel_table[:created_at].gteq(time))
end
)
scope :gteq, (
lambda do |floor|
where(Project.arel_table[:tiered_percentage].gteq(floor.to_i))
end
)
scope :in_progress, -> { lteq(99) }
scope :lteq, (
lambda do |ceiling|
where(Project.arel_table[:tiered_percentage].lteq(ceiling.to_i))
end
)
scope :passing, -> { gteq(100) }
scope :recently_updated, (
lambda do
# The "includes" here isn't ideal.
# Originally we used "eager_load" on :user, but
# "eager_load" forces a load of *all* fields per a bug in Rails:
# https://github.com/rails/rails/issues/15185
# Switching to ".includes" fixes the bug, though it means we do 2
# database queries instead of just one.
# We could use the gem "rails_select_on_includes" to fix this bug:
# https://github.com/alekseyl/rails_select_on_includes
# but that's something of a hack.
# If a totally-cached feed is used, then the development environment
# will complain as follows:
# GET /feed
# AVOID eager loading detected
# Project => [:user]
# Remove from your finder: :includes => [:user]
# However, you *cannot* simply remove the includes, because
# when the feed is *not* completely cached, the code *does* need
# this user data.
limit(50).reorder(updated_at: :desc, id: :asc).includes(:user)
end
)
# prefix query (old search system)
scope :text_search, (
lambda do |text|
start_text = "#{sanitize_sql_like(text)}%"
where(
Project.arel_table[:name].matches(start_text).or(
Project.arel_table[:homepage_url].matches(start_text)
).or(
Project.arel_table[:repo_url].matches(start_text)
)
)
end
)
# Search for exact match on URL
# (home page, repo, and maybe package URL someday)
# We have indexes on each of these columns, so this will be fast.
# We remove trailing space and slash to make it quietly "work as expected".
scope :url_search, (
lambda do |url|
clean_url = url.chomp(' ').chomp('/')
where('homepage_url = ? OR repo_url = ?', clean_url, clean_url)
end
)
# Use PostgreSQL-specific text search mechanism
# There are many options we aren't currently using; for more info, see:
# https://github.com/Casecommons/pg_search
pg_search_scope(
:search_for,
against: %i[name homepage_url repo_url description]
# using: { tsearch: { any_word: true } }
)
scope :updated_since, (
lambda do |time|
where(Project.arel_table[:updated_at].gteq(time))
end
)
# Record information about a project.
# We'll also record previous versions of information:
has_paper_trail
before_save :update_badge_percentages, unless: :skip_callbacks
# A project is associated with a user
belongs_to :user
delegate :name, to: :user, prefix: true # Support "user_name"
delegate :nickname, to: :user, prefix: true # Support "user_nickname"
# For these fields we'll have just simple validation rules.
# We'll rely on Rails' HTML escaping system to counter XSS.
validates :name, length: { maximum: MAX_SHORT_STRING_LENGTH },
text: true
validates :description, length: { maximum: MAX_TEXT_LENGTH },
text: true
validates :license, length: { maximum: MAX_SHORT_STRING_LENGTH },
text: true
validates :general_comments, text: true
# We'll do automated analysis on these URLs, which means we will *download*
# from URLs provided by untrusted users. Thus we'll add additional
# URL restrictions to counter tricks like http://ACCOUNT:PASSWORD@host...
# and http://something/?arbitrary_parameters
validates :repo_url, url: true, length: { maximum: MAX_SHORT_STRING_LENGTH },
uniqueness: { allow_blank: true }
validates :homepage_url,
url: true,
length: { maximum: MAX_SHORT_STRING_LENGTH }
validate :need_a_base_url
# Comma-separated list. This is very generous in what characters it
# allows in a programming language name, but restricts it to ASCII and omits
# problematic characters that are very unlikely in a name like
# <, >, &, ", brackets, and braces. This handles language names like
# JavaScript, C++, C#, D-, and PL/I. A space is optional after a comma.
# We have to allow embedded spaces, e.g., "Jupyter Notebook".
VALID_LANGUAGE_LIST =
%r{\A(|-| ([A-Za-z0-9!\#$%'()*+.\/\:;=?@\[\]^~ -]+
(,\ ?[A-Za-z0-9!\#$%'()*+.\/\:;=?@\[\]^~ -]+)*))\Z}x.freeze
validates :implementation_languages,
length: { maximum: MAX_SHORT_STRING_LENGTH },
format: {
with: VALID_LANGUAGE_LIST,
message: :comma_separated_list
}
validates :cpe,
length: { maximum: MAX_SHORT_STRING_LENGTH },
format: {
with: /\A(cpe:.*)?\Z/,
message: :begin_with_cpe
}
validates :user_id, presence: true
Criteria.each_value do |criteria|
criteria.each_value do |criterion|
if criterion.na_allowed?
validates criterion.name.status, inclusion: { in: STATUS_CHOICE_NA }
else
validates criterion.name.status, inclusion: { in: STATUS_CHOICE }
end
validates criterion.name.justification,
length: { maximum: MAX_TEXT_LENGTH },
text: true
end
end
# Return a string representing the additional rights on this project.
# Currently it's just a (possibly empty) list of user ids from
# AdditionalRight. If AdditionalRights gains different kinds of rights
# (e.g., to spec additional owners), this method will need to be tweaked.
def additional_rights_to_s
# "distinct" shouldn't be needed; it's purely defensive here
list = AdditionalRight.where(project_id: id).distinct.pluck(:user_id)
list.sort.to_s # Use list.sort.to_s[1..-2] to remove surrounding [ and ]
end
# Return string representing badge level; assumes tiered_percentage correct.
# This returns 'in_progress' if we aren't passing yet.
# See method badge_level if you want 'in_progress' for < 100.
# See method badge_value if you want the specific percentage for in_progress.
def badge_level
# This is *integer* division, so it truncates.
BADGE_LEVELS[tiered_percentage / 100]
end
def calculate_badge_percentage(level)
active = Criteria.active(level)
met = active.count { |criterion| enough?(criterion) }
to_percentage met, active.size
end
# Does this contain a URL *anywhere* in the (justification) text?
# Note: This regex needs to be logically the same as the one used in the
# client-side badge calculation, or it may confuse some users.
# See app/assets/javascripts/*.js function "containsURL".
#
# Note that we do NOT need to validate these URLs, because the BadgeApp
# 1. escapes these (as part of normal processing) against XSS attacks, and
# 2. does not traverse these URLs in its automated processing.
# Thus, this rule is intentionally *not* strict at all. Contrast this
# with the intentionally strict validation of the project and repo URLs,
# which *are* traversed by BadgeApp and thus need to be much more strict.
#
def contains_url?(text)
return false if !text || text.start_with?('// ')
text =~ %r{https?://[^ ]{5}}
end
# Returns a symbol indicating a the status of an particular criterion
# in a project. These are:
# :criterion_passing -
# 'Met' (or 'N/A' if applicable) has been selected for the criterion
# and all requred justification text (including url's) have been entered #
# :criterion_failing -
# 'Unmet' has been selected for a MUST criterion'.
# :criterion_barely -
# 'Unmet' has been selected for a SHOULD or SUGGESTED criterion and
# ,if SHOULD, required justification text has been entered.
# :criterion_url_required -
# 'Met' has been selected, but a required url in the justification
# text is missing.
# :criterion_justification_required -
# Required justification for 'Met', 'N/A' or 'Unmet' selection is missing.
# :criterion_unknown -
# The criterion has been left at it's default value and thus the status
# is unknown.
# This method is mirrored in assets/project-form.js as getCriterionResult
# If you change this method, change getCriterionResult accordingly.
def get_criterion_result(criterion)
status = self[criterion.name.status]
justification = self[criterion.name.justification]
return :criterion_unknown if status.unknown?
return get_met_result(criterion, justification) if status.met?
return get_unmet_result(criterion, justification) if status.unmet?
get_na_result(criterion, justification)
end
def get_satisfaction_data(level, panel)
total =
Criteria[level].values.select do |criterion|
criterion.major.downcase.delete(' ') == panel
end
passing = total.count { |criterion| enough?(criterion) }
{
text: "#{passing}/#{total.size}",
color: get_color(passing / [1, total.size.to_f].max)
}
end
# Return the badge value: 0..99 (the percent) if in progress,
# else it returns 'passing', 'silver', or 'gold'.
# This presumes that tiered_percentage has already been calculated.
# See method badge_level if you want 'in_progress' for < 100.
def badge_value
if tiered_percentage < 100
tiered_percentage
else
# This is *integer* division, so it truncates.
BADGE_LEVELS[tiered_percentage / 100]
end
end
# Return this project's image src URL for its badge image (SVG).
# * If the project entry has changed relatively recently,
# we give its /badge_static value. That way, the user sees the
# correct result even if the CDN hasn't completed distributing the
# new value or a bad key prevents its update.
# * If the project entry has NOT changed relatively recently,
# we give the /projects/:id/badge value, so that humans who copy the
# values without reading directions are more likely to see the URL that
# we want them to use in READMEs. We also include a comment in the HTML
# view telling people to use the /projects/:id/badge URL, all to encourage
# humans to use the correct URL.
def badge_src_url
if updated_at > 24.hours.ago # Has this entry changed relatively recently?
"/badge_static/#{badge_value}"
else
"/projects/#{id}/badge"
end
end
# Flash a message to update static_analysis if the user is updating
# for the first time since we added met_justification_required that
# criterion
def notify_for_static_analysis?(level)
status = self[Criteria[level][:static_analysis].name.status]
result = get_criterion_result(Criteria[level][:static_analysis])
updated_at < STATIC_ANALYSIS_JUSTIFICATION_REQUIRED_DATE &&
status.met? && result == :criterion_justification_required
end
# Send owner an email they add a new project.
def send_new_project_email
ReportMailer.email_new_project_owner(self).deliver_now
end
# Return true if we should show an explicit license for the data.
# Old entries did not set a license; we only want to show entry licenses
# if the updated_at field indicates there was agreement to it.
def show_entry_license?
updated_at >= ENTRY_LICENSE_EXPLICIT_DATE
end
# Update the badge percentage for a given level (expressed as a number;
# 0=passing), and update relevant event datetime if needed.
# It presumes the lower-level percentages (if relevant) are calculated.
def update_badge_percentage(level, current_time)
old_badge_percentage = self["badge_percentage_#{level}".to_sym]
update_prereqs(level) unless level.to_i.zero?
self["badge_percentage_#{level}".to_sym] =
calculate_badge_percentage(level)
update_passing_times(level, old_badge_percentage, current_time)
end
# Compute the 'tiered percentage' value 0..300. This gives partial credit,
# but only if you've completed a previous level.
def compute_tiered_percentage
if badge_percentage_0 < 100
badge_percentage_0
elsif badge_percentage_1 < 100
badge_percentage_1 + 100
else
badge_percentage_2 + 200
end
end
def update_tiered_percentage
self.tiered_percentage = compute_tiered_percentage
end
# Update the badge percentages for all levels.
def update_badge_percentages
# Create a single datetime value so that they are consistent
current_time = Time.now.utc
Project::LEVEL_IDS.each do |level|
update_badge_percentage(level, current_time)
end
update_tiered_percentage # Update the 'tiered_percentage' number 0..300
end
# Return owning user's name for purposes of display.
def user_display_name
user_name || user_nickname
end
# Update badge percentages for all project entries, and send emails
# to any project where this causes loss or gain of a badge.
# Use this after the badging rules have changed.
# We precalculate and store percentages in the database;
# this speeds up many actions, but it means that a change in the rules
# doesn't automatically change the precalculated values.
# rubocop:disable Metrics/MethodLength
def self.update_all_badge_percentages(levels)
raise TypeError, 'levels must be an Array' unless levels.is_a?(Array)
levels.each do |l|
raise ArgumentError, "Invalid level: #{l}" unless l.in? Criteria.keys
end
Project.skip_callbacks = true
Project.find_each do |project|
project.with_lock do
# Create a single datetime value so that they are consistent
current_time = Time.now.utc
levels.each do |level|
project.update_badge_percentage(level, current_time)
end
project.update_tiered_percentage
project.save!(touch: false)
end
end
Project.skip_callbacks = false
end
# rubocop:enable Metrics/MethodLength
# The following configuration options are trusted. Set them to
# reasonable numbers or accept the defaults.
# Maximum number of reminders to send by email at one time.
# We want a rate limit to avoid being misinterpreted as a spammer,
# and also to limit damage if there's a mistake in the code.
# By default, start very low until we're confident in the code.
MAX_REMINDERS = (ENV['BADGEAPP_MAX_REMINDERS'] || 2).to_i
# Minimum number of days since last lost a badge before sending reminder,
# if it lost one.
LOST_PASSING_REMINDER = (ENV['BADGEAPP_LOST_PASSING_REMINDER'] || 30).to_i
# Minimum number of days since project last updated before sending reminder
LAST_UPDATED_REMINDER = (ENV['BADGEAPP_LAST_UPDATED_REMINDER'] || 30).to_i
# Minimum number of days since project was last sent a reminder
LAST_SENT_REMINDER = (ENV['BADGEAPP_LAST_SENT_REMINDER'] || 60).to_i
# Return which projects should be reminded to work on their badges. See:
# https://github.com/coreinfrastructure/best-practices-badge/issues/487
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def self.projects_to_remind
# This is computed entirely using the ActiveRecord query interface
# as a single select+sort+limit, and not implemented using methods or
# direct SQL commands. Using the ActiveRecord query interface will turn
# this directly into a single database request, which will be blazingly
# fast regardless of the database size (via the indexes). Method
# invocations would be super-slow, and direct SQL commands will be less
# portable than ActiveRecord's interface (which works to paper over
# differences between SQL engines).
#
# Select projects eligible for reminders =
# in_progress and not_recently_lost_badge and not_disabled_reminders
# and inactive and not_recently_reminded and valid_email.
# where these terms are defined as:
# in_progress = badge_percentage less than 100%.
# not_recently_lost_badge = lost_passing_at IS NULL OR
# less than LOST_PASSING_REMINDER (30) days ago
# not_disabled_reminders = not(project.disabled_reminders), default false
# inactive = updated_at is LAST_UPDATED_REMINDER (30) days ago or more
# not_recently_reminded = last_reminder_at IS NULL OR
# more than 60 days ago. Notice that if recently_reminded is null
# (no reminders have been sent), only the other criteria matter.
# valid_email = users.encrypted_email (joined) is not null
# Prioritize. Sort by the last_reminder_at datetime
# (use updated_at if last_reminder_at is null), oldest first.
# Since last_reminder_at gets updated with a newer datetime when
# we send a message, each email we send will lower its reminder
# priority. Thus we will eventually cycle through all inactive projects
# if none of them respond to reminders.
# Use: projects.order("COALESCE(last_reminder_at, updated_at)")
# We cannot check if email includes "@" here, because they are
# encrypted (the database does not have access to the keys, by intent).
#
# The "reorder" below uses "Arel.sql" to work around
# a deprecation warning from Rails 5.2, and
# is not expected to work in Rails 6. The warning is as follows:
# DEPRECATION WARNING: Dangerous query method
# (method whose arguments are used as raw SQL) called with
# non-attribute argument(s): "COALESCE(last_reminder_at,
# projects.updated_at)". Non-attribute arguments will be
# disallowed in Rails 6.0. This method should not be called with
# user-provided values, such as request parameters or model
# attributes. Known-safe values can be passed by wrapping
# them in Arel.sql().
# For now we'll wrap them as required. This is unfortunate; it would
# dangerous if user-provided data was used, but that is not the case.
# We're hoping Rails 6 will give us an alternative construct.
# If not, alternatives include creating a calculated field
# (e.g., one that does the coalescing).
Project
.select('projects.*, users.encrypted_email as user_encrypted_email')
.where('badge_percentage_0 < 100')
.where('lost_passing_at IS NULL OR lost_passing_at < ?',
LOST_PASSING_REMINDER.days.ago)
.where('disabled_reminders = FALSE')
.where('projects.updated_at < ?',
LAST_UPDATED_REMINDER.days.ago)
.where('last_reminder_at IS NULL OR last_reminder_at < ?',
LAST_SENT_REMINDER.days.ago)
.joins(:user).references(:user) # Need this to check email address
.where('user_id IS NOT NULL') # Safety check
.where('users.encrypted_email IS NOT NULL')
.reorder(Arel.sql('COALESCE(last_reminder_at, projects.updated_at)'))
.first(MAX_REMINDERS)
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
# Return which projects should be announced as getting badges in the
# month target_month with level (as a number, 0=passing)
def self.projects_first_in(level, target_month)
name = COMPLETED_BADGE_LEVELS[level] # field name, e.g. 'passing'
# We could omit listing projects which have lost & regained their
# badge by adding this line:
# .where('lost_#{name}_at IS NULL')
# However, it seems reasonable to note projects that have lost their
# badge but have since regained it (especially since it could have
# happened within this month!). After all, we want to encourage
# projects that have lost their badge levels to regain them.
Project
.select("id, name, achieved_#{name}_at")
.where("badge_percentage_#{level} >= 100")
.where("achieved_#{name}_at >= ?", target_month.at_beginning_of_month)
.where("achieved_#{name}_at <= ?", target_month.at_end_of_month)
.reorder("achieved_#{name}_at")
end
def self.recently_reminded
Project
.select('projects.*, users.encrypted_email as user_encrypted_email')
.joins(:user).references(:user) # Need this to check email address
.where('last_reminder_at IS NOT NULL')
.where('last_reminder_at >= ?', 14.days.ago)
.reorder('last_reminder_at')
end
private
# def all_active_criteria_passing?
# Criteria.active.all? { |criterion| enough? criterion }
# end
WHAT_IS_ENOUGH = %i[criterion_passing criterion_barely].freeze
# This method is mirrored in assets/project-form.js as isEnough
# If you change this method, change isEnough accordingly.
def enough?(criterion)
result = get_criterion_result(criterion)
WHAT_IS_ENOUGH.include?(result)
end
# This method is mirrored in assets/project-form.js as getColor
# If you change this method, change getColor accordingly.
def get_color(value)
hue = (value * 120).round
"hsl(#{hue}, 100%, 50%)"
end
# This method is mirrored in assets/project-form.js as getMetResult
# If you change this method, change getMetResult accordingly.
def get_met_result(criterion, justification)
return :criterion_url_required if criterion.met_url_required? &&
!contains_url?(justification)
return :criterion_justification_required if
criterion.met_justification_required? &&
!justification_good?(justification)
:criterion_passing
end
# This method is mirrored in assets/project-form.js as getNAResult
# If you change this method, change getNAResult accordingly.
def get_na_result(criterion, justification)
return :criterion_justification_required if
criterion.na_justification_required? &&
!justification_good?(justification)
:criterion_passing
end
# This method is mirrored in assets/project-form.js as getUnmetResult
# If you change this method, change getUnmetResult accordingly.
def get_unmet_result(criterion, justification)
return :criterion_barely if criterion.suggested? || (criterion.should? &&
justification_good?(justification))
return :criterion_justification_required if criterion.should?
:criterion_failing
end
def justification_good?(justification)
return false if justification.nil? || justification.start_with?('// ')
justification.length >= MIN_SHOULD_LENGTH
end
def need_a_base_url
return unless repo_url.blank? && homepage_url.blank?
errors.add :base, I18n.t('error_messages.need_home_page_or_url')
end
def to_percentage(portion, total)
return 0 if portion.zero?
((portion * 100.0) / total).round
end
# Update achieved_..._at & lost_..._at fields given level as number
# rubocop:disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def update_passing_times(level, old_badge_percentage, current_time)
level_name = COMPLETED_BADGE_LEVELS[level.to_i] # E.g., 'passing'
current_percentage = self["badge_percentage_#{level}".to_sym]
# If something is wrong, don't modify anything!
return if current_percentage.blank? || old_badge_percentage.blank?
current_percentage_i = current_percentage.to_i
old_badge_percentage_i = old_badge_percentage.to_i
if current_percentage_i >= 100 && old_badge_percentage_i < 100
self["achieved_#{level_name}_at".to_sym] = current_time
first_achieved_field = "first_achieved_#{level_name}_at".to_sym
if self[first_achieved_field].blank? # First time? Set that too!
self[first_achieved_field] = current_time
end
elsif current_percentage_i < 100 && old_badge_percentage_i >= 100
self["lost_#{level_name}_at".to_sym] = current_time
end
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
# rubocop:enable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity
# Given numeric level 1+, set the value of
# achieve_{previous_level_name}_status to either Met or Unmet, based on
# the achievement of the *previous* level. This is a simple way to ensure
# that to pass level X when X > 0, you must meet the criteria of level X-1.
# We *only* set the field if it currently has a different value.
# When filling in the prerequisites, we do not fill in the justification
# for them. The justification is only there as it makes implementing this
# portion of the code simpler.
def update_prereqs(level)
level = level.to_i
return if level <= 0
# The following works because BADGE_LEVELS[1] is 'passing', etc:
achieved_previous_level = "achieve_#{BADGE_LEVELS[level]}_status".to_sym
if self["badge_percentage_#{level - 1}".to_sym] >= 100
return if self[achieved_previous_level] == 'Met'
self[achieved_previous_level] = 'Met'
else
return if self[achieved_previous_level] == 'Unmet'
self[achieved_previous_level] = 'Unmet'
end
end
end
# rubocop:enable Metrics/ClassLength
Make percentage <100% if level incomplete (#1593)
This commit caps the "percentage" value to
99 at most if the level is not 100% complete.
This is a defensive programming measure.
We round percentages, so this will only a problem once
(N-1)/N >= 0.995, that is, number of items in a level N>=200,
and we don't want that many questions in a level.
Still, I feel better being *certain* it cannot cause problems.
Signed-off-by: David A. Wheeler <9ae72d22d8b894b865a7a496af4fab6320e6abb2@dwheeler.com>
# frozen_string_literal: true
# Copyright 2015-2017, the Linux Foundation, IDA, and the
# CII Best Practices badge contributors
# SPDX-License-Identifier: MIT
# rubocop:disable Metrics/ClassLength
class Project < ApplicationRecord
has_many :additional_rights, dependent: :destroy
cattr_accessor :skip_callbacks
# We could add something like this:
# + has_many :users, through: :additional_rights
# but we don't, because we don't use the other information about those users.
# We only need the user_ids and the additional_rights table has that.
using StringRefinements
using SymbolRefinements
include PgSearch::Model # PostgreSQL-specific text search
# When did we add met_justification_required?
STATIC_ANALYSIS_JUSTIFICATION_REQUIRED_DATE =
Time.iso8601('2017-04-25T00:00:00Z')
# When did we first show an explicit license for the data
# (CC-BY-3.0+)?
ENTRY_LICENSE_EXPLICIT_DATE = Time.iso8601('2017-02-20T12:00:00Z')
STATUS_CHOICE = %w[? Met Unmet].freeze
STATUS_CHOICE_NA = (STATUS_CHOICE + %w[N/A]).freeze
MIN_SHOULD_LENGTH = 5
MAX_TEXT_LENGTH = 8192 # Arbitrary maximum to reduce abuse
MAX_SHORT_STRING_LENGTH = 254 # Arbitrary maximum to reduce abuse
# All badge level internal names *including* in_progress
# NOTE: If you add a new level, modify compute_tiered_percentage
BADGE_LEVELS = %w[in_progress passing silver gold].freeze
# All badge level internal names that indicate *completion*,
# so COMPLETED_BADGE_LEVELS[0] is 'passing'.
# Note: This is the *internal* lowercase name, e.g., for field names.
# For *printed* names use t("projects.form_early.level.#{level}")
# Note that drop() does NOT mutate the original value.
COMPLETED_BADGE_LEVELS = BADGE_LEVELS.drop(1).freeze
# All badge levels as IDs. Useful for enumerating "all levels" as:
# Project::LEVEL_IDS.each do |level| ... end
LEVEL_ID_NUMBERS = (0..(COMPLETED_BADGE_LEVELS.length - 1)).freeze
LEVEL_IDS = LEVEL_ID_NUMBERS.map(&:to_s)
PROJECT_OTHER_FIELDS = %i[
name description homepage_url repo_url cpe implementation_languages
license general_comments user_id disabled_reminders lock_version
level additional_rights_changes
].freeze
ALL_CRITERIA_STATUS = Criteria.all.map(&:status).freeze
ALL_CRITERIA_JUSTIFICATION = Criteria.all.map(&:justification).freeze
PROJECT_PERMITTED_FIELDS = (PROJECT_OTHER_FIELDS + ALL_CRITERIA_STATUS +
ALL_CRITERIA_JUSTIFICATION).freeze
default_scope { order(:created_at) }
scope :created_since, (
lambda do |time|
where(Project.arel_table[:created_at].gteq(time))
end
)
scope :gteq, (
lambda do |floor|
where(Project.arel_table[:tiered_percentage].gteq(floor.to_i))
end
)
scope :in_progress, -> { lteq(99) }
scope :lteq, (
lambda do |ceiling|
where(Project.arel_table[:tiered_percentage].lteq(ceiling.to_i))
end
)
scope :passing, -> { gteq(100) }
scope :recently_updated, (
lambda do
# The "includes" here isn't ideal.
# Originally we used "eager_load" on :user, but
# "eager_load" forces a load of *all* fields per a bug in Rails:
# https://github.com/rails/rails/issues/15185
# Switching to ".includes" fixes the bug, though it means we do 2
# database queries instead of just one.
# We could use the gem "rails_select_on_includes" to fix this bug:
# https://github.com/alekseyl/rails_select_on_includes
# but that's something of a hack.
# If a totally-cached feed is used, then the development environment
# will complain as follows:
# GET /feed
# AVOID eager loading detected
# Project => [:user]
# Remove from your finder: :includes => [:user]
# However, you *cannot* simply remove the includes, because
# when the feed is *not* completely cached, the code *does* need
# this user data.
limit(50).reorder(updated_at: :desc, id: :asc).includes(:user)
end
)
# prefix query (old search system)
scope :text_search, (
lambda do |text|
start_text = "#{sanitize_sql_like(text)}%"
where(
Project.arel_table[:name].matches(start_text).or(
Project.arel_table[:homepage_url].matches(start_text)
).or(
Project.arel_table[:repo_url].matches(start_text)
)
)
end
)
# Search for exact match on URL
# (home page, repo, and maybe package URL someday)
# We have indexes on each of these columns, so this will be fast.
# We remove trailing space and slash to make it quietly "work as expected".
scope :url_search, (
lambda do |url|
clean_url = url.chomp(' ').chomp('/')
where('homepage_url = ? OR repo_url = ?', clean_url, clean_url)
end
)
# Use PostgreSQL-specific text search mechanism
# There are many options we aren't currently using; for more info, see:
# https://github.com/Casecommons/pg_search
pg_search_scope(
:search_for,
against: %i[name homepage_url repo_url description]
# using: { tsearch: { any_word: true } }
)
scope :updated_since, (
lambda do |time|
where(Project.arel_table[:updated_at].gteq(time))
end
)
# Record information about a project.
# We'll also record previous versions of information:
has_paper_trail
before_save :update_badge_percentages, unless: :skip_callbacks
# A project is associated with a user
belongs_to :user
delegate :name, to: :user, prefix: true # Support "user_name"
delegate :nickname, to: :user, prefix: true # Support "user_nickname"
# For these fields we'll have just simple validation rules.
# We'll rely on Rails' HTML escaping system to counter XSS.
validates :name, length: { maximum: MAX_SHORT_STRING_LENGTH },
text: true
validates :description, length: { maximum: MAX_TEXT_LENGTH },
text: true
validates :license, length: { maximum: MAX_SHORT_STRING_LENGTH },
text: true
validates :general_comments, text: true
# We'll do automated analysis on these URLs, which means we will *download*
# from URLs provided by untrusted users. Thus we'll add additional
# URL restrictions to counter tricks like http://ACCOUNT:PASSWORD@host...
# and http://something/?arbitrary_parameters
validates :repo_url, url: true, length: { maximum: MAX_SHORT_STRING_LENGTH },
uniqueness: { allow_blank: true }
validates :homepage_url,
url: true,
length: { maximum: MAX_SHORT_STRING_LENGTH }
validate :need_a_base_url
# Comma-separated list. This is very generous in what characters it
# allows in a programming language name, but restricts it to ASCII and omits
# problematic characters that are very unlikely in a name like
# <, >, &, ", brackets, and braces. This handles language names like
# JavaScript, C++, C#, D-, and PL/I. A space is optional after a comma.
# We have to allow embedded spaces, e.g., "Jupyter Notebook".
VALID_LANGUAGE_LIST =
%r{\A(|-| ([A-Za-z0-9!\#$%'()*+.\/\:;=?@\[\]^~ -]+
(,\ ?[A-Za-z0-9!\#$%'()*+.\/\:;=?@\[\]^~ -]+)*))\Z}x.freeze
validates :implementation_languages,
length: { maximum: MAX_SHORT_STRING_LENGTH },
format: {
with: VALID_LANGUAGE_LIST,
message: :comma_separated_list
}
validates :cpe,
length: { maximum: MAX_SHORT_STRING_LENGTH },
format: {
with: /\A(cpe:.*)?\Z/,
message: :begin_with_cpe
}
validates :user_id, presence: true
Criteria.each_value do |criteria|
criteria.each_value do |criterion|
if criterion.na_allowed?
validates criterion.name.status, inclusion: { in: STATUS_CHOICE_NA }
else
validates criterion.name.status, inclusion: { in: STATUS_CHOICE }
end
validates criterion.name.justification,
length: { maximum: MAX_TEXT_LENGTH },
text: true
end
end
# Return a string representing the additional rights on this project.
# Currently it's just a (possibly empty) list of user ids from
# AdditionalRight. If AdditionalRights gains different kinds of rights
# (e.g., to spec additional owners), this method will need to be tweaked.
def additional_rights_to_s
# "distinct" shouldn't be needed; it's purely defensive here
list = AdditionalRight.where(project_id: id).distinct.pluck(:user_id)
list.sort.to_s # Use list.sort.to_s[1..-2] to remove surrounding [ and ]
end
# Return string representing badge level; assumes tiered_percentage correct.
# This returns 'in_progress' if we aren't passing yet.
# See method badge_level if you want 'in_progress' for < 100.
# See method badge_value if you want the specific percentage for in_progress.
def badge_level
# This is *integer* division, so it truncates.
BADGE_LEVELS[tiered_percentage / 100]
end
def calculate_badge_percentage(level)
active = Criteria.active(level)
met = active.count { |criterion| enough?(criterion) }
to_percentage met, active.size
end
# Does this contain a URL *anywhere* in the (justification) text?
# Note: This regex needs to be logically the same as the one used in the
# client-side badge calculation, or it may confuse some users.
# See app/assets/javascripts/*.js function "containsURL".
#
# Note that we do NOT need to validate these URLs, because the BadgeApp
# 1. escapes these (as part of normal processing) against XSS attacks, and
# 2. does not traverse these URLs in its automated processing.
# Thus, this rule is intentionally *not* strict at all. Contrast this
# with the intentionally strict validation of the project and repo URLs,
# which *are* traversed by BadgeApp and thus need to be much more strict.
#
def contains_url?(text)
return false if !text || text.start_with?('// ')
text =~ %r{https?://[^ ]{5}}
end
# Returns a symbol indicating a the status of an particular criterion
# in a project. These are:
# :criterion_passing -
# 'Met' (or 'N/A' if applicable) has been selected for the criterion
# and all requred justification text (including url's) have been entered #
# :criterion_failing -
# 'Unmet' has been selected for a MUST criterion'.
# :criterion_barely -
# 'Unmet' has been selected for a SHOULD or SUGGESTED criterion and
# ,if SHOULD, required justification text has been entered.
# :criterion_url_required -
# 'Met' has been selected, but a required url in the justification
# text is missing.
# :criterion_justification_required -
# Required justification for 'Met', 'N/A' or 'Unmet' selection is missing.
# :criterion_unknown -
# The criterion has been left at it's default value and thus the status
# is unknown.
# This method is mirrored in assets/project-form.js as getCriterionResult
# If you change this method, change getCriterionResult accordingly.
def get_criterion_result(criterion)
status = self[criterion.name.status]
justification = self[criterion.name.justification]
return :criterion_unknown if status.unknown?
return get_met_result(criterion, justification) if status.met?
return get_unmet_result(criterion, justification) if status.unmet?
get_na_result(criterion, justification)
end
def get_satisfaction_data(level, panel)
total =
Criteria[level].values.select do |criterion|
criterion.major.downcase.delete(' ') == panel
end
passing = total.count { |criterion| enough?(criterion) }
{
text: "#{passing}/#{total.size}",
color: get_color(passing / [1, total.size.to_f].max)
}
end
# Return the badge value: 0..99 (the percent) if in progress,
# else it returns 'passing', 'silver', or 'gold'.
# This presumes that tiered_percentage has already been calculated.
# See method badge_level if you want 'in_progress' for < 100.
def badge_value
if tiered_percentage < 100
tiered_percentage
else
# This is *integer* division, so it truncates.
BADGE_LEVELS[tiered_percentage / 100]
end
end
# Return this project's image src URL for its badge image (SVG).
# * If the project entry has changed relatively recently,
# we give its /badge_static value. That way, the user sees the
# correct result even if the CDN hasn't completed distributing the
# new value or a bad key prevents its update.
# * If the project entry has NOT changed relatively recently,
# we give the /projects/:id/badge value, so that humans who copy the
# values without reading directions are more likely to see the URL that
# we want them to use in READMEs. We also include a comment in the HTML
# view telling people to use the /projects/:id/badge URL, all to encourage
# humans to use the correct URL.
def badge_src_url
if updated_at > 24.hours.ago # Has this entry changed relatively recently?
"/badge_static/#{badge_value}"
else
"/projects/#{id}/badge"
end
end
# Flash a message to update static_analysis if the user is updating
# for the first time since we added met_justification_required that
# criterion
def notify_for_static_analysis?(level)
status = self[Criteria[level][:static_analysis].name.status]
result = get_criterion_result(Criteria[level][:static_analysis])
updated_at < STATIC_ANALYSIS_JUSTIFICATION_REQUIRED_DATE &&
status.met? && result == :criterion_justification_required
end
# Send owner an email they add a new project.
def send_new_project_email
ReportMailer.email_new_project_owner(self).deliver_now
end
# Return true if we should show an explicit license for the data.
# Old entries did not set a license; we only want to show entry licenses
# if the updated_at field indicates there was agreement to it.
def show_entry_license?
updated_at >= ENTRY_LICENSE_EXPLICIT_DATE
end
# Update the badge percentage for a given level (expressed as a number;
# 0=passing), and update relevant event datetime if needed.
# It presumes the lower-level percentages (if relevant) are calculated.
def update_badge_percentage(level, current_time)
old_badge_percentage = self["badge_percentage_#{level}".to_sym]
update_prereqs(level) unless level.to_i.zero?
self["badge_percentage_#{level}".to_sym] =
calculate_badge_percentage(level)
update_passing_times(level, old_badge_percentage, current_time)
end
# Compute the 'tiered percentage' value 0..300. This gives partial credit,
# but only if you've completed a previous level.
def compute_tiered_percentage
if badge_percentage_0 < 100
badge_percentage_0
elsif badge_percentage_1 < 100
badge_percentage_1 + 100
else
badge_percentage_2 + 200
end
end
def update_tiered_percentage
self.tiered_percentage = compute_tiered_percentage
end
# Update the badge percentages for all levels.
def update_badge_percentages
# Create a single datetime value so that they are consistent
current_time = Time.now.utc
Project::LEVEL_IDS.each do |level|
update_badge_percentage(level, current_time)
end
update_tiered_percentage # Update the 'tiered_percentage' number 0..300
end
# Return owning user's name for purposes of display.
def user_display_name
user_name || user_nickname
end
# Update badge percentages for all project entries, and send emails
# to any project where this causes loss or gain of a badge.
# Use this after the badging rules have changed.
# We precalculate and store percentages in the database;
# this speeds up many actions, but it means that a change in the rules
# doesn't automatically change the precalculated values.
# rubocop:disable Metrics/MethodLength
def self.update_all_badge_percentages(levels)
raise TypeError, 'levels must be an Array' unless levels.is_a?(Array)
levels.each do |l|
raise ArgumentError, "Invalid level: #{l}" unless l.in? Criteria.keys
end
Project.skip_callbacks = true
Project.find_each do |project|
project.with_lock do
# Create a single datetime value so that they are consistent
current_time = Time.now.utc
levels.each do |level|
project.update_badge_percentage(level, current_time)
end
project.update_tiered_percentage
project.save!(touch: false)
end
end
Project.skip_callbacks = false
end
# rubocop:enable Metrics/MethodLength
# The following configuration options are trusted. Set them to
# reasonable numbers or accept the defaults.
# Maximum number of reminders to send by email at one time.
# We want a rate limit to avoid being misinterpreted as a spammer,
# and also to limit damage if there's a mistake in the code.
# By default, start very low until we're confident in the code.
MAX_REMINDERS = (ENV['BADGEAPP_MAX_REMINDERS'] || 2).to_i
# Minimum number of days since last lost a badge before sending reminder,
# if it lost one.
LOST_PASSING_REMINDER = (ENV['BADGEAPP_LOST_PASSING_REMINDER'] || 30).to_i
# Minimum number of days since project last updated before sending reminder
LAST_UPDATED_REMINDER = (ENV['BADGEAPP_LAST_UPDATED_REMINDER'] || 30).to_i
# Minimum number of days since project was last sent a reminder
LAST_SENT_REMINDER = (ENV['BADGEAPP_LAST_SENT_REMINDER'] || 60).to_i
# Return which projects should be reminded to work on their badges. See:
# https://github.com/coreinfrastructure/best-practices-badge/issues/487
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def self.projects_to_remind
# This is computed entirely using the ActiveRecord query interface
# as a single select+sort+limit, and not implemented using methods or
# direct SQL commands. Using the ActiveRecord query interface will turn
# this directly into a single database request, which will be blazingly
# fast regardless of the database size (via the indexes). Method
# invocations would be super-slow, and direct SQL commands will be less
# portable than ActiveRecord's interface (which works to paper over
# differences between SQL engines).
#
# Select projects eligible for reminders =
# in_progress and not_recently_lost_badge and not_disabled_reminders
# and inactive and not_recently_reminded and valid_email.
# where these terms are defined as:
# in_progress = badge_percentage less than 100%.
# not_recently_lost_badge = lost_passing_at IS NULL OR
# less than LOST_PASSING_REMINDER (30) days ago
# not_disabled_reminders = not(project.disabled_reminders), default false
# inactive = updated_at is LAST_UPDATED_REMINDER (30) days ago or more
# not_recently_reminded = last_reminder_at IS NULL OR
# more than 60 days ago. Notice that if recently_reminded is null
# (no reminders have been sent), only the other criteria matter.
# valid_email = users.encrypted_email (joined) is not null
# Prioritize. Sort by the last_reminder_at datetime
# (use updated_at if last_reminder_at is null), oldest first.
# Since last_reminder_at gets updated with a newer datetime when
# we send a message, each email we send will lower its reminder
# priority. Thus we will eventually cycle through all inactive projects
# if none of them respond to reminders.
# Use: projects.order("COALESCE(last_reminder_at, updated_at)")
# We cannot check if email includes "@" here, because they are
# encrypted (the database does not have access to the keys, by intent).
#
# The "reorder" below uses "Arel.sql" to work around
# a deprecation warning from Rails 5.2, and
# is not expected to work in Rails 6. The warning is as follows:
# DEPRECATION WARNING: Dangerous query method
# (method whose arguments are used as raw SQL) called with
# non-attribute argument(s): "COALESCE(last_reminder_at,
# projects.updated_at)". Non-attribute arguments will be
# disallowed in Rails 6.0. This method should not be called with
# user-provided values, such as request parameters or model
# attributes. Known-safe values can be passed by wrapping
# them in Arel.sql().
# For now we'll wrap them as required. This is unfortunate; it would
# dangerous if user-provided data was used, but that is not the case.
# We're hoping Rails 6 will give us an alternative construct.
# If not, alternatives include creating a calculated field
# (e.g., one that does the coalescing).
Project
.select('projects.*, users.encrypted_email as user_encrypted_email')
.where('badge_percentage_0 < 100')
.where('lost_passing_at IS NULL OR lost_passing_at < ?',
LOST_PASSING_REMINDER.days.ago)
.where('disabled_reminders = FALSE')
.where('projects.updated_at < ?',
LAST_UPDATED_REMINDER.days.ago)
.where('last_reminder_at IS NULL OR last_reminder_at < ?',
LAST_SENT_REMINDER.days.ago)
.joins(:user).references(:user) # Need this to check email address
.where('user_id IS NOT NULL') # Safety check
.where('users.encrypted_email IS NOT NULL')
.reorder(Arel.sql('COALESCE(last_reminder_at, projects.updated_at)'))
.first(MAX_REMINDERS)
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
# Return which projects should be announced as getting badges in the
# month target_month with level (as a number, 0=passing)
def self.projects_first_in(level, target_month)
name = COMPLETED_BADGE_LEVELS[level] # field name, e.g. 'passing'
# We could omit listing projects which have lost & regained their
# badge by adding this line:
# .where('lost_#{name}_at IS NULL')
# However, it seems reasonable to note projects that have lost their
# badge but have since regained it (especially since it could have
# happened within this month!). After all, we want to encourage
# projects that have lost their badge levels to regain them.
Project
.select("id, name, achieved_#{name}_at")
.where("badge_percentage_#{level} >= 100")
.where("achieved_#{name}_at >= ?", target_month.at_beginning_of_month)
.where("achieved_#{name}_at <= ?", target_month.at_end_of_month)
.reorder("achieved_#{name}_at")
end
def self.recently_reminded
Project
.select('projects.*, users.encrypted_email as user_encrypted_email')
.joins(:user).references(:user) # Need this to check email address
.where('last_reminder_at IS NOT NULL')
.where('last_reminder_at >= ?', 14.days.ago)
.reorder('last_reminder_at')
end
private
# def all_active_criteria_passing?
# Criteria.active.all? { |criterion| enough? criterion }
# end
WHAT_IS_ENOUGH = %i[criterion_passing criterion_barely].freeze
# This method is mirrored in assets/project-form.js as isEnough
# If you change this method, change isEnough accordingly.
def enough?(criterion)
result = get_criterion_result(criterion)
WHAT_IS_ENOUGH.include?(result)
end
# This method is mirrored in assets/project-form.js as getColor
# If you change this method, change getColor accordingly.
def get_color(value)
hue = (value * 120).round
"hsl(#{hue}, 100%, 50%)"
end
# This method is mirrored in assets/project-form.js as getMetResult
# If you change this method, change getMetResult accordingly.
def get_met_result(criterion, justification)
return :criterion_url_required if criterion.met_url_required? &&
!contains_url?(justification)
return :criterion_justification_required if
criterion.met_justification_required? &&
!justification_good?(justification)
:criterion_passing
end
# This method is mirrored in assets/project-form.js as getNAResult
# If you change this method, change getNAResult accordingly.
def get_na_result(criterion, justification)
return :criterion_justification_required if
criterion.na_justification_required? &&
!justification_good?(justification)
:criterion_passing
end
# This method is mirrored in assets/project-form.js as getUnmetResult
# If you change this method, change getUnmetResult accordingly.
def get_unmet_result(criterion, justification)
return :criterion_barely if criterion.suggested? || (criterion.should? &&
justification_good?(justification))
return :criterion_justification_required if criterion.should?
:criterion_failing
end
def justification_good?(justification)
return false if justification.nil? || justification.start_with?('// ')
justification.length >= MIN_SHOULD_LENGTH
end
def need_a_base_url
return unless repo_url.blank? && homepage_url.blank?
errors.add :base, I18n.t('error_messages.need_home_page_or_url')
end
def to_percentage(portion, total)
return 0 if portion.zero?
return 100 if portion >= total
# Give percentage, but only up to 99% (so "100%" always means "complete")
# The tertiary operator is clearer & faster than using [...].min
result = ((portion * 100.0) / total).round
result > 99 ? 99 : result
end
# Update achieved_..._at & lost_..._at fields given level as number
# rubocop:disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def update_passing_times(level, old_badge_percentage, current_time)
level_name = COMPLETED_BADGE_LEVELS[level.to_i] # E.g., 'passing'
current_percentage = self["badge_percentage_#{level}".to_sym]
# If something is wrong, don't modify anything!
return if current_percentage.blank? || old_badge_percentage.blank?
current_percentage_i = current_percentage.to_i
old_badge_percentage_i = old_badge_percentage.to_i
if current_percentage_i >= 100 && old_badge_percentage_i < 100
self["achieved_#{level_name}_at".to_sym] = current_time
first_achieved_field = "first_achieved_#{level_name}_at".to_sym
if self[first_achieved_field].blank? # First time? Set that too!
self[first_achieved_field] = current_time
end
elsif current_percentage_i < 100 && old_badge_percentage_i >= 100
self["lost_#{level_name}_at".to_sym] = current_time
end
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
# rubocop:enable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity
# Given numeric level 1+, set the value of
# achieve_{previous_level_name}_status to either Met or Unmet, based on
# the achievement of the *previous* level. This is a simple way to ensure
# that to pass level X when X > 0, you must meet the criteria of level X-1.
# We *only* set the field if it currently has a different value.
# When filling in the prerequisites, we do not fill in the justification
# for them. The justification is only there as it makes implementing this
# portion of the code simpler.
def update_prereqs(level)
level = level.to_i
return if level <= 0
# The following works because BADGE_LEVELS[1] is 'passing', etc:
achieved_previous_level = "achieve_#{BADGE_LEVELS[level]}_status".to_sym
if self["badge_percentage_#{level - 1}".to_sym] >= 100
return if self[achieved_previous_level] == 'Met'
self[achieved_previous_level] = 'Met'
else
return if self[achieved_previous_level] == 'Unmet'
self[achieved_previous_level] = 'Unmet'
end
end
end
# rubocop:enable Metrics/ClassLength
|
require 'lita-cricket'
Gem::Specification.new do |spec|
spec.name = "lita-cricket"
spec.version = Lita::Handlers::Cricket::VERSION
spec.authors = ["Stuart Auld"]
spec.email = ["sja@marsupialmusic.net"]
spec.description = "Provides live cricket scores directly in Lita"
spec.summary = "Live cricket scores! Such wow!"
spec.homepage = "https://github.com/sjauld/lita-cricket"
spec.license = "MIT"
spec.metadata = { "lita_plugin_type" => "handler" }
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "lita", ">= 4.4"
spec.add_runtime_dependency "httparty"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "pry-byebug"
spec.add_development_dependency "rake"
spec.add_development_dependency "rack-test"
spec.add_development_dependency "rspec", ">= 3.0.0"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "coveralls"
end
nice version handling
$:.push File.expand_path('../lib', __FILE__)
require 'lita/lita-cricket'
Gem::Specification.new do |spec|
spec.name = "lita-cricket"
spec.version = Lita::Handlers::Cricket::VERSION
spec.authors = ["Stuart Auld"]
spec.email = ["sja@marsupialmusic.net"]
spec.description = "Provides live cricket scores directly in Lita"
spec.summary = "Live cricket scores! Such wow!"
spec.homepage = "https://github.com/sjauld/lita-cricket"
spec.license = "MIT"
spec.metadata = { "lita_plugin_type" => "handler" }
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "lita", ">= 4.4"
spec.add_runtime_dependency "httparty"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "pry-byebug"
spec.add_development_dependency "rake"
spec.add_development_dependency "rack-test"
spec.add_development_dependency "rspec", ">= 3.0.0"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "coveralls"
end
|
class Project < ActiveRecord::Base
has_many :tasks, as: :taskable
belongs_to :user
alias_attribute :creator, :user
has_many :project_users
has_many :users, through: :project_users
alias_attribute :members, :users
before_save :add_creator_to_members, if: :user_id_changed?
has_many :posts
validates_associated :posts
validates_associated :tasks
validates_associated :project_users
validates :title, presence: true, length: {is: 200}
validates :description, allow_blank: true
validates :priority, presence: true,inclusion: {in: %w(low normal high ASAP)}
validates :status, presence: true
validates_format_of :status,:with => ^[A-Za-z]+$
validates :progress, presence: true, numericality: { only_integer: true }, length: {in: 1..3}
validate :is_valid_date?
validates_datetime :due_date, :after => :started_at
private
def is_valid_date?
if((due_date.is_a?(Date) rescue ArgumentError) == ArgumentError)
errors.add(:due_date, 'Sorry, Invalid Date.')
end
end
def add_creator_to_members
self.members << self.creator
end
end
change status expression
class Project < ActiveRecord::Base
has_many :tasks, as: :taskable
belongs_to :user
alias_attribute :creator, :user
has_many :project_users
has_many :users, through: :project_users
alias_attribute :members, :users
before_save :add_creator_to_members, if: :user_id_changed?
has_many :posts
validates_associated :posts
validates_associated :tasks
validates_associated :project_users
validates :title, presence: true, length: {is: 200}
validates :description, allow_blank: true
validates :priority, presence: true,inclusion: {in: %w(low normal high ASAP)}
validates :status, presence: true
validates_format_of :status,:with => '^[A-Za-z]+$'
validates :progress, presence: true, numericality: { only_integer: true }, length: {in: 1..3}
validate :is_valid_date?
validates_datetime :due_date, :after => :started_at
private
def is_valid_date?
if((due_date.is_a?(Date) rescue ArgumentError) == ArgumentError)
errors.add(:due_date, 'Sorry, Invalid Date.')
end
end
def add_creator_to_members
self.members << self.creator
end
end
|
class Project < ActiveRecord::Base
include Concerns::Elasticsearch
LICENSES = {
cc40_by: {
name: "Creative Commons Attribution 4.0 International",
url: "http://creativecommons.org/licenses/by/4.0/",
logo_url: "https://i.creativecommons.org/l/by/4.0/88x31.png"
},
cc40_by_sa: {
name: "Creative Commons Attribution-ShareAlike 4.0 International",
url: "http://creativecommons.org/licenses/by-sa/4.0/",
logo_url: "https://i.creativecommons.org/l/by-sa/4.0/88x31.png"
},
cc0: {
name: "Creative Commons CC0 1.0 Universal",
url: "https://creativecommons.org/publicdomain/zero/1.0/",
logo_url: "https://licensebuttons.net/l/zero/1.0/88x31.png",
dedication_html: "To the extent possible under copyright law, the author has waived all copyright and related or neighboring rights to this work."
},
mit: {
name: "MIT License",
url: "http://opensource.org/licenses/MIT",
dedication_html: "This work is licensed under an <a href=\"http://opensource.org/licenses/MIT\">MIT License</a>."
},
public_domain: {
name: "Public Domain",
url: "https://creativecommons.org/publicdomain/mark/1.0/",
logo_url: "https://licensebuttons.net/l/publicdomain/88x31.png",
dedication_html: "This work is free of known copyright restrictions."
},
cc40_by_nc: {
name: "Creative Commons Attribution-NonCommercial 4.0 International",
url: "http://creativecommons.org/licenses/by-nc/4.0/",
logo_url: "https://i.creativecommons.org/l/by-nc/4.0/88x31.png",
discouraged: true
},
cc40_by_nc_sa: {
name: "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International",
url: "http://creativecommons.org/licenses/by-nc-sa/4.0/",
logo_url: "https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png",
discouraged: true
}
}
mapping do
indexes :title, :type => 'string', fields: { raw: { type: 'string', index: :not_analyzed } }
indexes :authors, :type => 'string'
indexes :license, :index => :not_analyzed
indexes :description, :type => 'string'
indexes :tag_names, :type => 'string'
indexes :brand_name, :type => 'string'
end
has_many :project_files, dependent: :destroy
has_and_belongs_to_many :tags
belongs_to :brand
validates :license, inclusion: { in: LICENSES.keys.map(&:to_s) }
validates :brand, presence: true
self.per_page = 10
def tag_names
tags.map(&:name)
end
def tag_names=(new_tag_names)
new_tag_names = new_tag_names.reject(&:blank?)
existing_tag_names = tag_names
removed_tags = tags.where(name: (existing_tag_names - new_tag_names))
self.tags.delete(removed_tags)
(new_tag_names - existing_tag_names).each do |new_tag_name|
tag = Tag.find_or_create_by(name: new_tag_name)
self.tags << tag
end
end
def license_object
OpenStruct.new(LICENSES[license.to_sym]) if license.present?
end
def as_indexed_json(options={})
{
title: title,
authors: authors,
license: license,
description: description,
tag_names: tag_names,
brand_name: brand.try(:name)
}.as_json
end
def to_param
if title
"#{id}-#{title.parameterize}"
else
id
end
end
end
Strip 'a', 'an', and 'the' from the start of titles for sorting
class Project < ActiveRecord::Base
include Concerns::Elasticsearch
LICENSES = {
cc40_by: {
name: "Creative Commons Attribution 4.0 International",
url: "http://creativecommons.org/licenses/by/4.0/",
logo_url: "https://i.creativecommons.org/l/by/4.0/88x31.png"
},
cc40_by_sa: {
name: "Creative Commons Attribution-ShareAlike 4.0 International",
url: "http://creativecommons.org/licenses/by-sa/4.0/",
logo_url: "https://i.creativecommons.org/l/by-sa/4.0/88x31.png"
},
cc0: {
name: "Creative Commons CC0 1.0 Universal",
url: "https://creativecommons.org/publicdomain/zero/1.0/",
logo_url: "https://licensebuttons.net/l/zero/1.0/88x31.png",
dedication_html: "To the extent possible under copyright law, the author has waived all copyright and related or neighboring rights to this work."
},
mit: {
name: "MIT License",
url: "http://opensource.org/licenses/MIT",
dedication_html: "This work is licensed under an <a href=\"http://opensource.org/licenses/MIT\">MIT License</a>."
},
public_domain: {
name: "Public Domain",
url: "https://creativecommons.org/publicdomain/mark/1.0/",
logo_url: "https://licensebuttons.net/l/publicdomain/88x31.png",
dedication_html: "This work is free of known copyright restrictions."
},
cc40_by_nc: {
name: "Creative Commons Attribution-NonCommercial 4.0 International",
url: "http://creativecommons.org/licenses/by-nc/4.0/",
logo_url: "https://i.creativecommons.org/l/by-nc/4.0/88x31.png",
discouraged: true
},
cc40_by_nc_sa: {
name: "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International",
url: "http://creativecommons.org/licenses/by-nc-sa/4.0/",
logo_url: "https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png",
discouraged: true
}
}
mapping do
indexes :title, :type => 'string', fields: { raw: { type: 'string', index: :not_analyzed } }
indexes :authors, :type => 'string'
indexes :license, :index => :not_analyzed
indexes :description, :type => 'string'
indexes :tag_names, :type => 'string'
indexes :brand_name, :type => 'string'
end
has_many :project_files, dependent: :destroy
has_and_belongs_to_many :tags
belongs_to :brand
validates :license, inclusion: { in: LICENSES.keys.map(&:to_s) }
validates :brand, presence: true
self.per_page = 10
def tag_names
tags.map(&:name)
end
def tag_names=(new_tag_names)
new_tag_names = new_tag_names.reject(&:blank?)
existing_tag_names = tag_names
removed_tags = tags.where(name: (existing_tag_names - new_tag_names))
self.tags.delete(removed_tags)
(new_tag_names - existing_tag_names).each do |new_tag_name|
tag = Tag.find_or_create_by(name: new_tag_name)
self.tags << tag
end
end
def license_object
OpenStruct.new(LICENSES[license.to_sym]) if license.present?
end
# Remove leading "A", "An", and "The" from titles
def title_for_search
title.strip.sub(/\Athe\s+/i, '').sub(/\Aan?\s+/i, '')
end
def as_indexed_json(options={})
{
title: title_for_search,
authors: authors,
license: license,
description: description,
tag_names: tag_names,
brand_name: brand.try(:name)
}.as_json
end
def to_param
if title
"#{id}-#{title.parameterize}"
else
id
end
end
end
|
class Project < ActiveRecord::Base
belongs_to :classroom
attr_accessor :auto_assign
has_many :assignments, :dependent => :destroy
has_many :users, :through => :assignments
after_create :assign, :if => Proc.new {|u| u.auto_assign and u.classroom_id.present? }
def assign(assignees = classroom.users.student)
ActiveRecord::Base.transaction do
assignees.each do |u|
assignments.create(:user => u)
end
end
end
end
Assign to all class members, incl. Admin, Teacher
class Project < ActiveRecord::Base
belongs_to :classroom
attr_accessor :auto_assign
has_many :assignments, :dependent => :destroy
has_many :users, :through => :assignments
after_create :assign, :if => Proc.new {|u| u.auto_assign and u.classroom_id.present? }
def assign(assignees = classroom.users)
ActiveRecord::Base.transaction do
assignees.each do |u|
assignments.create(:user => u)
end
end
end
end
|
class Project < ActiveRecord::Base
include Searchable
validates_presence_of :name, :platform
# validate unique name and platform (case?)
has_many :versions
has_many :dependencies, -> { group 'project_name' }, through: :versions
belongs_to :github_repository
scope :platform, ->(platform) { where('lower(platform) = ?', platform.downcase) }
scope :with_homepage, -> { where("homepage <> ''") }
scope :with_repository_url, -> { where("repository_url <> ''") }
scope :without_repository_url, -> { where("repository_url IS ? OR repository_url = ''", nil) }
scope :with_repo, -> { includes(:github_repository).where('github_repositories.id IS NOT NULL') }
scope :without_repo, -> { where(github_repository_id: nil) }
scope :with_github_url, -> { where('repository_url ILIKE ?', '%github.com%') }
before_save :normalize_licenses
after_create :update_github_repo
def to_param
{ name: name, platform: platform.downcase }
end
def to_s
name
end
def latest_version
@latest_version ||= versions.to_a.sort.first
end
def owner
return nil unless github_repository
GithubUser.find_by_login github_repository.owner_name
end
def platform_class
"Repositories::#{platform}".constantize
end
def color
Languages::Language[language].try(:color) || platform_class.color
end
def mlt
begin
results = Project.__elasticsearch__.client.mlt(id: self.id, index: 'projects', type: 'project', mlt_fields: 'keywords,platform,description,repository_url', min_term_freq: 1, min_doc_freq: 2)
ids = results['hits']['hits'].map{|h| h['_id']}
Project.where(id: ids)
rescue
[]
end
end
def stars
github_repository.try(:stargazers_count) || 0
end
def language
github_repository.try(:language)
end
def description
if platform == 'Go'
github_repository.try(:description).presence || read_attribute(:description)
else
read_attribute(:description).presence || github_repository.try(:description)
end
end
def homepage
read_attribute(:homepage).presence || github_repository.try(:homepage)
end
def dependents
Dependency.where(platform: platform, project_name: name)
end
def dependent_projects
dependents.includes(:version => :project).map(&:version).map(&:project).uniq
end
def self.undownloaded_repos
with_github_url.without_repo
end
def self.license(license)
where('? = ANY("normalized_licenses")', license)
end
def self.language(language)
joins(:github_repository).where('github_repositories.language ILIKE ?', language)
end
def self.popular_languages(options = {})
search('*', options).response.facets[:languages][:terms]
end
def self.popular_platforms(options = {})
search('*', options).response.facets[:platforms][:terms]
end
def self.popular_licenses(options = {})
search('*', options).response.facets[:licenses][:terms].reject{ |t| t.term == 'Other' }
end
def self.popular(options = {})
search('*', options.merge(sort: 'stars', order: 'desc')).records.reject{|p| p.github_repository.nil? }
end
def normalize_licenses
if licenses.blank?
normalized = []
elsif licenses.length > 150
normalized = ['Other']
else
normalized = licenses.split(',').map do |license|
Spdx.find(license).try(:id)
end.compact
normalized = ['Other'] if normalized.empty?
end
self.normalized_licenses = normalized
end
def update_github_repo
name_with_owner = github_name_with_owner
if name_with_owner
puts name_with_owner
else
puts repository_url
return false
end
begin
r = AuthToken.client.repo(name_with_owner).to_hash
return false if r.nil? || r.empty?
g = GithubRepository.find_or_initialize_by(r.slice(:full_name))
g.owner_id = r[:owner][:id]
g.assign_attributes r.slice(*GithubRepository::API_FIELDS)
g.save
self.github_repository_id = g.id
self.save
rescue Octokit::NotFound, Octokit::Forbidden => e
begin
response = Net::HTTP.get_response(URI(github_url))
if response.code.to_i == 301
self.repository_url = URI(response['location']).to_s
update_github_repo
end
rescue URI::InvalidURIError => e
p e
end
end
end
def github_url
return nil if repository_url.blank? || github_name_with_owner.blank?
"https://github.com/#{github_name_with_owner}"
end
def github_name_with_owner
GithubRepository.extract_full_name repository_url
end
end
Limit related projects to 5 for now
class Project < ActiveRecord::Base
include Searchable
validates_presence_of :name, :platform
# validate unique name and platform (case?)
has_many :versions
has_many :dependencies, -> { group 'project_name' }, through: :versions
belongs_to :github_repository
scope :platform, ->(platform) { where('lower(platform) = ?', platform.downcase) }
scope :with_homepage, -> { where("homepage <> ''") }
scope :with_repository_url, -> { where("repository_url <> ''") }
scope :without_repository_url, -> { where("repository_url IS ? OR repository_url = ''", nil) }
scope :with_repo, -> { includes(:github_repository).where('github_repositories.id IS NOT NULL') }
scope :without_repo, -> { where(github_repository_id: nil) }
scope :with_github_url, -> { where('repository_url ILIKE ?', '%github.com%') }
before_save :normalize_licenses
after_create :update_github_repo
def to_param
{ name: name, platform: platform.downcase }
end
def to_s
name
end
def latest_version
@latest_version ||= versions.to_a.sort.first
end
def owner
return nil unless github_repository
GithubUser.find_by_login github_repository.owner_name
end
def platform_class
"Repositories::#{platform}".constantize
end
def color
Languages::Language[language].try(:color) || platform_class.color
end
def mlt
begin
results = Project.__elasticsearch__.client.mlt(id: self.id, index: 'projects', type: 'project', mlt_fields: 'keywords,platform,description,repository_url', min_term_freq: 1, min_doc_freq: 2)
ids = results['hits']['hits'].map{|h| h['_id']}
Project.where(id: ids).limit(5).includes(:versions)
rescue
[]
end
end
def stars
github_repository.try(:stargazers_count) || 0
end
def language
github_repository.try(:language)
end
def description
if platform == 'Go'
github_repository.try(:description).presence || read_attribute(:description)
else
read_attribute(:description).presence || github_repository.try(:description)
end
end
def homepage
read_attribute(:homepage).presence || github_repository.try(:homepage)
end
def dependents
Dependency.where(platform: platform, project_name: name)
end
def dependent_projects
dependents.includes(:version => :project).map(&:version).map(&:project).uniq
end
def self.undownloaded_repos
with_github_url.without_repo
end
def self.license(license)
where('? = ANY("normalized_licenses")', license)
end
def self.language(language)
joins(:github_repository).where('github_repositories.language ILIKE ?', language)
end
def self.popular_languages(options = {})
search('*', options).response.facets[:languages][:terms]
end
def self.popular_platforms(options = {})
search('*', options).response.facets[:platforms][:terms]
end
def self.popular_licenses(options = {})
search('*', options).response.facets[:licenses][:terms].reject{ |t| t.term == 'Other' }
end
def self.popular(options = {})
search('*', options.merge(sort: 'stars', order: 'desc')).records.reject{|p| p.github_repository.nil? }
end
def normalize_licenses
if licenses.blank?
normalized = []
elsif licenses.length > 150
normalized = ['Other']
else
normalized = licenses.split(',').map do |license|
Spdx.find(license).try(:id)
end.compact
normalized = ['Other'] if normalized.empty?
end
self.normalized_licenses = normalized
end
def update_github_repo
name_with_owner = github_name_with_owner
if name_with_owner
puts name_with_owner
else
puts repository_url
return false
end
begin
r = AuthToken.client.repo(name_with_owner).to_hash
return false if r.nil? || r.empty?
g = GithubRepository.find_or_initialize_by(r.slice(:full_name))
g.owner_id = r[:owner][:id]
g.assign_attributes r.slice(*GithubRepository::API_FIELDS)
g.save
self.github_repository_id = g.id
self.save
rescue Octokit::NotFound, Octokit::Forbidden => e
begin
response = Net::HTTP.get_response(URI(github_url))
if response.code.to_i == 301
self.repository_url = URI(response['location']).to_s
update_github_repo
end
rescue URI::InvalidURIError => e
p e
end
end
end
def github_url
return nil if repository_url.blank? || github_name_with_owner.blank?
"https://github.com/#{github_name_with_owner}"
end
def github_name_with_owner
GithubRepository.extract_full_name repository_url
end
end
|
class Project < ActiveRecord::Base
has_and_belongs_to_many :admins, :class_name => "User", :join_table => "project_admins", inverse_of: :projects
has_many :workunits
validates :admins, presence: true
end
compute the total number of hours
class Project < ActiveRecord::Base
has_and_belongs_to_many :admins, :class_name => "User", :join_table => "project_admins", inverse_of: :projects
has_many :workunits
validates :admins, presence: true
def total_hours
return self.workunits.reject{|w| !w.confirmed}.map{|w| w.duration}.reduce(:+)
end
def admin_names
names = self.admins.map{|a| a.email}
return names.join(", ")
end
end
|
class Project < ApplicationRecord
has_many :project_teams, dependent: :destroy
has_many :team_members, through: :project_teams, source: :user
has_many :tasks, dependent: :destroy
validates_presence_of :title, :description, :due_date
validate :due_date_cannot_be_in_the_past, on: :create
def tasks_attributes=(tasks_attributes)
tasks_attributes.delete_if { |_i, h| h.any? { |_k, v| v.empty? } }
tasks_attributes.values.each { |task| tasks.build(task) }
end
def due_date_cannot_be_in_the_past
errors.add(:due_date, "can't be in the past") if due_date.present? && due_date < Date.today
end
def team_member?(user)
team_members.include?(user)
end
def completed?
if completed
true
elsif !completed && tasks.all?(&:completed?)
true && update(completed: true)
else
false
end
end
end
refactored project.completed?
class Project < ApplicationRecord
has_many :project_teams, dependent: :destroy
has_many :team_members, through: :project_teams, source: :user
has_many :tasks, dependent: :destroy
validates_presence_of :title, :description, :due_date
validate :due_date_cannot_be_in_the_past, on: :create
def tasks_attributes=(tasks_attributes)
tasks_attributes.delete_if { |_i, h| h.any? { |_k, v| v.empty? } }
tasks_attributes.values.each { |task| tasks.build(task) }
end
def due_date_cannot_be_in_the_past
errors.add(:due_date, "can't be in the past") if due_date.present? && due_date < Date.today
end
def team_member?(user)
team_members.include?(user)
end
def completed?
return true if completed
return true && update(completed: true) if !completed && tasks.all?(&:completed?)
false
end
end
|
class Project < ActiveRecord::Base
include ApplicationHelper
include AnnotationsHelper
DOWNLOADS_PATH = "/downloads/"
before_validation :cleanup_namespaces
after_validation :user_presence
serialize :namespaces
belongs_to :user
has_and_belongs_to_many :docs,
:after_add => [:increment_docs_counter, :update_annotations_updated_at, :increment_docs_projects_counter, :update_delta_index],
:after_remove => [:decrement_docs_counter, :update_annotations_updated_at, :decrement_docs_projects_counter, :update_delta_index]
has_and_belongs_to_many :pmdocs, :join_table => :docs_projects, :class_name => 'Doc', :conditions => {:sourcedb => 'PubMed'}
has_and_belongs_to_many :pmcdocs, :join_table => :docs_projects, :class_name => 'Doc', :conditions => {:sourcedb => 'PMC', :serial => 0}
# Project to Proejct associations
# parent project => associate projects = @project.associate_projects
has_and_belongs_to_many :associate_projects,
:foreign_key => 'project_id',
:association_foreign_key => 'associate_project_id',
:join_table => 'associate_projects_projects',
:class_name => 'Project',
:before_add => :increment_pending_associate_projects_count,
:after_add => [:increment_counters, :copy_associate_project_relational_models],
:after_remove => :decrement_counters
# associate projects => parent projects = @project.projects
has_and_belongs_to_many :projects,
:foreign_key => 'associate_project_id',
:association_foreign_key => 'project_id',
:join_table => 'associate_projects_projects'
attr_accessible :name, :description, :author, :license, :status, :accessibility, :reference, :sample, :viewer, :editor, :rdfwriter, :xmlwriter, :bionlpwriter, :annotations_zip_downloadable, :namespaces, :process
has_many :denotations, :dependent => :destroy, after_add: :update_updated_at
has_many :relations, :dependent => :destroy, after_add: :update_updated_at
has_many :modifications, :dependent => :destroy, after_add: :update_updated_at
has_many :associate_maintainers, :dependent => :destroy
has_many :associate_maintainer_users, :through => :associate_maintainers, :source => :user, :class_name => 'User'
has_many :notices, dependent: :destroy
validates :name, :presence => true, :length => {:minimum => 5, :maximum => 30}, uniqueness: true
default_scope where(:type => nil)
scope :public, where(accessibility: 1)
scope :for_index, where('accessibility = 1 AND status < 4')
scope :accessible, -> (current_user) {
if current_user.present?
if current_user.root?
else
includes(:associate_maintainers).where('projects.accessibility = ? OR projects.user_id =? OR associate_maintainers.user_id =?', 1, current_user.id, current_user.id)
end
else
where(accessibility: 1)
end
}
scope :editable, -> (current_user) {
if current_user.present?
if current_user.root?
else
includes(:associate_maintainers).where('projects.user_id =? OR associate_maintainers.user_id =?', current_user.id, current_user.id)
end
else
where(accessibility: 10)
end
}
# scope for home#index
scope :top, order('status ASC').order('denotations_count DESC').order('projects.updated_at DESC').limit(10)
scope :not_id_in, lambda{|project_ids|
where('projects.id NOT IN (?)', project_ids)
}
scope :id_in, lambda{|project_ids|
where('projects.id IN (?)', project_ids)
}
scope :name_in, -> (project_names) {
where('projects.name IN (?)', project_names) if project_names.present?
}
# scopes for order
scope :order_pmdocs_count,
joins("LEFT OUTER JOIN docs_projects ON docs_projects.project_id = projects.id LEFT OUTER JOIN docs ON docs.id = docs_projects.doc_id AND docs.sourcedb = 'PubMed'").
group('projects.id').
order("count(docs.id) DESC")
scope :order_pmcdocs_count,
joins("LEFT OUTER JOIN docs_projects ON docs_projects.project_id = projects.id LEFT OUTER JOIN docs ON docs.id = docs_projects.doc_id AND docs.sourcedb = 'PMC'").
group('projects.id').
order("count(docs.id) DESC")
scope :order_denotations_count,
joins('LEFT OUTER JOIN denotations ON denotations.project_id = projects.id').
group('projects.id').
order("count(denotations.id) DESC")
scope :order_relations_count,
joins('LEFT OUTER JOIN relations ON relations.project_id = projects.id').
group('projects.id').
order('count(relations.id) DESC')
scope :order_author,
order('author ASC')
scope :order_maintainer,
joins('LEFT OUTER JOIN users ON users.id = projects.user_id').
group('projects.id, users.username').
order('users.username ASC')
scope :order_association, lambda{|current_user|
if current_user.present?
joins("LEFT OUTER JOIN associate_maintainers ON projects.id = associate_maintainers.project_id AND associate_maintainers.user_id = #{current_user.id}").
order("CASE WHEN projects.user_id = #{current_user.id} THEN 2 WHEN associate_maintainers.user_id = #{current_user.id} THEN 1 ELSE 0 END DESC")
end
}
# default sort order priority : left > right
DefaultSortArray = [['status', 'ASC'], ['denotations_count', 'DESC'], ['projects.updated_at', 'DESC'], ['name', 'ASC'], ['author', 'ASC'], ['users.username', 'ASC']]
# List of column names ignore case to sort
CaseInsensitiveArray = %w(name author users.username)
LicenseDefault = 'Creative Commons Attribution 3.0 Unported License'
EditorDefault = 'http://textae.pubannotation.org/editor.html?mode=edit'
scope :sort_by_params, -> (sort_order) {
sort_order = sort_order.collect{|s| s.join(' ')}.join(', ')
unscoped.includes(:user).order(sort_order)
}
def public?
accessibility == 1
end
def accessible?(current_user)
self.accessibility == 1 || self.user == current_user || current_user.root?
end
def editable?(current_user)
current_user.present? && (current_user.root? || current_user == user || self.associate_maintainer_users.include?(current_user))
end
def destroyable?(current_user)
current_user.root? || current_user == user
end
def status_text
status_hash = {
1 => I18n.t('activerecord.options.project.status.released'),
2 => I18n.t('activerecord.options.project.status.beta'),
3 => I18n.t('activerecord.options.project.status.developing'),
4 => I18n.t('activerecord.options.project.status.testing')
}
status_hash[self.status]
end
def accessibility_text
accessibility_hash = {
1 => I18n.t('activerecord.options.project.accessibility.public'),
2 => :Private
}
accessibility_hash[self.accessibility]
end
def process_text
process_hash = {
1 => I18n.t('activerecord.options.project.process.manual'),
2 => I18n.t('activerecord.options.project.process.automatic')
}
process_hash[self.process]
end
def self.order_by(projects, order, current_user)
case order
when 'pmdocs_count', 'pmcdocs_count', 'denotations_count', 'relations_count'
projects.accessible(current_user).order("#{order} DESC")
when 'author'
projects.accessible(current_user).order_author
when 'maintainer'
projects.accessible(current_user).order_maintainer
else
# 'association' or nil
projects.accessible(current_user).order_association(current_user)
end
end
# after_add doc
def increment_docs_counter(doc)
if doc.sourcedb == 'PMC' && doc.serial == 0
counter_column = :pmcdocs_count
elsif doc.sourcedb == 'PubMed'
counter_column = :pmdocs_count
end
if counter_column
Project.increment_counter(counter_column, self.id)
if self.projects.present?
self.projects.each do |project|
Project.increment_counter(counter_column, project.id)
end
end
end
end
def update_delta_index(doc)
doc.save
end
def increment_docs_projects_counter(doc)
Doc.increment_counter(:projects_count, doc.id)
end
# after_remove doc
def decrement_docs_counter(doc)
if doc.sourcedb == 'PMC' && doc.serial == 0
counter_column = :pmcdocs_count
elsif doc.sourcedb == 'PubMed'
counter_column = :pmdocs_count
end
if counter_column
Project.decrement_counter(counter_column, self.id)
if self.projects.present?
self.projects.each do |project|
Project.decrement_counter(counter_column, project.id)
end
end
end
end
def decrement_docs_projects_counter(doc)
Doc.decrement_counter(:projects_count, doc.id)
doc.reload
end
def update_annotations_updated_at(doc)
self.update_attribute(:annotations_updated_at, DateTime.now)
end
def associate_maintainers_addable_for?(current_user)
if self.new_record?
true
else
current_user.root? == true || current_user == self.user
end
end
def association_for(current_user)
if current_user.present?
if current_user == self.user
'M'
elsif self.associate_maintainer_users.include?(current_user)
'A'
end
end
end
def build_associate_maintainers(usernames)
if usernames.present?
users = User.where('username IN (?)', usernames)
users = users.uniq if users.present?
users.each do |user|
self.associate_maintainers.build({:user_id => user.id})
end
end
end
def add_associate_projects(params_associate_projects, current_user)
if params_associate_projects.present?
associate_projects_names = Array.new
params_associate_projects[:name].each do |index, name|
associate_projects_names << name
if params_associate_projects[:import].present? && params_associate_projects[:import][index]
project = Project.includes(:associate_projects).find_by_name(name)
associate_projects_accessible = project.associate_projects.accessible(current_user)
# import associate projects which current user accessible
if associate_projects_accessible.present?
associate_project_names = associate_projects_accessible.collect{|associate_project| associate_project.name}
associate_projects_names = associate_projects_names | associate_project_names if associate_project_names.present?
end
end
end
associate_projects = Project.where('name IN (?) AND id NOT IN (?)', associate_projects_names.uniq, associate_project_and_project_ids)
self.associate_projects << associate_projects
end
end
def associate_project_ids
associate_project_ids = associate_projects.present? ? associate_projects.collect{|associate_project| associate_project.id} : []
associate_project_ids.uniq
end
def self_id_and_associate_project_ids
associate_project_ids << self.id if self.id.present?
end
def self_id_and_associate_project_and_project_ids
associate_project_and_project_ids << self.id if self.id.present?
end
def project_ids
project_ids = projects.present? ? projects.collect{|project| project.id} : []
project_ids.uniq
end
def associate_project_and_project_ids
if associate_project_ids.present? || project_ids.present?
associate_project_ids | project_ids
else
[0]
end
end
def associatable_project_ids(current_user)
if self.new_record?
associatable_projects = Project.accessible(current_user)
else
associatable_projects = Project.accessible(current_user).not_id_in(self.self_id_and_associate_project_and_project_ids)
end
associatable_projects.collect{|associatable_projects| associatable_projects.id}
end
# increment counters after add associate projects
def increment_counters(associate_project)
Project.update_counters self.id,
:pmdocs_count => associate_project.pmdocs.count,
:pmcdocs_count => associate_project.pmcdocs.count,
:denotations_count => associate_project.denotations.count,
:relations_count => associate_project.relations.count
end
def increment_pending_associate_projects_count(associate_project)
Project.increment_counter(:pending_associate_projects_count, self.id)
end
def copy_associate_project_relational_models(associate_project)
Project.decrement_counter(:pending_associate_projects_count, self.id)
if associate_project.docs.present?
copy_docs = associate_project.docs - self.docs
copy_docs.each do |doc|
# copy doc
self.docs << doc
end
end
if associate_project.denotations.present?
# copy denotations
associate_project.denotations.each do |denotation|
same_denotation = self.denotations.where(
{
:hid => denotation.hid,
:doc_id => denotation.doc_id,
:begin => denotation.begin,
:end => denotation.end,
:obj => denotation.obj
}
)
if same_denotation.blank?
self.denotations << denotation.dup
end
end
end
if associate_project.relations.present?
associate_project.relations.each do |relation|
same_relation = self.relations.where({
:hid => relation.hid,
:subj_id => relation.subj_id,
:subj_type => relation.subj_type,
:obj_id => relation.obj_id,
:obj_type => relation.obj_type,
:pred => relation.pred
})
if same_relation.blank?
self.relations << relation.dup
end
end
end
end
handle_asynchronously :copy_associate_project_relational_models, :run_at => Proc.new { 1.minutes.from_now }
# decrement counters after delete associate projects
def decrement_counters(associate_project)
Project.update_counters self.id,
:pmdocs_count => - associate_project.pmdocs.count,
:pmcdocs_count => - associate_project.pmcdocs.count,
:denotations_count => - associate_project.denotations.count,
:relations_count => - associate_project.relations.count
end
def get_denotations_count(doc = nil, span = nil)
if doc.nil?
self.denotations_count
else
if span.nil?
doc.denotations.where("denotations.project_id = ?", self.id).count
else
doc.hdenotations(self, span).length
end
end
end
def get_annotations_count(doc = nil, span = nil)
if doc.nil?
self.annotations_count
else
if span.nil?
# begin from the doc because it should be faster.
doc.denotations.where("denotations.project_id = ?", self.id).count + doc.subcatrels.where("relations.project_id = ?", self.id).count + doc.catmods.where("modifications.project_id = ?", self.id).count + doc.subcatrelmods.where("modifications.project_id = ?", self.id).count
else
hdenotations = doc.hdenotations(self, span)
ids = hdenotations.collect{|d| d[:id]}
hrelations = doc.hrelations(self, ids)
ids += hrelations.collect{|d| d[:id]}
hmodifications = doc.hmodifications(self, ids)
hdenotations.size + hrelations.size + hmodifications.size
end
end
end
def annotations_collection(encoding = nil)
if self.docs.present?
self.docs.collect{|doc| doc.set_ascii_body if encoding == 'ascii'; doc.hannotations(self)}
else
[]
end
end
def json
except_columns = %w(pmdocs_count pmcdocs_count pending_associate_projects_count user_id)
to_json(except: except_columns, methods: :maintainer)
end
def docs_list_hash
docs.collect{|doc| doc.to_list_hash} if docs.present?
end
def maintainer
user.present? ? user.username : ''
end
def downloads_system_path
"#{Rails.root}/public#{Project::DOWNLOADS_PATH}"
end
def annotations_zip_filename
"#{self.name.gsub(' ', '_')}-annotations.zip"
end
def annotations_zip_path
"#{Project::DOWNLOADS_PATH}" + self.annotations_zip_filename
end
def annotations_zip_system_path
self.downloads_system_path + self.annotations_zip_filename
end
def create_annotations_zip(encoding = nil)
require 'fileutils'
begin
annotations_collection = self.annotations_collection(encoding)
FileUtils.mkdir_p(self.downloads_system_path) unless Dir.exist?(self.downloads_system_path)
file = File.new(self.annotations_zip_system_path, 'w')
Zip::ZipOutputStream.open(file.path) do |z|
annotations_collection.each do |annotations|
title = get_doc_info(annotations[:target]).sub(/\.$/, '').gsub(' ', '_')
title += ".json" unless title.end_with?(".json")
z.put_next_entry(title)
z.print annotations.to_json
end
end
file.close
self.notices.create({method: "create annotations zip", successful: true})
rescue => e
self.notices.create({method: "create annotations zip", successful: false})
end
end
def get_conversion (annotation, converter, identifier = nil)
RestClient.post converter, annotation.to_json, :content_type => :json do |response, request, result|
case response.code
when 200
response.force_encoding(Encoding::UTF_8)
else
nil
end
end
end
def annotations_rdf_filename
"#{self.name.gsub(' ', '_')}-annotations-rdf.zip"
end
def annotations_rdf_path
"#{Project::DOWNLOADS_PATH}" + self.annotations_rdf_filename
end
def annotations_rdf_system_path
self.downloads_system_path + self.annotations_rdf_filename
end
def create_annotations_rdf(encoding = nil)
begin
ttl = rdfize_docs(self.annotations_collection(encoding), Pubann::Application.config.rdfizer_annotations)
result = create_rdf_zip(ttl)
self.notices.create({method: "create annotations rdf", successful: true})
rescue => e
self.notices.create({method: "create annotations rdf", successful: false})
end
ttl
end
def create_rdf_zip (ttl)
require 'fileutils'
begin
FileUtils.mkdir_p(self.downloads_system_path) unless Dir.exist?(self.downloads_system_path)
file = File.new(self.annotations_rdf_system_path, 'w')
Zip::ZipOutputStream.open(file.path) do |z|
z.put_next_entry(self.name + '.ttl')
z.print ttl
end
file.close
end
end
def index_projects_annotations_rdf
projects = Project.for_index
projects.reject!{|p| p.name =~ /Allie/}
total_number = projects.length
projects.each_with_index do |project, index|
index1 = index + 1
self.notices.create({method:"- annotations rdf index (#{index1}/#{total_number}): #{project.name}"})
begin
index_project_annotations_rdf(project)
self.notices.create({method:"- annotations rdf index (#{index1}/#{total_number}): #{project.name}", successful: true})
rescue => e
self.notices.create({method:"- annotations rdf index (#{index1}/#{total_number}): #{project.name}", successful: false, message: e.message})
end
end
self.notices.create({method: "index projects annotations rdf", successful: true})
end
def index_project_annotations_rdf(project)
begin
rdfize_docs(project.annotations_collection, Pubann::Application.config.rdfizer_annotations, project.name)
self.notices.create({method: "index project annotations rdf: #{project.name}", successful: true})
rescue => e
self.notices.create({method: "index project annotations rdf: #{project.name}", successful: false, message: e.message})
end
end
def index_docs_rdf(docs = nil)
begin
if docs.nil?
projects = Project.for_index
projects.reject!{|p| p.name =~ /Allie/}
docs = projects.inject([]){|sum, p| sum + p.docs}.uniq
end
annotations_collection = docs.collect{|doc| doc.hannotations}
ttl = rdfize_docs(annotations_collection, Pubann::Application.config.rdfizer_spans)
# store_rdf(nil, ttl)
self.notices.create({method: "index docs rdf", successful: true})
rescue => e
self.notices.create({method: "index docs rdf", successful: false, message: e.message})
end
end
def rdfize_docs_backup(annotations_collection, rdfizer, project_name=nil)
ttl = ''
header_length = 0
total_number = annotations_collection.length
annotations_collection.each_with_index do |annotations, i|
index1 = i + 1
doc_description = annotations[:sourcedb] + '-' + annotations[:sourceid]
doc_description += '-' + annotations[:divid].to_s if annotations[:divid]
begin
self.notices.create({method:" - index doc rdf (#{index1}/#{total_number}): #{doc_description}"})
doc_ttl = self.get_conversion(annotations, rdfizer)
if i == 0
doc_ttl.each_line{|l| break unless l.start_with?('@'); header_length += 1}
else
doc_ttl = doc_ttl.split(/\n/)[header_length .. -1].join("\n")
end
doc_ttl += "\n" unless doc_ttl.end_with?("\n")
post_rdf(project_name, doc_ttl)
ttl += doc_ttl
self.notices.create({method:" - index doc rdf (#{index1}/#{total_number}): #{doc_description}", successful: true})
rescue => e
self.notices.create({method:" - index doc rdf (#{index1}/#{total_number}): #{doc_description}", successful: false, message: e.message})
next
end
end
ttl
end
def rdfize_docs(annotations_collection, rdfizer, project_name=nil)
total_number = annotations_collection.length
annotations_collection.each_with_index do |annotations, i|
index1 = i + 1
doc_description = annotations[:sourcedb] + '-' + annotations[:sourceid]
doc_description += '-' + annotations[:divid].to_s if annotations[:divid]
begin
self.notices.create({method:" - index doc rdf (#{index1}/#{total_number}): #{doc_description}"})
doc_ttl = self.get_conversion(annotations, rdfizer)
post_rdf(project_name, doc_ttl)
self.notices.create({method:" - index doc rdf (#{index1}/#{total_number}): #{doc_description}", successful: true})
rescue => e
self.notices.create({method:" - index doc rdf (#{index1}/#{total_number}): #{doc_description}", successful: false, message: e.message})
next
end
end
end
def store_rdf(project_name = nil, ttl)
require 'open3'
ttl_file = Tempfile.new("temporary.ttl")
ttl_file.write(ttl)
ttl_file.close
File.open("docs-spans.ttl", 'w') {|f| f.write(ttl)}
graph_uri = project_name.nil? ? "http://pubannotation.org/docs" : "http://pubannotation.org/projects/#{project_name}"
destination = "#{Pubann::Application.config.sparql_end_point}/sparql-graph-crud-auth?graph-uri=#{graph_uri}"
cmd = %[curl --digest --user #{Pubann::Application.config.sparql_end_point_auth} --verbose --url #{destination} -X PUT -T #{ttl_file.path}]
message, error, state = Open3.capture3(cmd)
ttl_file.unlink
raise IOError, "sparql-graph-crud failed" unless state.success?
end
def post_rdf(project_name = nil, ttl)
require 'open3'
ttl_file = Tempfile.new("temporary.ttl")
ttl_file.write(ttl)
ttl_file.close
graph_uri = project_name.nil? ? "http://pubannotation.org/docs" : "http://pubannotation.org/projects/#{project_name}"
destination = "#{Pubann::Application.config.sparql_end_point}/sparql-graph-crud-auth?graph-uri=#{graph_uri}"
cmd = %[curl --digest --user #{Pubann::Application.config.sparql_end_point_auth} --verbose --url #{destination} -X POST -T #{ttl_file.path}]
message, error, state = Open3.capture3(cmd)
ttl_file.unlink
raise IOError, "sparql-graph-crud failed" unless state.success?
end
def self.params_from_json(json_file)
project_attributes = JSON.parse(File.read(json_file))
user = User.find_by_username(project_attributes['maintainer'])
project_params = project_attributes.select{|key| Project.attr_accessible[:default].include?(key)}
end
def create_annotations_from_zip(zip_file_path, options = {})
begin
files = Zip::ZipFile.open(zip_file_path) do |zip|
zip.collect do |entry|
next if entry.ftype == :directory
next unless entry.name.end_with?('.json')
{name:entry.name, content:entry.get_input_stream.read}
end.delete_if{|e| e.nil?}
end
raise IOError, "No JSON file found" unless files.length > 0
error_files = []
annotations_collection = files.inject([]) do |m, file|
begin
as = JSON.parse(file[:content], symbolize_names:true)
if as.is_a?(Array)
m + as
else
m + [as]
end
rescue => e
error_files << file[:name]
m
end
end
raise IOError, "Invalid JSON files: #{error_files.join(', ')}" unless error_files.empty?
error_anns = []
annotations_collection.each do |annotations|
if annotations[:text].present? && annotations[:sourcedb].present? && annotations[:sourceid].present?
else
error_anns << if annotations[:sourcedb].present? && annotations[:sourceid].present?
"#{annotations[:sourcedb]}:#{annotations[:sourceid]}"
elsif annotations[:text].present?
annotations[:text][0..10] + "..."
else
'???'
end
end
end
raise IOError, "Invalid annotation found. An annotation has to include at least the four components, text, denotation, sourcedb, and sourceid: #{error_anns.join(', ')}" unless error_anns.empty?
error_anns = []
annotations_collection.each do |annotations|
begin
normalize_annotations!(annotations)
rescue => e
error_anns << "#{annotations[:sourcedb]}:#{annotations[:sourceid]}"
end
end
raise IOError, "Invalid annotations: #{error_anns.join(', ')}" unless error_anns.empty?
total_number = annotations_collection.length
interval = (total_number > 100000)? 100 : 10
imported, added, failed, messages = 0, 0, 0, []
annotations_collection.each_with_index do |annotations, i|
begin
self.notices.create({method:"- annotations upload (#{i}/#{total_number} docs)", successful:true, message: "finished"}) if (i != 0) && (i % interval == 0)
i, a, f, m = self.add_doc(annotations[:sourcedb], annotations[:sourceid])
if annotations[:divid].present?
doc = Doc.find_by_sourcedb_and_sourceid_and_serial(annotations[:sourcedb], annotations[:sourceid], annotations[:divid])
else
divs = Doc.find_all_by_sourcedb_and_sourceid(annotations[:sourcedb], annotations[:sourceid])
doc = divs[0] if divs.length == 1
end
result = if doc.present?
self.save_annotations(annotations, doc, options)
elsif divs.present?
self.store_annotations(annotations, divs, options)
else
raise IOError, "document does not exist"
end
rescue => e
self.notices.create({method:"- annotations upload: #{annotations[:sourcedb]}:#{annotations[:sourceid]}", successful:false, message: e.message})
next
end
end
self.notices.create({method:'annotations batch upload', successful:true})
messages << "annotations loaded to #{annotations_collection.length} documents"
rescue => e
self.notices.create({method:'annotations batch upload', successful:false, message: e.message})
end
end
def create_annotations_from_zip_backup(zip_file_path, options)
annotations_collection = Zip::ZipFile.open(zip_file_path) do |zip|
zip.collect{|entry| JSON.parse(entry.get_input_stream.read, symbolize_names:true)}
end
total_number = annotations_collection.length
imported, added, failed, messages = 0, 0, 0, []
annotations_collection.each_with_index do |annotations, index|
docspec = annotations[:divid].present? ? "#{annotations[:sourcedb]}:#{annotations[:sourceid]}-#{annotations[:divid]}" : "#{annotations[:sourcedb]}:#{annotations[:sourceid]}"
self.notices.create({method:"> annotations upload (#{index}/#{total_number}): #{docspec}"})
i, a, f, m = self.add_doc(annotations[:sourcedb], annotations[:sourceid])
imported += i; added += a; failed += f
messages << m if m.present?
serial = annotations[:divid].present? ? annotations[:divid].to_i : 0
doc = Doc.find_by_sourcedb_and_sourceid_and_serial(annotations[:sourcedb], annotations[:sourceid], serial)
result = self.save_annotations(annotations, doc, options)
successful = result.nil? ? false : true
self.notices.create({method:"> annotations upload (#{index}/#{total_number}): #{docspec}", successful:successful})
end
self.notices.create({method:'annotations batch upload', successful:true})
messages << "annotations loaded to #{annotations_collection.length} documents"
end
# def save_annotations(annotations_files)
# annotations_files.each do |annotations_file|
# annotations = JSON.parse(File.read(annotations_file))
# File.unlink(annotations_file)
# serial = annotations[:divid].present? ? annotations[:divid].to_i : 0
# doc = Doc.find_by_sourcedb_and_sourceid_and_serial(annotations[:sourcedb], annotations[:sourceid], serial)
# if doc.present?
# self.save_annotations(annotations, doc)
# end
# end
# end
def self.create_from_zip(zip_file, project_name, current_user)
messages = Array.new
errors = Array.new
unless Dir.exist?(TempFilePath)
FileUtils.mkdir_p(TempFilePath)
end
project_json_file = "#{TempFilePath}#{project_name}-project.json"
docs_json_file = "#{TempFilePath}#{project_name}-docs.json"
doc_annotations_files = Array.new
# open zip file
Zip::ZipFile.open(zip_file) do |zipfile|
zipfile.each do |file|
file_name = file.name
if file_name == 'project.json'
# extract project.json
file.extract(project_json_file) unless File.exist?(project_json_file)
elsif file_name == 'docs.json'
# extract docs.json
file.extract(docs_json_file) unless File.exist?(docs_json_file)
else
# extract sourcedb-sourdeid-serial-section.json
doc_annotations_file = "#{TempFilePath}#{file.name}"
unless File.exist?(doc_annotations_file)
file.extract(doc_annotations_file)
doc_annotations_files << {name: file.name, path: doc_annotations_file}
end
end
end
end
# create project if [project_name]-project.json exist
if File.exist?(project_json_file)
params_from_json = Project.params_from_json(project_json_file)
File.unlink(project_json_file)
project_params = params_from_json
project = Project.new(project_params)
project.user = current_user
if project.valid?
project.save
messages << I18n.t('controllers.shared.successfully_created', model: I18n.t('activerecord.models.project'))
else
errors << project.errors.full_messages.join('<br />')
project = nil
end
end
# create project.docs if [project_name]-docs.json exist
if project.present?
if File.exist?(docs_json_file)
if project.present?
num_created, num_added, num_failed = project.add_docs_from_json(JSON.parse(File.read(docs_json_file), :symbolize_names => true), current_user)
messages << I18n.t('controllers.docs.create_project_docs.created_to_document_set', num_created: num_created, project_name: project.name) if num_created > 0
messages << I18n.t('controllers.docs.create_project_docs.added_to_document_set', num_added: num_added, project_name: project.name) if num_added > 0
messages << I18n.t('controllers.docs.create_project_docs.failed_to_document_set', num_failed: num_failed, project_name: project.name) if num_failed > 0
end
File.unlink(docs_json_file)
end
# save annotations
if doc_annotations_files
delay.save_annotations(project, doc_annotations_files)
messages << I18n.t('controllers.projects.upload_zip.delay_save_annotations')
end
end
return [messages, errors]
end
# def self.save_annotations(project, doc_annotations_files)
# doc_annotations_files.each do |doc_annotations_file|
# doc_info = doc_annotations_file[:name].split('-')
# doc = Doc.find_by_sourcedb_and_sourceid_and_serial(doc_info[0], doc_info[1], doc_info[2])
# doc_params = JSON.parse(File.read(doc_annotations_file[:path]))
# File.unlink(doc_annotations_file[:path])
# if doc.present?
# if doc_params['denotations'].present?
# annotations = {
# denotations: doc_params['denotations'],
# relations: doc_params['relations'],
# text: doc_params['text']
# }
# self.save_annotations(annotations, doc)
# end
# end
# end
# end
def add_docs_from_json(docs, user)
num_created, num_added, num_failed = 0, 0, 0
docs = [docs] if docs.class == Hash
sourcedbs = docs.group_by{|doc| doc[:sourcedb]}
if sourcedbs.present?
sourcedbs.each do |sourcedb, docs_array|
ids = docs_array.collect{|doc| doc[:sourceid]}.join(",")
num_created_t, num_added_t, num_failed_t = self.add_docs({ids: ids, sourcedb: sourcedb, docs_array: docs_array, user: user})
num_created += num_created_t
num_added += num_added_t
num_failed += num_failed_t
end
end
return [num_created, num_added, num_failed]
end
def add_docs2(docspecs)
imported, added, failed, messages = 0, 0, 0, []
docspecs.each do |docspec|
i, a, f, m = self.add_doc(docspec[:sourcedb], docspec[:sourceid])
imported += i; added += a; failed += f;
messages << m if m.present?
end
notices.create({method: "add documents to the project", successful: true, message:"imported:#{imported}, added:#{added}, failed:#{failed}"})
end
def add_docs(options = {})
num_created, num_added, num_failed = 0, 0, 0
ids = options[:ids].split(/[ ,"':|\t\n]+/).collect{|id| id.strip}
ids.each do |sourceid|
divs = Doc.find_all_by_sourcedb_and_sourceid(options[:sourcedb], sourceid)
is_current_users_sourcedb = (options[:sourcedb] =~ /.#{Doc::UserSourcedbSeparator}#{options[:user].username}\Z/).present?
if divs.present?
if is_current_users_sourcedb
# when sourcedb is user's sourcedb
# update or create if not present
options[:docs_array].each do |doc_array|
# find doc sourcedb sourdeid and serial
doc = Doc.find_or_initialize_by_sourcedb_and_sourceid_and_serial(options[:sourcedb], sourceid, doc_array['divid'])
mappings = {
'text' => 'body',
'section' => 'section',
'source_url' => 'source',
'divid' => 'serial'
}
doc_params = Hash[doc_array.map{|key, value| [mappings[key], value]}].select{|key| key.present?}
if doc.new_record?
# when same sourcedb sourceid serial not present
doc.attributes = doc_params
if doc.valid?
# create
doc.save
self.docs << doc unless self.docs.include?(doc)
num_created += 1
else
num_failed += 1
end
else
# when same sourcedb sourceid serial present
# update
if doc.update_attributes(doc_params)
self.docs << doc unless self.docs.include?(doc)
num_added += 1
else
num_failed += 1
end
end
end
else
# when sourcedb is not user's sourcedb
unless self.docs.include?(divs.first)
self.docs << divs
num_added += divs.size
end
end
else
if options[:sourcedb].include?(Doc::UserSourcedbSeparator)
# when sourcedb include :
if is_current_users_sourcedb
# when sourcedb is user's sourcedb
divs, num_failed_user_sourcedb_docs = create_user_sourcedb_docs(docs_array: options[:docs_array])
num_failed += num_failed_user_sourcedb_docs
else
# when sourcedb is not user's sourcedb
num_failed += options[:docs_array].size
end
else
# when sourcedb is not user generated
begin
# when doc_sequencer_ present
doc_sequence = Object.const_get("DocSequencer#{options[:sourcedb]}").new(sourceid)
divs_hash = doc_sequence.divs
divs = Doc.create_divs(divs_hash, :sourcedb => options[:sourcedb], :sourceid => sourceid, :source_url => doc_sequence.source_url)
rescue
# when doc_sequencer_ not present
divs, num_failed_user_sourcedb_docs = create_user_sourcedb_docs({docs_array: options[:docs_array], sourcedb: "#{options[:sourcedb]}#{Doc::UserSourcedbSeparator}#{options[:user].username}"})
num_failed += num_failed_user_sourcedb_docs
end
end
if divs
self.docs << divs
num_created += divs.size
else
num_failed += 1
end
end
end
return [num_created, num_added, num_failed]
end
def add_doc(sourcedb, sourceid)
imported, added, failed, message = 0, 0, 0, ''
begin
divs = Doc.find_all_by_sourcedb_and_sourceid(sourcedb, sourceid)
if divs.present?
if self.docs.include?(divs.first)
raise "The document #{sourcedb}:#{sourceid} already exists."
else
self.docs << divs
added += 1
end
else
divs = Doc.import(sourcedb, sourceid)
if divs.present?
imported += 1
self.docs << divs
added += 1
else
raise "Failed to get the document #{sourcedb}:#{sourceid} from the source."
end
end
if divs.present? and !self.docs.include?(divs.first)
self.docs << divs
added += 1
end
rescue => e
failed += 1
message = e.message
end
[imported, added, failed, message]
end
def create_user_sourcedb_docs(options = {})
divs = []
num_failed = 0
if options[:docs_array].present?
options[:docs_array].each do |doc_array_params|
# all of columns insert into database need to be included in this hash.
doc_array_params[:sourcedb] = options[:sourcedb] if options[:sourcedb].present?
mappings = {
:text => :body,
:sourcedb => :sourcedb,
:sourceid => :sourceid,
:section => :section,
:source_url => :source,
:divid => :serial
}
doc_params = Hash[doc_array_params.map{|key, value| [mappings[key], value]}].select{|key| key.present? && Doc.attr_accessible[:default].include?(key)}
doc = Doc.new(doc_params)
if doc.valid?
doc.save
divs << doc
else
num_failed += 1
end
end
end
return [divs, num_failed]
end
def save_hdenotations(hdenotations, doc)
hdenotations.each do |a|
ca = Denotation.new
ca.hid = a[:id]
ca.begin = a[:span][:begin]
ca.end = a[:span][:end]
ca.obj = a[:obj]
ca.project_id = self.id
ca.doc_id = doc.id
raise ArgumentError, "Invalid representation of denotation: #{ca.hid}" unless ca.save
end
end
def save_hrelations(hrelations, doc)
hrelations.each do |a|
ra = Relation.new
ra.hid = a[:id]
ra.pred = a[:pred]
ra.subj = Denotation.find_by_doc_id_and_project_id_and_hid(doc.id, self.id, a[:subj])
ra.obj = Denotation.find_by_doc_id_and_project_id_and_hid(doc.id, self.id, a[:obj])
ra.project_id = self.id
raise ArgumentError, "Invalid representation of relation: #{ra.hid}" unless ra.save
end
end
def save_hmodifications(hmodifications, doc)
hmodifications.each do |a|
ma = Modification.new
ma.hid = a[:id]
ma.pred = a[:pred]
ma.obj = case a[:obj]
when /^R/
doc.subcatrels.find_by_project_id_and_hid(self.id, a[:obj])
else
Denotation.find_by_doc_id_and_project_id_and_hid(doc.id, self.id, a[:obj])
end
ma.project_id = self.id
raise ArgumentError, "Invalid representatin of modification: #{ma.hid}" unless ma.save
end
end
def save_annotations(annotations, doc, options = nil)
raise ArgumentError, "nil document" unless doc.present?
options ||= {}
doc.destroy_project_annotations(self) unless options.present? && options[:mode] == :addition
if options[:prefix].present?
prefix = options[:prefix]
annotations[:denotations].each {|a| a[:id] = prefix + '_' + a[:id]} if annotations[:denotations].present?
annotations[:relations].each {|a| a[:id] = prefix + '_' + a[:id]; a[:subj] = prefix + '_' + a[:subj]; a[:obj] = prefix + '_' + a[:obj]} if annotations[:relations].present?
annotations[:modifications].each {|a| a[:id] = prefix + '_' + a[:id]; a[:obj] = prefix + '_' + a[:obj]} if annotations[:modifications].present?
end
original_text = annotations[:text]
annotations[:text] = doc.body
if annotations[:denotations].present?
annotations[:denotations] = align_denotations(annotations[:denotations], original_text, annotations[:text])
ActiveRecord::Base.transaction do
self.save_hdenotations(annotations[:denotations], doc)
self.save_hrelations(annotations[:relations], doc) if annotations[:relations].present?
self.save_hmodifications(annotations[:modifications], doc) if annotations[:modifications].present?
end
end
result = annotations.select{|k,v| v.present?}
end
def store_annotations(annotations, divs, options = {})
options ||= {}
successful = true
fit_index = nil
begin
if divs.length == 1
result = self.save_annotations(annotations, divs[0], options)
else
result = []
div_index = divs.collect{|d| [d.serial, d]}.to_h
divs_hash = divs.collect{|d| d.to_hash}
fit_index = TextAlignment.find_divisions(annotations[:text], divs_hash)
fit_index.each do |i|
if i[0] >= 0
ann = {divid:i[0]}
idx = {}
ann[:text] = annotations[:text][i[1][0] ... i[1][1]]
if annotations[:denotations].present?
ann[:denotations] = annotations[:denotations]
.select{|a| a[:span][:begin] >= i[1][0] && a[:span][:end] <= i[1][1]}
.collect{|a| n = a.dup; n[:span] = a[:span].dup; n}
.each{|a| a[:span][:begin] -= i[1][0]; a[:span][:end] -= i[1][0]}
ann[:denotations].each{|a| idx[a[:id]] = true}
end
if annotations[:relations].present?
ann[:relations] = annotations[:relations].select{|a| idx[a[:subj]] && idx[a[:obj]]}
ann[:relations].each{|a| idx[a[:id]] = true}
end
if annotations[:modifications].present?
ann[:modifications] = annotations[:modifications].select{|a| idx[a[:obj]]}
ann[:modifications].each{|a| idx[a[:id]] = true}
end
result << self.save_annotations(ann, div_index[i[0]], options)
end
end
{div_index: fit_index}
end
self.notices.create({method: "annotations upload: #{divs[0].sourcedb}:#{divs[0].sourceid}", successful: successful}) if options[:delayed]
result
rescue => e
self.notices.create({method: "annotations upload: #{divs[0].sourcedb}:#{divs[0].sourceid}", successful: successful}) if options[:delayed]
raise e
end
end
def obtain_annotations(doc, annotation_server_url, options = nil)
annotations = doc.hannotations(self)
annotations = gen_annotations(annotations, annotation_server_url, options)
normalize_annotations!(annotations)
result = self.save_annotations(annotations, doc, options)
end
def obtain_annotations_all_docs(annotation_server_url, options = nil)
docs = self.docs
num_total = docs.length
num_success = 0
docs.each_with_index do |doc, i|
begin
notices.create({method: "obtain annotations (#{i}/#{num_total} docs)", successful:true, message:"finished"})
self.obtain_annotations(doc, annotation_server_url, options)
num_success += 1
rescue => e
notices.create({method: "obtain annotations #{doc.descriptor}", successful: false, message: e.message})
end
end
notices.create({method: 'obtain annotations for all the project documents', successful: num_total == num_success})
end
def user_presence
if user.blank?
errors.add(:user_id, 'is blank')
end
end
def namespaces_base
namespaces.find{|namespace| namespace['prefix'] == '_base'} if namespaces.present?
end
def base_uri
namespaces_base['uri'] if namespaces_base.present?
end
def namespaces_prefixes
namespaces.select{|namespace| namespace['prefix'] != '_base'} if namespaces.present?
end
# delete empty value hashes
def cleanup_namespaces
namespaces.reject!{|namespace| namespace['prefix'].blank? || namespace['uri'].blank?} if namespaces.present?
end
def delete_doc(doc, current_user)
raise RuntimeError, "The project does not include the document." unless self.docs.include?(doc)
doc.destroy_project_annotations(self)
self.docs.delete(doc)
doc.destroy if doc.sourcedb.end_with?("#{Doc::UserSourcedbSeparator}#{current_user.username}") && doc.projects_count == 0
end
def delete_all_docs(current_user)
docs = self.docs
num_total = docs.length
num_success = 0
docs.each_with_index do |doc, i|
begin
notices.create({method: "delete documents (#{i}/#{num_total} docs)", successful:true, message:"finished"}) if (i != 0) && (i % 100 == 0)
delete_doc(doc, current_user)
num_success += 1
rescue => e
notices.create({method: "delete document: #{doc.descriptor}", successful: false, message: e.message})
end
end
successful = if (self.denotations.length + self.relations.length + self.modifications.length == 0)
self.update_attribute(:annotations_count, 0)
self.docs.clear
true
else
false
end
notices.create({method: 'delete all the documents in the project', successful: successful})
end
def destroy_annotations
docs = self.docs
num_total = docs.length
num_success = 0
docs.each_with_index do |doc, i|
begin
notices.create({method: "delete annotations (#{i}/#{num_total} docs)", successful:true, message:"finished"}) if (i != 0) && (i % 100 == 0)
doc.destroy_project_annotations(self)
num_success += 1
rescue => e
notices.create({method: "delete annotations: #{doc.descriptor}", successful: false, message: e.message})
end
end
successful = if (self.denotations.length + self.relations.length + self.modifications.length == 0)
self.update_attribute(:annotations_count, 0)
true
else
false
end
notices.create({method: 'delete all the annotations in the project', successful: successful})
end
def delay_destroy
begin
destroy
rescue
notices.create({method: 'destroy the project', successful: false})
end
end
def update_updated_at(model)
self.update_attribute(:updated_at, DateTime.now)
end
end
REVISED sourcedb specification is not case-sensitive.
class Project < ActiveRecord::Base
include ApplicationHelper
include AnnotationsHelper
DOWNLOADS_PATH = "/downloads/"
before_validation :cleanup_namespaces
after_validation :user_presence
serialize :namespaces
belongs_to :user
has_and_belongs_to_many :docs,
:after_add => [:increment_docs_counter, :update_annotations_updated_at, :increment_docs_projects_counter, :update_delta_index],
:after_remove => [:decrement_docs_counter, :update_annotations_updated_at, :decrement_docs_projects_counter, :update_delta_index]
has_and_belongs_to_many :pmdocs, :join_table => :docs_projects, :class_name => 'Doc', :conditions => {:sourcedb => 'PubMed'}
has_and_belongs_to_many :pmcdocs, :join_table => :docs_projects, :class_name => 'Doc', :conditions => {:sourcedb => 'PMC', :serial => 0}
# Project to Proejct associations
# parent project => associate projects = @project.associate_projects
has_and_belongs_to_many :associate_projects,
:foreign_key => 'project_id',
:association_foreign_key => 'associate_project_id',
:join_table => 'associate_projects_projects',
:class_name => 'Project',
:before_add => :increment_pending_associate_projects_count,
:after_add => [:increment_counters, :copy_associate_project_relational_models],
:after_remove => :decrement_counters
# associate projects => parent projects = @project.projects
has_and_belongs_to_many :projects,
:foreign_key => 'associate_project_id',
:association_foreign_key => 'project_id',
:join_table => 'associate_projects_projects'
attr_accessible :name, :description, :author, :license, :status, :accessibility, :reference, :sample, :viewer, :editor, :rdfwriter, :xmlwriter, :bionlpwriter, :annotations_zip_downloadable, :namespaces, :process
has_many :denotations, :dependent => :destroy, after_add: :update_updated_at
has_many :relations, :dependent => :destroy, after_add: :update_updated_at
has_many :modifications, :dependent => :destroy, after_add: :update_updated_at
has_many :associate_maintainers, :dependent => :destroy
has_many :associate_maintainer_users, :through => :associate_maintainers, :source => :user, :class_name => 'User'
has_many :notices, dependent: :destroy
validates :name, :presence => true, :length => {:minimum => 5, :maximum => 30}, uniqueness: true
default_scope where(:type => nil)
scope :public, where(accessibility: 1)
scope :for_index, where('accessibility = 1 AND status < 4')
scope :accessible, -> (current_user) {
if current_user.present?
if current_user.root?
else
includes(:associate_maintainers).where('projects.accessibility = ? OR projects.user_id =? OR associate_maintainers.user_id =?', 1, current_user.id, current_user.id)
end
else
where(accessibility: 1)
end
}
scope :editable, -> (current_user) {
if current_user.present?
if current_user.root?
else
includes(:associate_maintainers).where('projects.user_id =? OR associate_maintainers.user_id =?', current_user.id, current_user.id)
end
else
where(accessibility: 10)
end
}
# scope for home#index
scope :top, order('status ASC').order('denotations_count DESC').order('projects.updated_at DESC').limit(10)
scope :not_id_in, lambda{|project_ids|
where('projects.id NOT IN (?)', project_ids)
}
scope :id_in, lambda{|project_ids|
where('projects.id IN (?)', project_ids)
}
scope :name_in, -> (project_names) {
where('projects.name IN (?)', project_names) if project_names.present?
}
# scopes for order
scope :order_pmdocs_count,
joins("LEFT OUTER JOIN docs_projects ON docs_projects.project_id = projects.id LEFT OUTER JOIN docs ON docs.id = docs_projects.doc_id AND docs.sourcedb = 'PubMed'").
group('projects.id').
order("count(docs.id) DESC")
scope :order_pmcdocs_count,
joins("LEFT OUTER JOIN docs_projects ON docs_projects.project_id = projects.id LEFT OUTER JOIN docs ON docs.id = docs_projects.doc_id AND docs.sourcedb = 'PMC'").
group('projects.id').
order("count(docs.id) DESC")
scope :order_denotations_count,
joins('LEFT OUTER JOIN denotations ON denotations.project_id = projects.id').
group('projects.id').
order("count(denotations.id) DESC")
scope :order_relations_count,
joins('LEFT OUTER JOIN relations ON relations.project_id = projects.id').
group('projects.id').
order('count(relations.id) DESC')
scope :order_author,
order('author ASC')
scope :order_maintainer,
joins('LEFT OUTER JOIN users ON users.id = projects.user_id').
group('projects.id, users.username').
order('users.username ASC')
scope :order_association, lambda{|current_user|
if current_user.present?
joins("LEFT OUTER JOIN associate_maintainers ON projects.id = associate_maintainers.project_id AND associate_maintainers.user_id = #{current_user.id}").
order("CASE WHEN projects.user_id = #{current_user.id} THEN 2 WHEN associate_maintainers.user_id = #{current_user.id} THEN 1 ELSE 0 END DESC")
end
}
# default sort order priority : left > right
DefaultSortArray = [['status', 'ASC'], ['denotations_count', 'DESC'], ['projects.updated_at', 'DESC'], ['name', 'ASC'], ['author', 'ASC'], ['users.username', 'ASC']]
# List of column names ignore case to sort
CaseInsensitiveArray = %w(name author users.username)
LicenseDefault = 'Creative Commons Attribution 3.0 Unported License'
EditorDefault = 'http://textae.pubannotation.org/editor.html?mode=edit'
scope :sort_by_params, -> (sort_order) {
sort_order = sort_order.collect{|s| s.join(' ')}.join(', ')
unscoped.includes(:user).order(sort_order)
}
def public?
accessibility == 1
end
def accessible?(current_user)
self.accessibility == 1 || self.user == current_user || current_user.root?
end
def editable?(current_user)
current_user.present? && (current_user.root? || current_user == user || self.associate_maintainer_users.include?(current_user))
end
def destroyable?(current_user)
current_user.root? || current_user == user
end
def status_text
status_hash = {
1 => I18n.t('activerecord.options.project.status.released'),
2 => I18n.t('activerecord.options.project.status.beta'),
3 => I18n.t('activerecord.options.project.status.developing'),
4 => I18n.t('activerecord.options.project.status.testing')
}
status_hash[self.status]
end
def accessibility_text
accessibility_hash = {
1 => I18n.t('activerecord.options.project.accessibility.public'),
2 => :Private
}
accessibility_hash[self.accessibility]
end
def process_text
process_hash = {
1 => I18n.t('activerecord.options.project.process.manual'),
2 => I18n.t('activerecord.options.project.process.automatic')
}
process_hash[self.process]
end
def self.order_by(projects, order, current_user)
case order
when 'pmdocs_count', 'pmcdocs_count', 'denotations_count', 'relations_count'
projects.accessible(current_user).order("#{order} DESC")
when 'author'
projects.accessible(current_user).order_author
when 'maintainer'
projects.accessible(current_user).order_maintainer
else
# 'association' or nil
projects.accessible(current_user).order_association(current_user)
end
end
# after_add doc
def increment_docs_counter(doc)
if doc.sourcedb == 'PMC' && doc.serial == 0
counter_column = :pmcdocs_count
elsif doc.sourcedb == 'PubMed'
counter_column = :pmdocs_count
end
if counter_column
Project.increment_counter(counter_column, self.id)
if self.projects.present?
self.projects.each do |project|
Project.increment_counter(counter_column, project.id)
end
end
end
end
def update_delta_index(doc)
doc.save
end
def increment_docs_projects_counter(doc)
Doc.increment_counter(:projects_count, doc.id)
end
# after_remove doc
def decrement_docs_counter(doc)
if doc.sourcedb == 'PMC' && doc.serial == 0
counter_column = :pmcdocs_count
elsif doc.sourcedb == 'PubMed'
counter_column = :pmdocs_count
end
if counter_column
Project.decrement_counter(counter_column, self.id)
if self.projects.present?
self.projects.each do |project|
Project.decrement_counter(counter_column, project.id)
end
end
end
end
def decrement_docs_projects_counter(doc)
Doc.decrement_counter(:projects_count, doc.id)
doc.reload
end
def update_annotations_updated_at(doc)
self.update_attribute(:annotations_updated_at, DateTime.now)
end
def associate_maintainers_addable_for?(current_user)
if self.new_record?
true
else
current_user.root? == true || current_user == self.user
end
end
def association_for(current_user)
if current_user.present?
if current_user == self.user
'M'
elsif self.associate_maintainer_users.include?(current_user)
'A'
end
end
end
def build_associate_maintainers(usernames)
if usernames.present?
users = User.where('username IN (?)', usernames)
users = users.uniq if users.present?
users.each do |user|
self.associate_maintainers.build({:user_id => user.id})
end
end
end
def add_associate_projects(params_associate_projects, current_user)
if params_associate_projects.present?
associate_projects_names = Array.new
params_associate_projects[:name].each do |index, name|
associate_projects_names << name
if params_associate_projects[:import].present? && params_associate_projects[:import][index]
project = Project.includes(:associate_projects).find_by_name(name)
associate_projects_accessible = project.associate_projects.accessible(current_user)
# import associate projects which current user accessible
if associate_projects_accessible.present?
associate_project_names = associate_projects_accessible.collect{|associate_project| associate_project.name}
associate_projects_names = associate_projects_names | associate_project_names if associate_project_names.present?
end
end
end
associate_projects = Project.where('name IN (?) AND id NOT IN (?)', associate_projects_names.uniq, associate_project_and_project_ids)
self.associate_projects << associate_projects
end
end
def associate_project_ids
associate_project_ids = associate_projects.present? ? associate_projects.collect{|associate_project| associate_project.id} : []
associate_project_ids.uniq
end
def self_id_and_associate_project_ids
associate_project_ids << self.id if self.id.present?
end
def self_id_and_associate_project_and_project_ids
associate_project_and_project_ids << self.id if self.id.present?
end
def project_ids
project_ids = projects.present? ? projects.collect{|project| project.id} : []
project_ids.uniq
end
def associate_project_and_project_ids
if associate_project_ids.present? || project_ids.present?
associate_project_ids | project_ids
else
[0]
end
end
def associatable_project_ids(current_user)
if self.new_record?
associatable_projects = Project.accessible(current_user)
else
associatable_projects = Project.accessible(current_user).not_id_in(self.self_id_and_associate_project_and_project_ids)
end
associatable_projects.collect{|associatable_projects| associatable_projects.id}
end
# increment counters after add associate projects
def increment_counters(associate_project)
Project.update_counters self.id,
:pmdocs_count => associate_project.pmdocs.count,
:pmcdocs_count => associate_project.pmcdocs.count,
:denotations_count => associate_project.denotations.count,
:relations_count => associate_project.relations.count
end
def increment_pending_associate_projects_count(associate_project)
Project.increment_counter(:pending_associate_projects_count, self.id)
end
def copy_associate_project_relational_models(associate_project)
Project.decrement_counter(:pending_associate_projects_count, self.id)
if associate_project.docs.present?
copy_docs = associate_project.docs - self.docs
copy_docs.each do |doc|
# copy doc
self.docs << doc
end
end
if associate_project.denotations.present?
# copy denotations
associate_project.denotations.each do |denotation|
same_denotation = self.denotations.where(
{
:hid => denotation.hid,
:doc_id => denotation.doc_id,
:begin => denotation.begin,
:end => denotation.end,
:obj => denotation.obj
}
)
if same_denotation.blank?
self.denotations << denotation.dup
end
end
end
if associate_project.relations.present?
associate_project.relations.each do |relation|
same_relation = self.relations.where({
:hid => relation.hid,
:subj_id => relation.subj_id,
:subj_type => relation.subj_type,
:obj_id => relation.obj_id,
:obj_type => relation.obj_type,
:pred => relation.pred
})
if same_relation.blank?
self.relations << relation.dup
end
end
end
end
handle_asynchronously :copy_associate_project_relational_models, :run_at => Proc.new { 1.minutes.from_now }
# decrement counters after delete associate projects
def decrement_counters(associate_project)
Project.update_counters self.id,
:pmdocs_count => - associate_project.pmdocs.count,
:pmcdocs_count => - associate_project.pmcdocs.count,
:denotations_count => - associate_project.denotations.count,
:relations_count => - associate_project.relations.count
end
def get_denotations_count(doc = nil, span = nil)
if doc.nil?
self.denotations_count
else
if span.nil?
doc.denotations.where("denotations.project_id = ?", self.id).count
else
doc.hdenotations(self, span).length
end
end
end
def get_annotations_count(doc = nil, span = nil)
if doc.nil?
self.annotations_count
else
if span.nil?
# begin from the doc because it should be faster.
doc.denotations.where("denotations.project_id = ?", self.id).count + doc.subcatrels.where("relations.project_id = ?", self.id).count + doc.catmods.where("modifications.project_id = ?", self.id).count + doc.subcatrelmods.where("modifications.project_id = ?", self.id).count
else
hdenotations = doc.hdenotations(self, span)
ids = hdenotations.collect{|d| d[:id]}
hrelations = doc.hrelations(self, ids)
ids += hrelations.collect{|d| d[:id]}
hmodifications = doc.hmodifications(self, ids)
hdenotations.size + hrelations.size + hmodifications.size
end
end
end
def annotations_collection(encoding = nil)
if self.docs.present?
self.docs.collect{|doc| doc.set_ascii_body if encoding == 'ascii'; doc.hannotations(self)}
else
[]
end
end
def json
except_columns = %w(pmdocs_count pmcdocs_count pending_associate_projects_count user_id)
to_json(except: except_columns, methods: :maintainer)
end
def docs_list_hash
docs.collect{|doc| doc.to_list_hash} if docs.present?
end
def maintainer
user.present? ? user.username : ''
end
def downloads_system_path
"#{Rails.root}/public#{Project::DOWNLOADS_PATH}"
end
def annotations_zip_filename
"#{self.name.gsub(' ', '_')}-annotations.zip"
end
def annotations_zip_path
"#{Project::DOWNLOADS_PATH}" + self.annotations_zip_filename
end
def annotations_zip_system_path
self.downloads_system_path + self.annotations_zip_filename
end
def create_annotations_zip(encoding = nil)
require 'fileutils'
begin
annotations_collection = self.annotations_collection(encoding)
FileUtils.mkdir_p(self.downloads_system_path) unless Dir.exist?(self.downloads_system_path)
file = File.new(self.annotations_zip_system_path, 'w')
Zip::ZipOutputStream.open(file.path) do |z|
annotations_collection.each do |annotations|
title = get_doc_info(annotations[:target]).sub(/\.$/, '').gsub(' ', '_')
title += ".json" unless title.end_with?(".json")
z.put_next_entry(title)
z.print annotations.to_json
end
end
file.close
self.notices.create({method: "create annotations zip", successful: true})
rescue => e
self.notices.create({method: "create annotations zip", successful: false})
end
end
def get_conversion (annotation, converter, identifier = nil)
RestClient.post converter, annotation.to_json, :content_type => :json do |response, request, result|
case response.code
when 200
response.force_encoding(Encoding::UTF_8)
else
nil
end
end
end
def annotations_rdf_filename
"#{self.name.gsub(' ', '_')}-annotations-rdf.zip"
end
def annotations_rdf_path
"#{Project::DOWNLOADS_PATH}" + self.annotations_rdf_filename
end
def annotations_rdf_system_path
self.downloads_system_path + self.annotations_rdf_filename
end
def create_annotations_rdf(encoding = nil)
begin
ttl = rdfize_docs(self.annotations_collection(encoding), Pubann::Application.config.rdfizer_annotations)
result = create_rdf_zip(ttl)
self.notices.create({method: "create annotations rdf", successful: true})
rescue => e
self.notices.create({method: "create annotations rdf", successful: false})
end
ttl
end
def create_rdf_zip (ttl)
require 'fileutils'
begin
FileUtils.mkdir_p(self.downloads_system_path) unless Dir.exist?(self.downloads_system_path)
file = File.new(self.annotations_rdf_system_path, 'w')
Zip::ZipOutputStream.open(file.path) do |z|
z.put_next_entry(self.name + '.ttl')
z.print ttl
end
file.close
end
end
def index_projects_annotations_rdf
projects = Project.for_index
projects.reject!{|p| p.name =~ /Allie/}
total_number = projects.length
projects.each_with_index do |project, index|
index1 = index + 1
self.notices.create({method:"- annotations rdf index (#{index1}/#{total_number}): #{project.name}"})
begin
index_project_annotations_rdf(project)
self.notices.create({method:"- annotations rdf index (#{index1}/#{total_number}): #{project.name}", successful: true})
rescue => e
self.notices.create({method:"- annotations rdf index (#{index1}/#{total_number}): #{project.name}", successful: false, message: e.message})
end
end
self.notices.create({method: "index projects annotations rdf", successful: true})
end
def index_project_annotations_rdf(project)
begin
rdfize_docs(project.annotations_collection, Pubann::Application.config.rdfizer_annotations, project.name)
self.notices.create({method: "index project annotations rdf: #{project.name}", successful: true})
rescue => e
self.notices.create({method: "index project annotations rdf: #{project.name}", successful: false, message: e.message})
end
end
def index_docs_rdf(docs = nil)
begin
if docs.nil?
projects = Project.for_index
projects.reject!{|p| p.name =~ /Allie/}
docs = projects.inject([]){|sum, p| sum + p.docs}.uniq
end
annotations_collection = docs.collect{|doc| doc.hannotations}
ttl = rdfize_docs(annotations_collection, Pubann::Application.config.rdfizer_spans)
# store_rdf(nil, ttl)
self.notices.create({method: "index docs rdf", successful: true})
rescue => e
self.notices.create({method: "index docs rdf", successful: false, message: e.message})
end
end
def rdfize_docs_backup(annotations_collection, rdfizer, project_name=nil)
ttl = ''
header_length = 0
total_number = annotations_collection.length
annotations_collection.each_with_index do |annotations, i|
index1 = i + 1
doc_description = annotations[:sourcedb] + '-' + annotations[:sourceid]
doc_description += '-' + annotations[:divid].to_s if annotations[:divid]
begin
self.notices.create({method:" - index doc rdf (#{index1}/#{total_number}): #{doc_description}"})
doc_ttl = self.get_conversion(annotations, rdfizer)
if i == 0
doc_ttl.each_line{|l| break unless l.start_with?('@'); header_length += 1}
else
doc_ttl = doc_ttl.split(/\n/)[header_length .. -1].join("\n")
end
doc_ttl += "\n" unless doc_ttl.end_with?("\n")
post_rdf(project_name, doc_ttl)
ttl += doc_ttl
self.notices.create({method:" - index doc rdf (#{index1}/#{total_number}): #{doc_description}", successful: true})
rescue => e
self.notices.create({method:" - index doc rdf (#{index1}/#{total_number}): #{doc_description}", successful: false, message: e.message})
next
end
end
ttl
end
def rdfize_docs(annotations_collection, rdfizer, project_name=nil)
total_number = annotations_collection.length
annotations_collection.each_with_index do |annotations, i|
index1 = i + 1
doc_description = annotations[:sourcedb] + '-' + annotations[:sourceid]
doc_description += '-' + annotations[:divid].to_s if annotations[:divid]
begin
self.notices.create({method:" - index doc rdf (#{index1}/#{total_number}): #{doc_description}"})
doc_ttl = self.get_conversion(annotations, rdfizer)
post_rdf(project_name, doc_ttl)
self.notices.create({method:" - index doc rdf (#{index1}/#{total_number}): #{doc_description}", successful: true})
rescue => e
self.notices.create({method:" - index doc rdf (#{index1}/#{total_number}): #{doc_description}", successful: false, message: e.message})
next
end
end
end
def store_rdf(project_name = nil, ttl)
require 'open3'
ttl_file = Tempfile.new("temporary.ttl")
ttl_file.write(ttl)
ttl_file.close
File.open("docs-spans.ttl", 'w') {|f| f.write(ttl)}
graph_uri = project_name.nil? ? "http://pubannotation.org/docs" : "http://pubannotation.org/projects/#{project_name}"
destination = "#{Pubann::Application.config.sparql_end_point}/sparql-graph-crud-auth?graph-uri=#{graph_uri}"
cmd = %[curl --digest --user #{Pubann::Application.config.sparql_end_point_auth} --verbose --url #{destination} -X PUT -T #{ttl_file.path}]
message, error, state = Open3.capture3(cmd)
ttl_file.unlink
raise IOError, "sparql-graph-crud failed" unless state.success?
end
def post_rdf(project_name = nil, ttl)
require 'open3'
ttl_file = Tempfile.new("temporary.ttl")
ttl_file.write(ttl)
ttl_file.close
graph_uri = project_name.nil? ? "http://pubannotation.org/docs" : "http://pubannotation.org/projects/#{project_name}"
destination = "#{Pubann::Application.config.sparql_end_point}/sparql-graph-crud-auth?graph-uri=#{graph_uri}"
cmd = %[curl --digest --user #{Pubann::Application.config.sparql_end_point_auth} --verbose --url #{destination} -X POST -T #{ttl_file.path}]
message, error, state = Open3.capture3(cmd)
ttl_file.unlink
raise IOError, "sparql-graph-crud failed" unless state.success?
end
def self.params_from_json(json_file)
project_attributes = JSON.parse(File.read(json_file))
user = User.find_by_username(project_attributes['maintainer'])
project_params = project_attributes.select{|key| Project.attr_accessible[:default].include?(key)}
end
def create_annotations_from_zip(zip_file_path, options = {})
begin
files = Zip::ZipFile.open(zip_file_path) do |zip|
zip.collect do |entry|
next if entry.ftype == :directory
next unless entry.name.end_with?('.json')
{name:entry.name, content:entry.get_input_stream.read}
end.delete_if{|e| e.nil?}
end
raise IOError, "No JSON file found" unless files.length > 0
error_files = []
annotations_collection = files.inject([]) do |m, file|
begin
as = JSON.parse(file[:content], symbolize_names:true)
if as.is_a?(Array)
m + as
else
m + [as]
end
rescue => e
error_files << file[:name]
m
end
end
raise IOError, "Invalid JSON files: #{error_files.join(', ')}" unless error_files.empty?
error_anns = []
annotations_collection.each do |annotations|
if annotations[:text].present? && annotations[:sourcedb].present? && annotations[:sourceid].present?
else
error_anns << if annotations[:sourcedb].present? && annotations[:sourceid].present?
"#{annotations[:sourcedb]}:#{annotations[:sourceid]}"
elsif annotations[:text].present?
annotations[:text][0..10] + "..."
else
'???'
end
end
end
raise IOError, "Invalid annotation found. An annotation has to include at least the four components, text, denotation, sourcedb, and sourceid: #{error_anns.join(', ')}" unless error_anns.empty?
error_anns = []
annotations_collection.each do |annotations|
begin
normalize_annotations!(annotations)
rescue => e
error_anns << "#{annotations[:sourcedb]}:#{annotations[:sourceid]}"
end
end
raise IOError, "Invalid annotations: #{error_anns.join(', ')}" unless error_anns.empty?
total_number = annotations_collection.length
interval = (total_number > 100000)? 100 : 10
imported, added, failed, messages = 0, 0, 0, []
annotations_collection.each_with_index do |annotations, i|
begin
self.notices.create({method:"- annotations upload (#{i}/#{total_number} docs)", successful:true, message: "finished"}) if (i != 0) && (i % interval == 0)
annotations[:sourcedb] = 'PubMed' if annotations[:sourcedb].downcase == 'pubmed'
annotations[:sourcedb] = 'PMC' if annotations[:sourcedb].downcase == 'pmc'
annotations[:sourcedb] = 'FirstAuthor' if annotations[:sourcedb].downcase == 'firstauthor'
i, a, f, m = self.add_doc(annotations[:sourcedb], annotations[:sourceid])
if annotations[:divid].present?
doc = Doc.find_by_sourcedb_and_sourceid_and_serial(annotations[:sourcedb], annotations[:sourceid], annotations[:divid])
else
divs = Doc.find_all_by_sourcedb_and_sourceid(annotations[:sourcedb], annotations[:sourceid])
doc = divs[0] if divs.length == 1
end
result = if doc.present?
self.save_annotations(annotations, doc, options)
elsif divs.present?
self.store_annotations(annotations, divs, options)
else
raise IOError, "document does not exist"
end
rescue => e
self.notices.create({method:"- annotations upload: #{annotations[:sourcedb]}:#{annotations[:sourceid]}", successful:false, message: e.message})
next
end
end
self.notices.create({method:'annotations batch upload', successful:true})
messages << "annotations loaded to #{annotations_collection.length} documents"
rescue => e
self.notices.create({method:'annotations batch upload', successful:false, message: e.message})
end
end
def create_annotations_from_zip_backup(zip_file_path, options)
annotations_collection = Zip::ZipFile.open(zip_file_path) do |zip|
zip.collect{|entry| JSON.parse(entry.get_input_stream.read, symbolize_names:true)}
end
total_number = annotations_collection.length
imported, added, failed, messages = 0, 0, 0, []
annotations_collection.each_with_index do |annotations, index|
docspec = annotations[:divid].present? ? "#{annotations[:sourcedb]}:#{annotations[:sourceid]}-#{annotations[:divid]}" : "#{annotations[:sourcedb]}:#{annotations[:sourceid]}"
self.notices.create({method:"> annotations upload (#{index}/#{total_number}): #{docspec}"})
i, a, f, m = self.add_doc(annotations[:sourcedb], annotations[:sourceid])
imported += i; added += a; failed += f
messages << m if m.present?
serial = annotations[:divid].present? ? annotations[:divid].to_i : 0
doc = Doc.find_by_sourcedb_and_sourceid_and_serial(annotations[:sourcedb], annotations[:sourceid], serial)
result = self.save_annotations(annotations, doc, options)
successful = result.nil? ? false : true
self.notices.create({method:"> annotations upload (#{index}/#{total_number}): #{docspec}", successful:successful})
end
self.notices.create({method:'annotations batch upload', successful:true})
messages << "annotations loaded to #{annotations_collection.length} documents"
end
# def save_annotations(annotations_files)
# annotations_files.each do |annotations_file|
# annotations = JSON.parse(File.read(annotations_file))
# File.unlink(annotations_file)
# serial = annotations[:divid].present? ? annotations[:divid].to_i : 0
# doc = Doc.find_by_sourcedb_and_sourceid_and_serial(annotations[:sourcedb], annotations[:sourceid], serial)
# if doc.present?
# self.save_annotations(annotations, doc)
# end
# end
# end
def self.create_from_zip(zip_file, project_name, current_user)
messages = Array.new
errors = Array.new
unless Dir.exist?(TempFilePath)
FileUtils.mkdir_p(TempFilePath)
end
project_json_file = "#{TempFilePath}#{project_name}-project.json"
docs_json_file = "#{TempFilePath}#{project_name}-docs.json"
doc_annotations_files = Array.new
# open zip file
Zip::ZipFile.open(zip_file) do |zipfile|
zipfile.each do |file|
file_name = file.name
if file_name == 'project.json'
# extract project.json
file.extract(project_json_file) unless File.exist?(project_json_file)
elsif file_name == 'docs.json'
# extract docs.json
file.extract(docs_json_file) unless File.exist?(docs_json_file)
else
# extract sourcedb-sourdeid-serial-section.json
doc_annotations_file = "#{TempFilePath}#{file.name}"
unless File.exist?(doc_annotations_file)
file.extract(doc_annotations_file)
doc_annotations_files << {name: file.name, path: doc_annotations_file}
end
end
end
end
# create project if [project_name]-project.json exist
if File.exist?(project_json_file)
params_from_json = Project.params_from_json(project_json_file)
File.unlink(project_json_file)
project_params = params_from_json
project = Project.new(project_params)
project.user = current_user
if project.valid?
project.save
messages << I18n.t('controllers.shared.successfully_created', model: I18n.t('activerecord.models.project'))
else
errors << project.errors.full_messages.join('<br />')
project = nil
end
end
# create project.docs if [project_name]-docs.json exist
if project.present?
if File.exist?(docs_json_file)
if project.present?
num_created, num_added, num_failed = project.add_docs_from_json(JSON.parse(File.read(docs_json_file), :symbolize_names => true), current_user)
messages << I18n.t('controllers.docs.create_project_docs.created_to_document_set', num_created: num_created, project_name: project.name) if num_created > 0
messages << I18n.t('controllers.docs.create_project_docs.added_to_document_set', num_added: num_added, project_name: project.name) if num_added > 0
messages << I18n.t('controllers.docs.create_project_docs.failed_to_document_set', num_failed: num_failed, project_name: project.name) if num_failed > 0
end
File.unlink(docs_json_file)
end
# save annotations
if doc_annotations_files
delay.save_annotations(project, doc_annotations_files)
messages << I18n.t('controllers.projects.upload_zip.delay_save_annotations')
end
end
return [messages, errors]
end
# def self.save_annotations(project, doc_annotations_files)
# doc_annotations_files.each do |doc_annotations_file|
# doc_info = doc_annotations_file[:name].split('-')
# doc = Doc.find_by_sourcedb_and_sourceid_and_serial(doc_info[0], doc_info[1], doc_info[2])
# doc_params = JSON.parse(File.read(doc_annotations_file[:path]))
# File.unlink(doc_annotations_file[:path])
# if doc.present?
# if doc_params['denotations'].present?
# annotations = {
# denotations: doc_params['denotations'],
# relations: doc_params['relations'],
# text: doc_params['text']
# }
# self.save_annotations(annotations, doc)
# end
# end
# end
# end
def add_docs_from_json(docs, user)
num_created, num_added, num_failed = 0, 0, 0
docs = [docs] if docs.class == Hash
sourcedbs = docs.group_by{|doc| doc[:sourcedb]}
if sourcedbs.present?
sourcedbs.each do |sourcedb, docs_array|
ids = docs_array.collect{|doc| doc[:sourceid]}.join(",")
num_created_t, num_added_t, num_failed_t = self.add_docs({ids: ids, sourcedb: sourcedb, docs_array: docs_array, user: user})
num_created += num_created_t
num_added += num_added_t
num_failed += num_failed_t
end
end
return [num_created, num_added, num_failed]
end
def add_docs2(docspecs)
imported, added, failed, messages = 0, 0, 0, []
docspecs.each do |docspec|
i, a, f, m = self.add_doc(docspec[:sourcedb], docspec[:sourceid])
imported += i; added += a; failed += f;
messages << m if m.present?
end
notices.create({method: "add documents to the project", successful: true, message:"imported:#{imported}, added:#{added}, failed:#{failed}"})
end
def add_docs(options = {})
num_created, num_added, num_failed = 0, 0, 0
ids = options[:ids].split(/[ ,"':|\t\n]+/).collect{|id| id.strip}
ids.each do |sourceid|
divs = Doc.find_all_by_sourcedb_and_sourceid(options[:sourcedb], sourceid)
is_current_users_sourcedb = (options[:sourcedb] =~ /.#{Doc::UserSourcedbSeparator}#{options[:user].username}\Z/).present?
if divs.present?
if is_current_users_sourcedb
# when sourcedb is user's sourcedb
# update or create if not present
options[:docs_array].each do |doc_array|
# find doc sourcedb sourdeid and serial
doc = Doc.find_or_initialize_by_sourcedb_and_sourceid_and_serial(options[:sourcedb], sourceid, doc_array['divid'])
mappings = {
'text' => 'body',
'section' => 'section',
'source_url' => 'source',
'divid' => 'serial'
}
doc_params = Hash[doc_array.map{|key, value| [mappings[key], value]}].select{|key| key.present?}
if doc.new_record?
# when same sourcedb sourceid serial not present
doc.attributes = doc_params
if doc.valid?
# create
doc.save
self.docs << doc unless self.docs.include?(doc)
num_created += 1
else
num_failed += 1
end
else
# when same sourcedb sourceid serial present
# update
if doc.update_attributes(doc_params)
self.docs << doc unless self.docs.include?(doc)
num_added += 1
else
num_failed += 1
end
end
end
else
# when sourcedb is not user's sourcedb
unless self.docs.include?(divs.first)
self.docs << divs
num_added += divs.size
end
end
else
if options[:sourcedb].include?(Doc::UserSourcedbSeparator)
# when sourcedb include :
if is_current_users_sourcedb
# when sourcedb is user's sourcedb
divs, num_failed_user_sourcedb_docs = create_user_sourcedb_docs(docs_array: options[:docs_array])
num_failed += num_failed_user_sourcedb_docs
else
# when sourcedb is not user's sourcedb
num_failed += options[:docs_array].size
end
else
# when sourcedb is not user generated
begin
# when doc_sequencer_ present
doc_sequence = Object.const_get("DocSequencer#{options[:sourcedb]}").new(sourceid)
divs_hash = doc_sequence.divs
divs = Doc.create_divs(divs_hash, :sourcedb => options[:sourcedb], :sourceid => sourceid, :source_url => doc_sequence.source_url)
rescue
# when doc_sequencer_ not present
divs, num_failed_user_sourcedb_docs = create_user_sourcedb_docs({docs_array: options[:docs_array], sourcedb: "#{options[:sourcedb]}#{Doc::UserSourcedbSeparator}#{options[:user].username}"})
num_failed += num_failed_user_sourcedb_docs
end
end
if divs
self.docs << divs
num_created += divs.size
else
num_failed += 1
end
end
end
return [num_created, num_added, num_failed]
end
def add_doc(sourcedb, sourceid)
imported, added, failed, message = 0, 0, 0, ''
begin
divs = Doc.find_all_by_sourcedb_and_sourceid(sourcedb, sourceid)
if divs.present?
if self.docs.include?(divs.first)
raise "The document #{sourcedb}:#{sourceid} already exists."
else
self.docs << divs
added += 1
end
else
divs = Doc.import(sourcedb, sourceid)
if divs.present?
imported += 1
self.docs << divs
added += 1
else
raise "Failed to get the document #{sourcedb}:#{sourceid} from the source."
end
end
if divs.present? and !self.docs.include?(divs.first)
self.docs << divs
added += 1
end
rescue => e
failed += 1
message = e.message
end
[imported, added, failed, message]
end
def create_user_sourcedb_docs(options = {})
divs = []
num_failed = 0
if options[:docs_array].present?
options[:docs_array].each do |doc_array_params|
# all of columns insert into database need to be included in this hash.
doc_array_params[:sourcedb] = options[:sourcedb] if options[:sourcedb].present?
mappings = {
:text => :body,
:sourcedb => :sourcedb,
:sourceid => :sourceid,
:section => :section,
:source_url => :source,
:divid => :serial
}
doc_params = Hash[doc_array_params.map{|key, value| [mappings[key], value]}].select{|key| key.present? && Doc.attr_accessible[:default].include?(key)}
doc = Doc.new(doc_params)
if doc.valid?
doc.save
divs << doc
else
num_failed += 1
end
end
end
return [divs, num_failed]
end
def save_hdenotations(hdenotations, doc)
hdenotations.each do |a|
ca = Denotation.new
ca.hid = a[:id]
ca.begin = a[:span][:begin]
ca.end = a[:span][:end]
ca.obj = a[:obj]
ca.project_id = self.id
ca.doc_id = doc.id
raise ArgumentError, "Invalid representation of denotation: #{ca.hid}" unless ca.save
end
end
def save_hrelations(hrelations, doc)
hrelations.each do |a|
ra = Relation.new
ra.hid = a[:id]
ra.pred = a[:pred]
ra.subj = Denotation.find_by_doc_id_and_project_id_and_hid(doc.id, self.id, a[:subj])
ra.obj = Denotation.find_by_doc_id_and_project_id_and_hid(doc.id, self.id, a[:obj])
ra.project_id = self.id
raise ArgumentError, "Invalid representation of relation: #{ra.hid}" unless ra.save
end
end
def save_hmodifications(hmodifications, doc)
hmodifications.each do |a|
ma = Modification.new
ma.hid = a[:id]
ma.pred = a[:pred]
ma.obj = case a[:obj]
when /^R/
doc.subcatrels.find_by_project_id_and_hid(self.id, a[:obj])
else
Denotation.find_by_doc_id_and_project_id_and_hid(doc.id, self.id, a[:obj])
end
ma.project_id = self.id
raise ArgumentError, "Invalid representatin of modification: #{ma.hid}" unless ma.save
end
end
def save_annotations(annotations, doc, options = nil)
raise ArgumentError, "nil document" unless doc.present?
options ||= {}
doc.destroy_project_annotations(self) unless options.present? && options[:mode] == :addition
if options[:prefix].present?
prefix = options[:prefix]
annotations[:denotations].each {|a| a[:id] = prefix + '_' + a[:id]} if annotations[:denotations].present?
annotations[:relations].each {|a| a[:id] = prefix + '_' + a[:id]; a[:subj] = prefix + '_' + a[:subj]; a[:obj] = prefix + '_' + a[:obj]} if annotations[:relations].present?
annotations[:modifications].each {|a| a[:id] = prefix + '_' + a[:id]; a[:obj] = prefix + '_' + a[:obj]} if annotations[:modifications].present?
end
original_text = annotations[:text]
annotations[:text] = doc.body
if annotations[:denotations].present?
annotations[:denotations] = align_denotations(annotations[:denotations], original_text, annotations[:text])
ActiveRecord::Base.transaction do
self.save_hdenotations(annotations[:denotations], doc)
self.save_hrelations(annotations[:relations], doc) if annotations[:relations].present?
self.save_hmodifications(annotations[:modifications], doc) if annotations[:modifications].present?
end
end
result = annotations.select{|k,v| v.present?}
end
def store_annotations(annotations, divs, options = {})
options ||= {}
successful = true
fit_index = nil
begin
if divs.length == 1
result = self.save_annotations(annotations, divs[0], options)
else
result = []
div_index = divs.collect{|d| [d.serial, d]}.to_h
divs_hash = divs.collect{|d| d.to_hash}
fit_index = TextAlignment.find_divisions(annotations[:text], divs_hash)
fit_index.each do |i|
if i[0] >= 0
ann = {divid:i[0]}
idx = {}
ann[:text] = annotations[:text][i[1][0] ... i[1][1]]
if annotations[:denotations].present?
ann[:denotations] = annotations[:denotations]
.select{|a| a[:span][:begin] >= i[1][0] && a[:span][:end] <= i[1][1]}
.collect{|a| n = a.dup; n[:span] = a[:span].dup; n}
.each{|a| a[:span][:begin] -= i[1][0]; a[:span][:end] -= i[1][0]}
ann[:denotations].each{|a| idx[a[:id]] = true}
end
if annotations[:relations].present?
ann[:relations] = annotations[:relations].select{|a| idx[a[:subj]] && idx[a[:obj]]}
ann[:relations].each{|a| idx[a[:id]] = true}
end
if annotations[:modifications].present?
ann[:modifications] = annotations[:modifications].select{|a| idx[a[:obj]]}
ann[:modifications].each{|a| idx[a[:id]] = true}
end
result << self.save_annotations(ann, div_index[i[0]], options)
end
end
{div_index: fit_index}
end
self.notices.create({method: "annotations upload: #{divs[0].sourcedb}:#{divs[0].sourceid}", successful: successful}) if options[:delayed]
result
rescue => e
self.notices.create({method: "annotations upload: #{divs[0].sourcedb}:#{divs[0].sourceid}", successful: successful}) if options[:delayed]
raise e
end
end
def obtain_annotations(doc, annotation_server_url, options = nil)
annotations = doc.hannotations(self)
annotations = gen_annotations(annotations, annotation_server_url, options)
normalize_annotations!(annotations)
result = self.save_annotations(annotations, doc, options)
end
def obtain_annotations_all_docs(annotation_server_url, options = nil)
docs = self.docs
num_total = docs.length
num_success = 0
docs.each_with_index do |doc, i|
begin
notices.create({method: "obtain annotations (#{i}/#{num_total} docs)", successful:true, message:"finished"})
self.obtain_annotations(doc, annotation_server_url, options)
num_success += 1
rescue => e
notices.create({method: "obtain annotations #{doc.descriptor}", successful: false, message: e.message})
end
end
notices.create({method: 'obtain annotations for all the project documents', successful: num_total == num_success})
end
def user_presence
if user.blank?
errors.add(:user_id, 'is blank')
end
end
def namespaces_base
namespaces.find{|namespace| namespace['prefix'] == '_base'} if namespaces.present?
end
def base_uri
namespaces_base['uri'] if namespaces_base.present?
end
def namespaces_prefixes
namespaces.select{|namespace| namespace['prefix'] != '_base'} if namespaces.present?
end
# delete empty value hashes
def cleanup_namespaces
namespaces.reject!{|namespace| namespace['prefix'].blank? || namespace['uri'].blank?} if namespaces.present?
end
def delete_doc(doc, current_user)
raise RuntimeError, "The project does not include the document." unless self.docs.include?(doc)
doc.destroy_project_annotations(self)
self.docs.delete(doc)
doc.destroy if doc.sourcedb.end_with?("#{Doc::UserSourcedbSeparator}#{current_user.username}") && doc.projects_count == 0
end
def delete_all_docs(current_user)
docs = self.docs
num_total = docs.length
num_success = 0
docs.each_with_index do |doc, i|
begin
notices.create({method: "delete documents (#{i}/#{num_total} docs)", successful:true, message:"finished"}) if (i != 0) && (i % 100 == 0)
delete_doc(doc, current_user)
num_success += 1
rescue => e
notices.create({method: "delete document: #{doc.descriptor}", successful: false, message: e.message})
end
end
successful = if (self.denotations.length + self.relations.length + self.modifications.length == 0)
self.update_attribute(:annotations_count, 0)
self.docs.clear
true
else
false
end
notices.create({method: 'delete all the documents in the project', successful: successful})
end
def destroy_annotations
docs = self.docs
num_total = docs.length
num_success = 0
docs.each_with_index do |doc, i|
begin
notices.create({method: "delete annotations (#{i}/#{num_total} docs)", successful:true, message:"finished"}) if (i != 0) && (i % 100 == 0)
doc.destroy_project_annotations(self)
num_success += 1
rescue => e
notices.create({method: "delete annotations: #{doc.descriptor}", successful: false, message: e.message})
end
end
successful = if (self.denotations.length + self.relations.length + self.modifications.length == 0)
self.update_attribute(:annotations_count, 0)
true
else
false
end
notices.create({method: 'delete all the annotations in the project', successful: successful})
end
def delay_destroy
begin
destroy
rescue
notices.create({method: 'destroy the project', successful: false})
end
end
def update_updated_at(model)
self.update_attribute(:updated_at, DateTime.now)
end
end
|
class Project < ActiveRecord::Base
belongs_to :professor
has_many :records
has_many :students, through: :records
def current?
self.status == "active"
end
def complete?
self.status == "complete"
end
def remaining_time
total_worked = 0
self.records.each do |record|
total_worked += record.hours_worked
end
self.budget - total_worked
end
end
change 'budget' to 'time_budget'
class Project < ActiveRecord::Base
belongs_to :professor
has_many :records
has_many :students, through: :records
def current?
self.status == "active"
end
def complete?
self.status == "complete"
end
def remaining_time
total_worked = 0
self.records.each do |record|
total_worked += record.hours_worked
end
self.time_budget - total_worked
end
end
|
class Project < ActiveRecord::Base
include ActionView::Helpers::TextHelper
belongs_to :user
has_many :instructions, dependent: :destroy
has_many :materials, dependent: :destroy
has_many :experiences, counter_cache: true, dependent: :destroy
has_many :bookmarks, counter_cache: true, dependent: :destroy
has_attached_file :photo,
:styles => { rect: '300x200#', square: '150x150#', medium: '300x300>', thumb: '100x100>' },
:default_url => "/images/:style/missing.png"
before_create :set_defaults
before_save :calculate_averages
LONG_ESTIMATED_SIMPLE_DESCRIPTIONS = [
'Extremely simple, requires just a few household items',
'', '', '',
'May require unusual materials or be a little messy',
'', '', '', '',
'Very challenging and/or expensive. May require technical skills'
]
ESTIMATED_SIMPLE_DESCRIPTIONS = [
'Very Simple',
'Very Simple',
'Simple',
'Simple',
'Mildly Challenging',
'Mildly Challenging',
'Challenging',
'Challenging',
'Very Challenging',
'Very Challenging'
]
def simple_description(long=false)
return '' unless estimated_simple
descriptions = long ? LONG_ESTIMATED_SIMPLE_DESCRIPTIONS : ESTIMATED_SIMPLE_DESCRIPTIONS
descriptions[estimated_simple]
end
def post_to_tumblr
client = Tumblr::Client.new({
:consumer_key => ENV['TUMBLR_CONSUMER_KEY'],
:consumer_secret => ENV['TUMBLR_CONSUMER_SECRET'],
:oauth_token => ENV['TUMBLR_OAUTH_TOKEN'],
:oauth_token_secret => ENV['TUMBLR_OAUTH_SECRET']
})
# body = """
# <img src='#{photo.url(:medium)}' style='display: block; margin: 0 auto 12px auto;'/>
# <p>#{truncate(description.gsub(/\r/, '<br/>'), :length => 250)}</p>
# <p><a href='http://www.makerparent.com/projects/#{id}'>Visit Project ></a></p>
# """
# puts title
# puts body
#
# client.text("makerparent.tumblr.com", {
# title: title,
# body: body
# })
caption = """
<h3>#{title}</h3>
<p>#{truncate(description.gsub(/\r/, '<br/>'), :length => 250)}</p>
<p><a href='http://www.makerparent.com/projects/#{id}'>Visit Project ></a></p>
"""
puts photo.url(:medium)
puts "http://www.makerparent.com/projects/#{id}"
puts caption
client.photo("makerparent.tumblr.com", {
source: photo.url(:medium),
link: "http://www.makerparent.com/projects/#{id}",
caption: caption
})
end
private
def calculate_averages
self.average_simple = estimated_simple
self.min_cost = estimated_cost
self.min_age = estimated_age
end
def set_defaults
self.experiences_count = 0
self.bookmarks_count = 0
end
end
working on tumblr integration
class Project < ActiveRecord::Base
include ActionView::Helpers::TextHelper
belongs_to :user
has_many :instructions, dependent: :destroy
has_many :materials, dependent: :destroy
has_many :experiences, counter_cache: true, dependent: :destroy
has_many :bookmarks, counter_cache: true, dependent: :destroy
has_attached_file :photo,
:styles => { rect: '300x200#', square: '150x150#', medium: '300x300>', thumb: '100x100>' },
:default_url => "/images/:style/missing.png"
before_create :set_defaults
before_save :calculate_averages
LONG_ESTIMATED_SIMPLE_DESCRIPTIONS = [
'Extremely simple, requires just a few household items',
'', '', '',
'May require unusual materials or be a little messy',
'', '', '', '',
'Very challenging and/or expensive. May require technical skills'
]
ESTIMATED_SIMPLE_DESCRIPTIONS = [
'Very Simple',
'Very Simple',
'Simple',
'Simple',
'Mildly Challenging',
'Mildly Challenging',
'Challenging',
'Challenging',
'Very Challenging',
'Very Challenging'
]
def simple_description(long=false)
return '' unless estimated_simple
descriptions = long ? LONG_ESTIMATED_SIMPLE_DESCRIPTIONS : ESTIMATED_SIMPLE_DESCRIPTIONS
descriptions[estimated_simple]
end
def post_to_tumblr
client = Tumblr::Client.new({
:consumer_key => ENV['TUMBLR_CONSUMER_KEY'],
:consumer_secret => ENV['TUMBLR_CONSUMER_SECRET'],
:oauth_token => ENV['TUMBLR_OAUTH_TOKEN'],
:oauth_token_secret => ENV['TUMBLR_OAUTH_SECRET']
})
# body = """
# <img src='#{photo.url(:medium)}' style='display: block; margin: 0 auto 12px auto;'/>
# <p>#{truncate(description.gsub(/\r/, '<br/>'), :length => 250)}</p>
# <p><a href='http://www.makerparent.com/projects/#{id}'>Visit Project ></a></p>
# """
# puts title
# puts body
#
# client.text("makerparent.tumblr.com", {
# title: title,
# body: body
# })
caption = """
<div style='text-align: center;'>
<h3>#{title}</h3>
<p>#{truncate(description.gsub(/\r/, '<br/>'), :length => 250)}</p>
<p><a href='http://www.makerparent.com/projects/#{id}'>Visit Project ></a></p>
</div>
"""
client.photo("makerparent.tumblr.com", {
source: photo.url(:medium),
link: "http://www.makerparent.com/projects/#{id}",
caption: caption
})
end
private
def calculate_averages
self.average_simple = estimated_simple
self.min_cost = estimated_cost
self.min_age = estimated_age
end
def set_defaults
self.experiences_count = 0
self.bookmarks_count = 0
end
end
|
require 'new_relic/agent/method_tracer'
class Scraper < ActiveRecord::Base
belongs_to :owner, inverse_of: :scrapers
has_many :runs, inverse_of: :scraper
has_many :metrics, through: :runs
belongs_to :forked_by, class_name: "User"
validates :name, format: { with: /\A[a-zA-Z0-9_-]+\z/, message: "can only have letters, numbers, '_' and '-'" }
has_one :last_run, -> { order "queued_at DESC" }, class_name: "Run"
has_many :contributors, through: :contributions, source: :user
has_many :contributions
extend FriendlyId
friendly_id :full_name, use: :finders
delegate :queued?, :running?, to: :last_run, allow_nil: true
# Given a scraper name on github populates the fields for a morph scraper but doesn't save it
def self.new_from_github(full_name)
repo = Octokit.repository(full_name)
repo_owner = Owner.find_by_nickname(repo.owner.login)
# Populate a new scraper with information from the repo
Scraper.new(name: repo.name, full_name: repo.full_name,
description: repo.description, github_id: repo.id, owner_id: repo_owner.id,
github_url: repo.rels[:html].href, git_url: repo.rels[:git].href)
end
# Find a user related to this scraper that we can use them to make authenticated github requests
def related_user
if owner.user?
owner
else
owner.users.first
end
end
def update_contributors
# We can't use unauthenticated requests because we will go over our rate limit
begin
c = related_user.octokit_client.contributors(full_name).map do |c|
User.find_or_create_by_nickname(c["login"])
end
rescue Octokit::NotFound
c = []
end
update_attributes(contributors: c)
end
def successful_runs
runs.includes(:log_lines).order(finished_at: :desc).select{|r| r.finished_successfully?}
end
def latest_successful_run_time
latest_successful_run = successful_runs.first
latest_successful_run.finished_at if latest_successful_run
end
def finished_runs
runs.where("finished_at IS NOT NULL").order(finished_at: :desc).includes(:log_lines, :metric)
end
# For successful runs calculates the average wall clock time that this scraper takes
# Handy for the user to know how long it should expect to run for
# Returns nil if not able to calculate this
# TODO Refactor this using scopes
def average_successful_wall_time
successful_runs.sum(&:wall_time) / successful_runs.count if successful_runs.count > 0
end
def total_wall_time
runs.to_a.sum(&:wall_time)
end
def utime
metrics.sum(:utime)
end
def stime
metrics.sum(:stime)
end
def cpu_time
utime + stime
end
def update_sqlite_db_size
update_attributes(sqlite_db_size: database.sqlite_db_size)
end
def total_disk_usage
repo_size + sqlite_db_size
end
add_method_tracer :average_successful_wall_time, 'Custom/Scraper/average_successful_wall_time'
add_method_tracer :total_wall_time, 'Custom/Scraper/total_wall_time'
add_method_tracer :cpu_time, 'Custom/Scraper/cpu_time'
add_method_tracer :total_disk_usage, 'Custom/Scraper/total_disk_usage'
def queued_or_running?
queued? || running?
end
# Let's say a scraper requires attention if it's set to run automatically and the last run failed
def requires_attention?
auto_run && last_run && last_run.finished_with_errors?
end
def self.can_write?(user, owner)
user && (owner == user || user.organizations.include?(owner))
end
def can_write?(user)
Scraper.can_write?(user, owner)
end
def destroy_repo_and_data
FileUtils::rm_rf repo_path
FileUtils::rm_rf data_path
end
def repo_path
"#{owner.repo_root}/#{name}"
end
def data_path
"#{owner.data_root}/#{name}"
end
def self.update_docker_image!
docker_command = "docker #{ENV['DOCKER_TCP'] ? "-H #{ENV['DOCKER_TCP']}" : ""}"
system("#{docker_command} pull openaustralia/morph-ruby")
system("#{docker_command} pull openaustralia/morph-php")
system("#{docker_command} pull openaustralia/morph-python")
end
def readme
f = Dir.glob(File.join(repo_path, "README*")).first
if f
GitHub::Markup.render(f, File.read(f)).html_safe
end
end
def readme_filename
Pathname.new(Dir.glob(File.join(repo_path, "README*")).first).basename.to_s
end
def github_url_readme
github_url_for_file(readme_filename)
end
def runnable?
last_run.nil? || last_run.finished?
end
# Set auto to true if this job is being queued automatically (i.e. not directly by a person)
def queue!(auto = false)
# Guard against more than one of a particular scraper running at the same time
if runnable?
run = runs.create(queued_at: Time.now, auto: auto, owner_id: owner_id)
if auto
RunWorkerAuto.perform_async(run.id)
else
RunWorker.perform_async(run.id)
end
end
end
def github_url_for_file(file)
github_url + "/blob/master/" + file
end
def language
l = Morph::Language.language(repo_path)
end
def main_scraper_filename
Morph::Language.main_scraper_filename(repo_path)
end
def github_url_main_scraper_file
github_url_for_file(main_scraper_filename)
end
def database
Morph::Database.new(self)
end
# It seems silly implementing this
def Scraper.directory_size(directory)
r = 0
if File.exists?(directory)
# Ick
files = Dir.entries(directory)
files.delete(".")
files.delete("..")
files.map{|f| File.join(directory, f)}.each do |f|
s = File.lstat(f)
if s.file?
r += s.size
else
r += Scraper.directory_size(f)
end
end
end
r
end
def update_repo_size
r = Scraper.directory_size(repo_path)
update_attribute(:repo_size, r)
r
end
def scraperwiki_shortname
# scraperwiki_url should be of the form https://classic.scraperwiki.com/scrapers/shortname/
if scraperwiki_url
m = scraperwiki_url.match(/https:\/\/classic.scraperwiki.com\/scrapers\/([-\w]+)(\/)?/)
m[1] if m
end
end
def scraperwiki_shortname=(shortname)
self.scraperwiki_url = "https://classic.scraperwiki.com/scrapers/#{shortname}/" if shortname
end
def current_revision_from_repo
r = Grit::Repo.new(repo_path)
Grit::Head.current(r).commit.id
end
# files should be a hash of "filename" => "content"
def add_commit_to_master_on_github(user, files, message)
client = user.octokit_client
blobs = files.map do |filename, content|
{
:path => filename,
:mode => "100644",
:type => "blob",
:content => content
}
end
# Let's get all the info about head
ref = client.ref(full_name, "heads/master")
commit_sha = ref.object.sha
commit = client.commit(full_name, commit_sha)
tree_sha = commit.commit.tree.sha
tree2 = client.create_tree(full_name, blobs, :base_tree => tree_sha)
commit2 = client.create_commit(full_name, message, tree2.sha, commit_sha)
client.update_ref(full_name, "heads/master", commit2.sha)
end
# Overwrites whatever there was before in that repo
# Obviously use with great care
def add_commit_to_root_on_github(user, files, message)
client = user.octokit_client
blobs = files.map do |filename, content|
{
:path => filename,
:mode => "100644",
:type => "blob",
:content => content
}
end
tree = client.create_tree(full_name, blobs)
commit = client.create_commit(full_name, message, tree.sha)
client.update_ref(full_name, "heads/master", commit.sha)
end
# progress should be between 0 and 100
def fork_progress(message, progress)
update_attributes(forking_message: message, forking_progress: progress)
end
def synchronise_repo
Morph::Github.synchronise_repo(repo_path, git_url)
update_repo_size
update_contributors
end
# Return the https version of the git clone url (git_url)
def git_url_https
"https" + git_url[3..-1]
end
def fork_from_scraperwiki!
client = forked_by.octokit_client
# We need to set auto_init so that we can create a commit later. The API doesn't support
# adding a commit to an empty repository
begin
fork_progress("Creating GitHub repository", 20)
repo = Morph::Github.create_repository(forked_by, owner, name)
update_attributes(github_id: repo.id, github_url: repo.rels[:html].href, git_url: repo.rels[:git].href)
rescue Octokit::UnprocessableEntity
# This means the repo has already been created. We will have gotten here if this background job failed at some
# point past here and is rerun. So, let's happily continue
end
scraperwiki = Morph::Scraperwiki.new(scraperwiki_shortname)
# Copy the sqlite database across from Scraperwiki
fork_progress("Forking sqlite database", 40)
database.write_sqlite_database(scraperwiki.sqlite_database)
# Rename the main table in the sqlite database
database.standardise_table_name("swdata")
fork_progress("Forking code", 60)
# Fill in description
repo = client.edit_repository(full_name, description: scraperwiki.title,
homepage: Rails.application.routes.url_helpers.scraper_url(self))
self.update_attributes(description: scraperwiki.title)
files = {
Morph::Language.language_to_scraper_filename(scraperwiki.language) => scraperwiki.code,
".gitignore" => "# Ignore output of scraper\n#{Morph::Database.sqlite_db_filename}\n",
}
files["README.textile"] = scraperwiki.description unless scraperwiki.description.blank?
add_commit_to_root_on_github(forked_by, files, "Fork of code from ScraperWiki at #{scraperwiki_url}")
# Add another commit (but only if necessary) to translate the code so it runs here
unless scraperwiki.translated_code == scraperwiki.code
add_commit_to_master_on_github(forked_by, {Morph::Language.language_to_scraper_filename(scraperwiki.language) => scraperwiki.translated_code},
"Automatic update to make ScraperWiki scraper work on Morph")
end
fork_progress("Synching repository", 80)
synchronise_repo
# Forking has finished
fork_progress(nil, 100)
update_attributes(forking: false)
# TODO Add repo link
end
end
Whitespace changes only
require 'new_relic/agent/method_tracer'
class Scraper < ActiveRecord::Base
belongs_to :owner, inverse_of: :scrapers
has_many :runs, inverse_of: :scraper
has_many :metrics, through: :runs
belongs_to :forked_by, class_name: "User"
validates :name, format: { with: /\A[a-zA-Z0-9_-]+\z/, message: "can only have letters, numbers, '_' and '-'" }
has_one :last_run, -> { order "queued_at DESC" }, class_name: "Run"
has_many :contributors, through: :contributions, source: :user
has_many :contributions
extend FriendlyId
friendly_id :full_name, use: :finders
delegate :queued?, :running?, to: :last_run, allow_nil: true
# Given a scraper name on github populates the fields for a morph scraper but doesn't save it
def self.new_from_github(full_name)
repo = Octokit.repository(full_name)
repo_owner = Owner.find_by_nickname(repo.owner.login)
# Populate a new scraper with information from the repo
Scraper.new(name: repo.name, full_name: repo.full_name,
description: repo.description, github_id: repo.id, owner_id: repo_owner.id,
github_url: repo.rels[:html].href, git_url: repo.rels[:git].href)
end
# Find a user related to this scraper that we can use them to make authenticated github requests
def related_user
if owner.user?
owner
else
owner.users.first
end
end
def update_contributors
# We can't use unauthenticated requests because we will go over our rate limit
begin
c = related_user.octokit_client.contributors(full_name).map do |c|
User.find_or_create_by_nickname(c["login"])
end
rescue Octokit::NotFound
c = []
end
update_attributes(contributors: c)
end
def successful_runs
runs.includes(:log_lines).order(finished_at: :desc).select{|r| r.finished_successfully?}
end
def latest_successful_run_time
latest_successful_run = successful_runs.first
latest_successful_run.finished_at if latest_successful_run
end
def finished_runs
runs.where("finished_at IS NOT NULL").order(finished_at: :desc).includes(:log_lines, :metric)
end
# For successful runs calculates the average wall clock time that this scraper takes
# Handy for the user to know how long it should expect to run for
# Returns nil if not able to calculate this
# TODO Refactor this using scopes
def average_successful_wall_time
successful_runs.sum(&:wall_time) / successful_runs.count if successful_runs.count > 0
end
def total_wall_time
runs.to_a.sum(&:wall_time)
end
def utime
metrics.sum(:utime)
end
def stime
metrics.sum(:stime)
end
def cpu_time
utime + stime
end
def update_sqlite_db_size
update_attributes(sqlite_db_size: database.sqlite_db_size)
end
def total_disk_usage
repo_size + sqlite_db_size
end
add_method_tracer :average_successful_wall_time, 'Custom/Scraper/average_successful_wall_time'
add_method_tracer :total_wall_time, 'Custom/Scraper/total_wall_time'
add_method_tracer :cpu_time, 'Custom/Scraper/cpu_time'
add_method_tracer :total_disk_usage, 'Custom/Scraper/total_disk_usage'
def queued_or_running?
queued? || running?
end
# Let's say a scraper requires attention if it's set to run automatically and the last run failed
def requires_attention?
auto_run && last_run && last_run.finished_with_errors?
end
def self.can_write?(user, owner)
user && (owner == user || user.organizations.include?(owner))
end
def can_write?(user)
Scraper.can_write?(user, owner)
end
def destroy_repo_and_data
FileUtils::rm_rf repo_path
FileUtils::rm_rf data_path
end
def repo_path
"#{owner.repo_root}/#{name}"
end
def data_path
"#{owner.data_root}/#{name}"
end
def self.update_docker_image!
docker_command = "docker #{ENV['DOCKER_TCP'] ? "-H #{ENV['DOCKER_TCP']}" : ""}"
system("#{docker_command} pull openaustralia/morph-ruby")
system("#{docker_command} pull openaustralia/morph-php")
system("#{docker_command} pull openaustralia/morph-python")
end
def readme
f = Dir.glob(File.join(repo_path, "README*")).first
if f
GitHub::Markup.render(f, File.read(f)).html_safe
end
end
def readme_filename
Pathname.new(Dir.glob(File.join(repo_path, "README*")).first).basename.to_s
end
def github_url_readme
github_url_for_file(readme_filename)
end
def runnable?
last_run.nil? || last_run.finished?
end
# Set auto to true if this job is being queued automatically (i.e. not directly by a person)
def queue!(auto = false)
# Guard against more than one of a particular scraper running at the same time
if runnable?
run = runs.create(queued_at: Time.now, auto: auto, owner_id: owner_id)
if auto
RunWorkerAuto.perform_async(run.id)
else
RunWorker.perform_async(run.id)
end
end
end
def github_url_for_file(file)
github_url + "/blob/master/" + file
end
def language
l = Morph::Language.language(repo_path)
end
def main_scraper_filename
Morph::Language.main_scraper_filename(repo_path)
end
def github_url_main_scraper_file
github_url_for_file(main_scraper_filename)
end
def database
Morph::Database.new(self)
end
# It seems silly implementing this
def Scraper.directory_size(directory)
r = 0
if File.exists?(directory)
# Ick
files = Dir.entries(directory)
files.delete(".")
files.delete("..")
files.map{|f| File.join(directory, f)}.each do |f|
s = File.lstat(f)
if s.file?
r += s.size
else
r += Scraper.directory_size(f)
end
end
end
r
end
def update_repo_size
r = Scraper.directory_size(repo_path)
update_attribute(:repo_size, r)
r
end
def scraperwiki_shortname
# scraperwiki_url should be of the form https://classic.scraperwiki.com/scrapers/shortname/
if scraperwiki_url
m = scraperwiki_url.match(/https:\/\/classic.scraperwiki.com\/scrapers\/([-\w]+)(\/)?/)
m[1] if m
end
end
def scraperwiki_shortname=(shortname)
self.scraperwiki_url = "https://classic.scraperwiki.com/scrapers/#{shortname}/" if shortname
end
def current_revision_from_repo
r = Grit::Repo.new(repo_path)
Grit::Head.current(r).commit.id
end
# files should be a hash of "filename" => "content"
def add_commit_to_master_on_github(user, files, message)
client = user.octokit_client
blobs = files.map do |filename, content|
{
:path => filename,
:mode => "100644",
:type => "blob",
:content => content
}
end
# Let's get all the info about head
ref = client.ref(full_name, "heads/master")
commit_sha = ref.object.sha
commit = client.commit(full_name, commit_sha)
tree_sha = commit.commit.tree.sha
tree2 = client.create_tree(full_name, blobs, :base_tree => tree_sha)
commit2 = client.create_commit(full_name, message, tree2.sha, commit_sha)
client.update_ref(full_name, "heads/master", commit2.sha)
end
# Overwrites whatever there was before in that repo
# Obviously use with great care
def add_commit_to_root_on_github(user, files, message)
client = user.octokit_client
blobs = files.map do |filename, content|
{
:path => filename,
:mode => "100644",
:type => "blob",
:content => content
}
end
tree = client.create_tree(full_name, blobs)
commit = client.create_commit(full_name, message, tree.sha)
client.update_ref(full_name, "heads/master", commit.sha)
end
# progress should be between 0 and 100
def fork_progress(message, progress)
update_attributes(forking_message: message, forking_progress: progress)
end
def synchronise_repo
Morph::Github.synchronise_repo(repo_path, git_url)
update_repo_size
update_contributors
end
# Return the https version of the git clone url (git_url)
def git_url_https
"https" + git_url[3..-1]
end
def fork_from_scraperwiki!
client = forked_by.octokit_client
# We need to set auto_init so that we can create a commit later. The API doesn't support
# adding a commit to an empty repository
begin
fork_progress("Creating GitHub repository", 20)
repo = Morph::Github.create_repository(forked_by, owner, name)
update_attributes(github_id: repo.id, github_url: repo.rels[:html].href, git_url: repo.rels[:git].href)
rescue Octokit::UnprocessableEntity
# This means the repo has already been created. We will have gotten here if this background job failed at some
# point past here and is rerun. So, let's happily continue
end
scraperwiki = Morph::Scraperwiki.new(scraperwiki_shortname)
# Copy the sqlite database across from Scraperwiki
fork_progress("Forking sqlite database", 40)
database.write_sqlite_database(scraperwiki.sqlite_database)
# Rename the main table in the sqlite database
database.standardise_table_name("swdata")
fork_progress("Forking code", 60)
# Fill in description
repo = client.edit_repository(full_name, description: scraperwiki.title,
homepage: Rails.application.routes.url_helpers.scraper_url(self))
self.update_attributes(description: scraperwiki.title)
files = {
Morph::Language.language_to_scraper_filename(scraperwiki.language) => scraperwiki.code,
".gitignore" => "# Ignore output of scraper\n#{Morph::Database.sqlite_db_filename}\n",
}
files["README.textile"] = scraperwiki.description unless scraperwiki.description.blank?
add_commit_to_root_on_github(forked_by, files, "Fork of code from ScraperWiki at #{scraperwiki_url}")
# Add another commit (but only if necessary) to translate the code so it runs here
unless scraperwiki.translated_code == scraperwiki.code
add_commit_to_master_on_github(forked_by, {Morph::Language.language_to_scraper_filename(scraperwiki.language) => scraperwiki.translated_code},
"Automatic update to make ScraperWiki scraper work on Morph")
end
fork_progress("Synching repository", 80)
synchronise_repo
# Forking has finished
fork_progress(nil, 100)
update_attributes(forking: false)
# TODO Add repo link
end
end
|
class Service < ApplicationRecord
include UrlResponseChecker
include Swagger::Blocks
after_destroy do
InterfaceType.destroy_abandoned
end
swagger_schema :Service do
property :role do
key :type, :string
end
property :title do
key :type, :string
end
property :description do
key :type, :string
end
property :problem_id do
key :type, :string
end
property :version do
key :type, :string
end
end
enum role: [:iterate, :merge, :machine_learning]
has_many :projects
has_and_belongs_to_many :interface_types
validates :role, :url, :title, :version,
presence: true
validates :problem_id,
presence: true,
format: { with: /\A[\w\.\-\_]+\z/ }
validates :url,
uniqueness: true,
format: {
with: /\Ahttp(|s)\:\/\/\S+\z/,
message: I18n.t('activerecord.errors.models.service.attributes.url.regex_mismatch')
}
validate do |service|
HttpResponseValidator.validate(service) if service.url
ServiceInterfaceTypesValidator.validate(service)
end
def self.new_from_url(url)
Service.new(params_from_url(url))
rescue
false
end
def update_from_url(url)
return true if self.update(Service.params_from_url(url))
false
end
def self.params_from_url(url)
timeout = 3
Timeout::timeout(timeout) do
data = JSON.parse(URI.parse(url).read)
data['url'] = url
data['interface_types'] = InterfaceType.convert_interface_types(data['interface_types'])
return data
end
rescue Timeout::Error
raise "timeout of #{timeout} seconds to look up service exceeded"
end
def is_available?
UrlResponseChecker::check_response self.url
end
def label
self.title
end
def self.problem_identifiers
Service.distinct.pluck(:problem_id)
end
end
improve coverage of `app/validators/http_response_validator.rb`
class Service < ApplicationRecord
include UrlResponseChecker
include Swagger::Blocks
after_destroy do
InterfaceType.destroy_abandoned
end
swagger_schema :Service do
property :role do
key :type, :string
end
property :title do
key :type, :string
end
property :description do
key :type, :string
end
property :problem_id do
key :type, :string
end
property :version do
key :type, :string
end
end
enum role: [:iterate, :merge, :machine_learning]
has_many :projects
has_and_belongs_to_many :interface_types
validates :role, :url, :title, :version,
presence: true
validates :problem_id,
presence: true,
format: { with: /\A[\w\.\-\_]+\z/ }
validates :url,
uniqueness: true,
format: {
with: /\Ahttp(|s)\:\/\/\S+\z/,
message: I18n.t('activerecord.errors.models.service.attributes.url.regex_mismatch')
}
validate do |service|
HttpResponseValidator.validate(service)
ServiceInterfaceTypesValidator.validate(service)
end
def self.new_from_url(url)
Service.new(params_from_url(url))
rescue
false
end
def update_from_url(url)
return true if self.update(Service.params_from_url(url))
false
end
def self.params_from_url(url)
timeout = 3
Timeout::timeout(timeout) do
data = JSON.parse(URI.parse(url).read)
data['url'] = url
data['interface_types'] = InterfaceType.convert_interface_types(data['interface_types'])
return data
end
rescue Timeout::Error
raise "timeout of #{timeout} seconds to look up service exceeded"
end
def is_available?
UrlResponseChecker::check_response self.url
end
def label
self.title
end
def self.problem_identifiers
Service.distinct.pluck(:problem_id)
end
end
|
class Service
include Mongoid::Document
include Mongoid::Timestamps
field :organization_id, type: Integer
field :description, type: String
field :name, type: String
field :slug, type: String
field :total_records, type: Integer
field :version, type: Integer, default: 1
embeds_many :records
before_create :make_slug
validates :name, uniqueness: {case_sensitive: false}
def set_total_records
self.update(total_records: self.records.count)
end
def set_update_time
self.update(updated_at: Time.now )
end
def increment_version
self.version += 1
end
protected
def make_slug
self.slug = self.name.split(" ").map(&:downcase).join("-")
end
end
added validation that name must be present
class Service
include Mongoid::Document
include Mongoid::Timestamps
field :organization_id, type: Integer
field :description, type: String
field :name, type: String
field :slug, type: String
field :total_records, type: Integer
field :version, type: Integer, default: 1
embeds_many :records
before_create :make_slug
validates :name, presence: true, uniqueness: {case_sensitive: false}
def set_total_records
self.update(total_records: self.records.count)
end
def set_update_time
self.update(updated_at: Time.now )
end
def increment_version
self.version += 1
end
protected
def make_slug
self.slug = self.name.split(" ").map(&:downcase).join("-")
end
end
|
class Session < ActiveRecord::Base
belongs_to :event
has_many :tables
def long_name
self.name + " " + self.timeslot
end
def timeslot
self.start.strftime("%a %H:%M to ") + self.end.strftime("%a %H:%M")
end
def players
players = []
self.tables.each do |table|
table.registration_tables.each do |reg|
players.push reg.user_event.user
end
end
players
end
def players_count
players.length
end
def gms
gms = []
self.tables.each do |table|
table.game_masters.each do |gm|
gms.push gm.user_event.user
end
end
gms
end
def gm_count
gms.length
end
def total_max_players
total_max_players = 0
self.tables.each do |table|
unless table.raffle?
total_max_players = total_max_players + table.max_players
end
end
total_max_players
end
def total_gms_needed
total_max_gms = 0
self.tables.each do |table|
unless table.raffle?
total_max_gms = total_max_gms + table.gms_needed
end
end
total_max_gms
end
end
Add <=> to session
class Session < ActiveRecord::Base
belongs_to :event
has_many :tables
def long_name
self.name + " " + self.timeslot
end
def timeslot
self.start.strftime("%a %H:%M to ") + self.end.strftime("%a %H:%M")
end
def players
players = []
self.tables.each do |table|
table.registration_tables.each do |reg|
players.push reg.user_event.user
end
end
players
end
def players_count
players.length
end
def gms
gms = []
self.tables.each do |table|
table.game_masters.each do |gm|
gms.push gm.user_event.user
end
end
gms
end
def gm_count
gms.length
end
def total_max_players
total_max_players = 0
self.tables.each do |table|
unless table.raffle?
total_max_players = total_max_players + table.max_players
end
end
total_max_players
end
def total_gms_needed
total_max_gms = 0
self.tables.each do |table|
unless table.raffle?
total_max_gms = total_max_gms + table.gms_needed
end
end
total_max_gms
end
def <=> (other)
sort = self.start <=> other.start
if sort == 0
sort = self.end <=> other.end
end
if sort == 0
sort = self.long_name <=> other.long_name
end
sort
end
end
|
class Thought < ActiveRecord::Base
BLOG_DIR = "lib/blogposts/*.md"
def clean_body
ActionController::Base.helpers.strip_tags(self.body).gsub("\n", ' ')
end
def self.md_to_db
blog_files = Thought.get_md_files
blog_files.each do |blog|
thought = Thought.parse_md(blog)
@thought = Thought.find_or_create_by(title: thought[:title])
@thought.update(thought)
@thought.created_at = thought[:date] || Date.new
end
end
def self.get_md_files
Dir.glob(BLOG_DIR)
end
def self.parse_md(filename)
data = Metadown.render(File.open(filename, 'rb').read)
{title: data.metadata["title"], thumbnail: data.metadata["thumbnail"], created_at: data.metadata["date"], body: data.output}
end
end
change thoughts rb to actually do what I want
class Thought < ActiveRecord::Base
BLOG_DIR = "lib/blogposts/*.md"
def clean_body
ActionController::Base.helpers.strip_tags(self.body).gsub("\n", ' ')
end
def self.md_to_db
blog_files = Thought.get_md_files
blog_files.each do |blog|
thought = Thought.parse_md(blog)
@thought = Thought.find_or_create_by(title: thought[:title])
@thought.update(thought)
@thought.save
end
end
def self.get_md_files
Dir.glob(BLOG_DIR)
end
def self.parse_md(filename)
data = Metadown.render(File.open(filename, 'rb').read)
{title: data.metadata["title"], thumbnail: data.metadata["thumbnail"], body: data.output}
end
end
|
class Usuario < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :omniauthable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me,
:nome
attr_accessor :nome
has_one :perfil
has_many :canais
has_many :mensagens
validates :papel, inclusion: { in: %w(administrador administrador moderador usuario) }
before_validation :define_papel_padrao
after_save :cria_perfil_e_salva_nome
def cria_perfil_e_salva_nome
self.perfil ||= Perfil.new
self.perfil.nome = self.nome
self.perfil.save
true
end
def self.find_or_create_from_auth_hash(auth_hash)
if usuario = self.find_by_email(auth_hash.info.email)
usuario
else
usuario = self.create(email: auth_hash.info.email, password: Devise.friendly_token[0, 20])
usuario.nome = auth_hash.info.name
usuario
end
end
private
def define_papel_padrao
self.papel ||= 'usuario'
end
end
Corrigindo before_save callback no model usuario
class Usuario < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :omniauthable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me,
:nome
attr_accessor :nome
has_one :perfil
has_many :canais
has_many :mensagens
validates :papel, inclusion: { in: %w(administrador administrador moderador usuario) }
before_validation :define_papel_padrao
before_save do
self.perfil ||= Perfil.new
if self.nome
self.perfil.nome = self.nome
self.perfil.save
end
end
def self.find_or_create_from_auth_hash(auth_hash)
if usuario = self.find_by_email(auth_hash.info.email)
usuario
else
usuario = self.create(email: auth_hash.info.email, password: Devise.friendly_token[0, 20])
usuario.nome = auth_hash.info.name
usuario
end
end
private
def define_papel_padrao
self.papel ||= 'usuario'
end
end
|
class Variant < ActiveRecord::Base
include Moderated
include Subscribable
include WithAudits
include WithTimepointCounts
include SoftDeletable
include WithDomainExpertTags
include Flaggable
include Commentable
belongs_to :gene
belongs_to :secondary_gene, class_name: 'Gene'
has_many :evidence_items
has_many :variant_group_variants
has_many :variant_groups, through: :variant_group_variants
has_many :assertions
has_one :evidence_items_by_status
has_and_belongs_to_many :variant_types
has_and_belongs_to_many :variant_aliases
has_and_belongs_to_many :sources
has_and_belongs_to_many :hgvs_expressions
has_and_belongs_to_many :clinvar_entries
enum reference_build: [:GRCh38, :GRCh37, :NCBI36]
def self.index_scope
eager_load(:gene, :variant_types, :secondary_gene)
end
def self.view_scope
eager_load(:variant_groups, :variant_aliases, :clinvar_entries, :variant_types, :hgvs_expressions, :sources, :gene, :secondary_gene, evidence_items: [:disease, :source, :drugs, :open_changes, :assertions])
end
def self.navigation_scope
includes(:gene, :open_changes, :evidence_items_by_status, variant_groups: { variants: [:open_changes, :evidence_items_by_status, :gene] })
end
def self.datatable_scope
joins('LEFT OUTER JOIN genes ON genes.id = variants.gene_id')
.joins('INNER JOIN evidence_items ON evidence_items.variant_id = variants.id')
.joins('LEFT OUTER JOIN diseases ON diseases.id = evidence_items.disease_id')
.joins('LEFT OUTER JOIN drugs_evidence_items ON drugs_evidence_items.evidence_item_id = evidence_items.id')
.joins('LEFT OUTER JOIN drugs ON drugs.id = drugs_evidence_items.drug_id')
end
def self.typeahead_scope
joins('LEFT OUTER JOIN genes ON genes.id = variants.gene_id')
.joins('LEFT OUTER JOIN gene_aliases_genes ON gene_aliases_genes.gene_id = genes.id')
.joins('LEFT OUTER JOIN gene_aliases ON gene_aliases.id = gene_aliases_genes.gene_alias_id')
.joins('INNER JOIN evidence_items ON evidence_items.variant_id = variants.id')
.joins('LEFT OUTER JOIN diseases ON diseases.id = evidence_items.disease_id')
.joins('LEFT OUTER JOIN drugs_evidence_items ON drugs_evidence_items.evidence_item_id = evidence_items.id')
.joins('LEFT OUTER JOIN drugs ON drugs.id = drugs_evidence_items.drug_id')
.joins('LEFT OUTER JOIN variant_aliases_variants ON variants.id = variant_aliases_variants.variant_id')
.joins('LEFT OUTER JOIN variant_aliases ON variant_aliases_variants.variant_alias_id = variant_aliases.id')
end
def self.advanced_search_scope
eager_load(:variant_groups, :variant_aliases, :clinvar_entries, :variant_types, :hgvs_expressions, :sources, :gene, :secondary_gene, evidence_items: [:disease, :source, :drugs, :open_changes])
.joins(:evidence_items)
end
def assertions
evidence_items.flat_map(&:assertions).uniq
end
def parent_subscribables
[gene]
end
def display_name
name
end
def state_params
{
gene: {
id: gene.id,
name: gene.name
},
variant: {
id: self.id,
name: self.name
}
}
end
def self.timepoint_query
->(x) {
self.joins(:evidence_items)
.group('variants.id')
.select('variants.id')
.where("evidence_items.status != 'rejected'")
.having('MIN(evidence_items.created_at) >= ?', x)
.count
}
end
def lifecycle_events
{
last_modified: :last_applied_change,
last_reviewed: :last_review_event,
last_commented_on: :last_review_event,
}
end
def additional_changes_info
@@additional_variant_changes ||= {
'variant_types' => {
output_field_name: 'variant_type_ids',
creation_query: ->(x) { VariantType.find(x) },
application_query: ->(x) { VariantType.find(x) },
id_field: 'id'
},
'variant_aliases' => {
output_field_name: 'variant_alias_ids',
creation_query: ->(x) { x.map { |name| VariantAlias.get_or_create_by_name(name) } },
application_query: ->(x) { VariantAlias.find(x) },
id_field: 'id'
},
'hgvs_expressions' => {
output_field_name: 'hgvs_expression_ids',
creation_query: ->(x) { x.map { |exp| HgvsExpression.where(expression: exp).first_or_create } },
application_query: ->(x) { HgvsExpression.find(x) },
id_field: 'id'
},
'sources' => {
output_field_name: 'source_ids',
creation_query: ->(x) { Source.get_sources_from_list(x) },
application_query: ->(x) { Source.find(x) },
id_field: 'id'
},
'clinvar_entries' => {
output_field_name: 'clinvar_entry_ids',
creation_query: ->(x) { x.map { |clinvar_id| ClinvarEntry.get_or_create_by_id(clinvar_id) } },
application_query: ->(x) { ClinvarEntry.find(x) },
id_field: 'id'
}
}
end
end
Change variants endpoint to pull assertions directly associated with a variant
class Variant < ActiveRecord::Base
include Moderated
include Subscribable
include WithAudits
include WithTimepointCounts
include SoftDeletable
include WithDomainExpertTags
include Flaggable
include Commentable
belongs_to :gene
belongs_to :secondary_gene, class_name: 'Gene'
has_many :evidence_items
has_many :variant_group_variants
has_many :variant_groups, through: :variant_group_variants
has_many :assertions
has_one :evidence_items_by_status
has_and_belongs_to_many :variant_types
has_and_belongs_to_many :variant_aliases
has_and_belongs_to_many :sources
has_and_belongs_to_many :hgvs_expressions
has_and_belongs_to_many :clinvar_entries
enum reference_build: [:GRCh38, :GRCh37, :NCBI36]
def self.index_scope
eager_load(:gene, :variant_types, :secondary_gene)
end
def self.view_scope
eager_load(:variant_groups, :variant_aliases, :clinvar_entries, :variant_types, :hgvs_expressions, :sources, :gene, :secondary_gene, evidence_items: [:disease, :source, :drugs, :open_changes, :assertions])
end
def self.navigation_scope
includes(:gene, :open_changes, :evidence_items_by_status, variant_groups: { variants: [:open_changes, :evidence_items_by_status, :gene] })
end
def self.datatable_scope
joins('LEFT OUTER JOIN genes ON genes.id = variants.gene_id')
.joins('INNER JOIN evidence_items ON evidence_items.variant_id = variants.id')
.joins('LEFT OUTER JOIN diseases ON diseases.id = evidence_items.disease_id')
.joins('LEFT OUTER JOIN drugs_evidence_items ON drugs_evidence_items.evidence_item_id = evidence_items.id')
.joins('LEFT OUTER JOIN drugs ON drugs.id = drugs_evidence_items.drug_id')
end
def self.typeahead_scope
joins('LEFT OUTER JOIN genes ON genes.id = variants.gene_id')
.joins('LEFT OUTER JOIN gene_aliases_genes ON gene_aliases_genes.gene_id = genes.id')
.joins('LEFT OUTER JOIN gene_aliases ON gene_aliases.id = gene_aliases_genes.gene_alias_id')
.joins('INNER JOIN evidence_items ON evidence_items.variant_id = variants.id')
.joins('LEFT OUTER JOIN diseases ON diseases.id = evidence_items.disease_id')
.joins('LEFT OUTER JOIN drugs_evidence_items ON drugs_evidence_items.evidence_item_id = evidence_items.id')
.joins('LEFT OUTER JOIN drugs ON drugs.id = drugs_evidence_items.drug_id')
.joins('LEFT OUTER JOIN variant_aliases_variants ON variants.id = variant_aliases_variants.variant_id')
.joins('LEFT OUTER JOIN variant_aliases ON variant_aliases_variants.variant_alias_id = variant_aliases.id')
end
def self.advanced_search_scope
eager_load(:variant_groups, :variant_aliases, :clinvar_entries, :variant_types, :hgvs_expressions, :sources, :gene, :secondary_gene, evidence_items: [:disease, :source, :drugs, :open_changes])
.joins(:evidence_items)
end
def parent_subscribables
[gene]
end
def display_name
name
end
def state_params
{
gene: {
id: gene.id,
name: gene.name
},
variant: {
id: self.id,
name: self.name
}
}
end
def self.timepoint_query
->(x) {
self.joins(:evidence_items)
.group('variants.id')
.select('variants.id')
.where("evidence_items.status != 'rejected'")
.having('MIN(evidence_items.created_at) >= ?', x)
.count
}
end
def lifecycle_events
{
last_modified: :last_applied_change,
last_reviewed: :last_review_event,
last_commented_on: :last_review_event,
}
end
def additional_changes_info
@@additional_variant_changes ||= {
'variant_types' => {
output_field_name: 'variant_type_ids',
creation_query: ->(x) { VariantType.find(x) },
application_query: ->(x) { VariantType.find(x) },
id_field: 'id'
},
'variant_aliases' => {
output_field_name: 'variant_alias_ids',
creation_query: ->(x) { x.map { |name| VariantAlias.get_or_create_by_name(name) } },
application_query: ->(x) { VariantAlias.find(x) },
id_field: 'id'
},
'hgvs_expressions' => {
output_field_name: 'hgvs_expression_ids',
creation_query: ->(x) { x.map { |exp| HgvsExpression.where(expression: exp).first_or_create } },
application_query: ->(x) { HgvsExpression.find(x) },
id_field: 'id'
},
'sources' => {
output_field_name: 'source_ids',
creation_query: ->(x) { Source.get_sources_from_list(x) },
application_query: ->(x) { Source.find(x) },
id_field: 'id'
},
'clinvar_entries' => {
output_field_name: 'clinvar_entry_ids',
creation_query: ->(x) { x.map { |clinvar_id| ClinvarEntry.get_or_create_by_id(clinvar_id) } },
application_query: ->(x) { ClinvarEntry.find(x) },
id_field: 'id'
}
}
end
end
|
class Variant < ActiveRecord::Base
has_many :variant_suppliers
has_many :suppliers, :through => :variant_suppliers
has_many :variant_properties
has_many :properties, :through => :variant_properties
has_many :purchase_order_variants
has_many :purchase_orders, :through => :purchase_order_variants
belongs_to :product
belongs_to :brand
#validates :name, :presence => true
validates :price, :presence => true
validates :product_id, :presence => true
validates :sku, :presence => true
accepts_nested_attributes_for :variant_properties
OUT_OF_STOCK_QTY = 2
LOW_STOCK_QTY = 6
def sold_out?
(count_on_hand - count_pending_to_customer) <= OUT_OF_STOCK_QTY
end
def low_stock?
(count_on_hand - count_pending_to_customer) <= LOW_STOCK_QTY
end
def display_stock_status(start = '(', finish = ')')
return "#{start}Sold Out#{finish}" if self.sold_out?
return "#{start}Low Stock#{finish}" if self.low_stock?
''
end
def total_price(tax_rate)
((1 + tax_percentage(tax_rate)) * self.price)
end
def tax_percentage(tax_rate)
tax_rate ? tax_rate.percentage : 0
end
def product_tax_rate(state_id, tax_time = Time.now)
product.tax_rate(state_id, tax_time)
end
def shipping_category_id
product.shipping_category_id
end
def display_property_details(separator = '<br/>')
property_details.join(separator)
end
def property_details(separator = ': ')
variant_properties.collect {|vp| [vp.property.display_name ,vp.description].join(separator) }
end
def product_name
name? ? name : product.name + sub_name
end
def sub_name
primary_property ? "(#{primary_property.description})" : ''
end
def primary_property
pp = self.variant_properties.where(["variant_properties.primary = ?", true]).find(:first)
pp ? pp : self.variant_properties.find(:first)
end
def name_with_sku
[product_name, sku].compact.join(': ')
end
def qty_to_add
0
end
def is_available?
count_available > 0
end
def count_available(reload_variant = true)
self.reload if reload_variant
count_on_hand - count_pending_to_customer
end
def add_count_on_hand(num)
sql = "UPDATE variants SET count_on_hand = (#{num} + count_on_hand) WHERE id = #{self.id}"
ActiveRecord::Base.connection.execute(sql)
end
def subtract_count_on_hand(num)
add_count_on_hand((num * -1))
end
def add_pending_to_customer(num = 1)
sql = "UPDATE variants SET count_pending_to_customer = (#{num} + count_pending_to_customer) WHERE id = #{self.id}"
ActiveRecord::Base.connection.execute(sql)
end
def subtract_pending_to_customer(num)
add_pending_to_customer((num * -1))
end
def qty_to_add=(num)
### TODO this method needs a history of who did what
self.count_on_hand = self.count_on_hand + num.to_i
end
def self.admin_grid(product, params = {})
params[:page] ||= 1
params[:rows] ||= SETTINGS[:admin_grid_rows]
grid = Variant.where("variants.product_id", product.id)
grid = grid.includes(:product)
grid = grid.where("products.name = ?", params[:name]) if params[:name].present?
grid = grid.order("#{params[:sidx]} #{params[:sord]}")
grid = grid.limit(params[:rows])
grid.paginate({:page => params[:page]})
end
end
Fix for SQLite
class Variant < ActiveRecord::Base
has_many :variant_suppliers
has_many :suppliers, :through => :variant_suppliers
has_many :variant_properties
has_many :properties, :through => :variant_properties
has_many :purchase_order_variants
has_many :purchase_orders, :through => :purchase_order_variants
belongs_to :product
belongs_to :brand
#validates :name, :presence => true
validates :price, :presence => true
validates :product_id, :presence => true
validates :sku, :presence => true
accepts_nested_attributes_for :variant_properties
OUT_OF_STOCK_QTY = 2
LOW_STOCK_QTY = 6
def sold_out?
(count_on_hand - count_pending_to_customer) <= OUT_OF_STOCK_QTY
end
def low_stock?
(count_on_hand - count_pending_to_customer) <= LOW_STOCK_QTY
end
def display_stock_status(start = '(', finish = ')')
return "#{start}Sold Out#{finish}" if self.sold_out?
return "#{start}Low Stock#{finish}" if self.low_stock?
''
end
def total_price(tax_rate)
((1 + tax_percentage(tax_rate)) * self.price)
end
def tax_percentage(tax_rate)
tax_rate ? tax_rate.percentage : 0
end
def product_tax_rate(state_id, tax_time = Time.now)
product.tax_rate(state_id, tax_time)
end
def shipping_category_id
product.shipping_category_id
end
def display_property_details(separator = '<br/>')
property_details.join(separator)
end
def property_details(separator = ': ')
variant_properties.collect {|vp| [vp.property.display_name ,vp.description].join(separator) }
end
def product_name
name? ? name : product.name + sub_name
end
def sub_name
primary_property ? "(#{primary_property.description})" : ''
end
def primary_property
pp = self.variant_properties.where({:primary => true}).find(:first)
pp ? pp : self.variant_properties.find(:first)
end
def name_with_sku
[product_name, sku].compact.join(': ')
end
def qty_to_add
0
end
def is_available?
count_available > 0
end
def count_available(reload_variant = true)
self.reload if reload_variant
count_on_hand - count_pending_to_customer
end
def add_count_on_hand(num)
sql = "UPDATE variants SET count_on_hand = (#{num} + count_on_hand) WHERE id = #{self.id}"
ActiveRecord::Base.connection.execute(sql)
end
def subtract_count_on_hand(num)
add_count_on_hand((num * -1))
end
def add_pending_to_customer(num = 1)
sql = "UPDATE variants SET count_pending_to_customer = (#{num} + count_pending_to_customer) WHERE id = #{self.id}"
ActiveRecord::Base.connection.execute(sql)
end
def subtract_pending_to_customer(num)
add_pending_to_customer((num * -1))
end
def qty_to_add=(num)
### TODO this method needs a history of who did what
self.count_on_hand = self.count_on_hand + num.to_i
end
def self.admin_grid(product, params = {})
params[:page] ||= 1
params[:rows] ||= SETTINGS[:admin_grid_rows]
grid = Variant.where("variants.product_id", product.id)
grid = grid.includes(:product)
grid = grid.where("products.name = ?", params[:name]) if params[:name].present?
grid = grid.order("#{params[:sidx]} #{params[:sord]}")
grid = grid.limit(params[:rows])
grid.paginate({:page => params[:page]})
end
end
|
# encoding: utf-8
class Version < ActiveRecord::Base
include FriendlyId
attr_accessible :ambientacion, :coste, :fue, :numero, :rareza, :res, :senda,
:subtipo, :supertipo, :texto, :tipo, :canonica, :carta,
:imagenes_attributes, :expansion, :expansion_id, :imagen
attr_readonly :coste_convertido
belongs_to :carta, inverse_of: :versiones, touch: true
delegate :nombre, to: :carta, allow_nil: true
belongs_to :expansion, touch: true
has_many :imagenes, order: 'created_at ASC',
inverse_of: :version, dependent: :destroy
has_many :artistas, through: :imagenes
has_many :links, as: :linkeable, dependent: :destroy
has_many :slots
friendly_id :expansion_y_numero, use: :slugged
normalize_attributes :texto, :tipo, :supertipo, :subtipo, :fue, :res, :senda,
:ambientacion, :rareza, :coste
accepts_nested_attributes_for :imagenes, reject_if: :all_blank
before_save :ver_si_es_canonica, :convertir_coste
validates_uniqueness_of :numero, scope: :expansion_id, message: :no_es_unico_en_la_expansion
validates_presence_of :carta, inverse_of: :versiones
scope :costeadas, where(Version.arel_table['coste_convertido'].not_eq(nil))
scope :demonios, where(supertipo: 'Demonio')
# TODO deja afuera a los que tienen supertipo: String ('') (debería ser nil?)
scope :normales, where('supertipo <> ?', 'Demonio')
scope :caos, where(senda: 'Caos')
scope :locura, where(senda: 'Locura')
scope :muerte, where(senda: 'Muerte')
scope :poder, where(senda: 'Poder')
scope :neutral, where(senda: 'Neutral')
def self.senda_y_neutrales(senda)
where(senda: [senda, 'Neutral'])
end
# Devuelve el slot en el que esta versión está en la `lista`
def slot_en(lista)
lista.slots.where(version_id: id).first
end
def self.coste_convertido(coste = nil)
coste.present? ? coste.to_s.gsub(/\D/, '').to_i : nil
end
def numero_justificado
numero.to_s.rjust(3, '0')
end
# Para ordenar los resultados con +sort_by+
def self.prioridad_de_senda(senda)
case senda.downcase.to_sym
when :caos then 1
when :locura then 2
when :muerte then 3
when :poder then 4
when :neutral then 5
else
nil
end
end
def prioridad
Version.prioridad_de_senda(self.senda)
end
# Para copiar una versión sin expansión ni imágenes, por ejemplo para las
# reediciones
amoeba do
exclude_field :imagenes
nullify [ :expansion_id, :slug, :numero ]
end
def self.todas_las_versiones
joins(:carta, :expansion).select('cartas.nombre as nombre, versiones.*')
end
def nombre_y_expansion
self.nombre + (self.expansion.nil? ? '' : " (#{self.expansion.nombre})")
end
def demonio?
self.supertipo == 'Demonio'
end
private
# Usá `slug` para llamar a esto
def expansion_y_numero
"#{numero_justificado}-#{expansion.try(:slug) || 'huerfanas'}"
end
# La primer versión de cada carta es la canónica
def ver_si_es_canonica
unless carta.versiones.where(canonica: true).any?
self.canonica = true
end
true # Para que siga guardandola
end
def convertir_coste
self.coste_convertido = Version.coste_convertido(self.coste)
end
end
SQL nunca devuelve las nil a menos que se lo expliciten
# encoding: utf-8
class Version < ActiveRecord::Base
include FriendlyId
attr_accessible :ambientacion, :coste, :fue, :numero, :rareza, :res, :senda,
:subtipo, :supertipo, :texto, :tipo, :canonica, :carta,
:imagenes_attributes, :expansion, :expansion_id, :imagen
attr_readonly :coste_convertido
belongs_to :carta, inverse_of: :versiones, touch: true
delegate :nombre, to: :carta, allow_nil: true
belongs_to :expansion, touch: true
has_many :imagenes, order: 'created_at ASC',
inverse_of: :version, dependent: :destroy
has_many :artistas, through: :imagenes
has_many :links, as: :linkeable, dependent: :destroy
has_many :slots
friendly_id :expansion_y_numero, use: :slugged
normalize_attributes :texto, :tipo, :supertipo, :subtipo, :fue, :res, :senda,
:ambientacion, :rareza, :coste
accepts_nested_attributes_for :imagenes, reject_if: :all_blank
before_save :ver_si_es_canonica, :convertir_coste
validates_uniqueness_of :numero, scope: :expansion_id, message: :no_es_unico_en_la_expansion
validates_presence_of :carta, inverse_of: :versiones
scope :costeadas, where(Version.arel_table['coste_convertido'].not_eq(nil))
scope :demonios, where(supertipo: 'Demonio')
scope :caos, where(senda: 'Caos')
scope :locura, where(senda: 'Locura')
scope :muerte, where(senda: 'Muerte')
scope :poder, where(senda: 'Poder')
scope :neutral, where(senda: 'Neutral')
def self.normales
where arel_table[:supertipo].not_eq('Demonio').or(arel_table[:supertipo].eq(nil))
end
# Devuelve el slot en el que esta versión está en la `lista`
def slot_en(lista)
lista.slots.where(version_id: id).first
end
def self.coste_convertido(coste = nil)
coste.present? ? coste.to_s.gsub(/\D/, '').to_i : nil
end
def numero_justificado
numero.to_s.rjust(3, '0')
end
# Para ordenar los resultados con +sort_by+
def self.prioridad_de_senda(senda)
case senda.downcase.to_sym
when :caos then 1
when :locura then 2
when :muerte then 3
when :poder then 4
when :neutral then 5
else
nil
end
end
def prioridad
Version.prioridad_de_senda(self.senda)
end
# Para copiar una versión sin expansión ni imágenes, por ejemplo para las
# reediciones
amoeba do
exclude_field :imagenes
nullify [ :expansion_id, :slug, :numero ]
end
def self.todas_las_versiones
joins(:carta, :expansion).select('cartas.nombre as nombre, versiones.*')
end
def nombre_y_expansion
self.nombre + (self.expansion.nil? ? '' : " (#{self.expansion.nombre})")
end
def demonio?
self.supertipo == 'Demonio'
end
private
# Usá `slug` para llamar a esto
def expansion_y_numero
"#{numero_justificado}-#{expansion.try(:slug) || 'huerfanas'}"
end
# La primer versión de cada carta es la canónica
def ver_si_es_canonica
unless carta.versiones.where(canonica: true).any?
self.canonica = true
end
true # Para que siga guardandola
end
def convertir_coste
self.coste_convertido = Version.coste_convertido(self.coste)
end
end
|
class Version < ActiveRecord::Base
belongs_to :rubygem
has_many :dependencies, :order => 'rubygems.name ASC', :include => :rubygem, :dependent => :destroy
before_save :update_prerelease
after_validation :join_authors
after_create :full_nameify!
after_save :reorder_versions
validates :number, :format => {:with => /\A#{Gem::Version::VERSION_PATTERN}\z/}
validates :platform, :format => {:with => Rubygem::NAME_PATTERN}
validate :platform_and_number_are_unique, :on => :create
validate :authors_format, :on => :create
def self.owned_by(user)
where(:rubygem_id => user.rubygem_ids)
end
def self.subscribed_to_by(user)
where(:rubygem_id => user.subscribed_gem_ids).
by_created_at
end
def self.with_deps
includes(:dependencies)
end
def self.latest
where(:latest => true)
end
def self.prerelease
where(:prerelease => true)
end
def self.release
where(:prerelease => false)
end
def self.indexed
where(:indexed => true)
end
def self.by_position
order('position')
end
def self.by_built_at
order("versions.built_at desc")
end
def self.by_created_at
order('versions.created_at desc')
end
def self.rows_for_index
to_rows(:release)
end
def self.rows_for_latest_index
to_rows(:latest)
end
def self.rows_for_prerelease_index
to_rows(:prerelease)
end
def self.most_recent
latest.find_by_platform('ruby') || latest.first || first
end
def self.just_updated
where("versions.rubygem_id IN (SELECT versions.rubygem_id FROM versions GROUP BY versions.rubygem_id HAVING COUNT(versions.id) > 1)").
joins(:rubygem).
indexed.
by_created_at.
limit(5)
end
def self.published(limit)
where("built_at <= ?", DateTime.now.utc).
indexed.
by_built_at.
limit(limit)
end
def self.find_from_slug!(rubygem_id, slug)
rubygem = Rubygem.find(rubygem_id)
find_by_full_name!("#{rubygem.name}-#{slug}")
end
def self.rubygem_name_for(full_name)
$redis.hget(info_key(full_name), :name)
end
def self.info_key(full_name)
"v:#{full_name}"
end
def platformed?
platform != "ruby"
end
def reorder_versions
rubygem.reorder_versions
end
def yank!
update_attributes!(:indexed => false)
$redis.lrem(Rubygem.versions_key(rubygem.name), 1, full_name)
end
def unyank!
update_attributes!(:indexed => true)
push
end
def push
$redis.lpush(Rubygem.versions_key(rubygem.name), full_name)
end
def yanked?
!indexed
end
def info
[ description, summary, "This rubygem does not have a description or summary." ].detect(&:present?)
end
def update_attributes_from_gem_specification!(spec)
update_attributes!(
:authors => spec.authors,
:description => spec.description,
:summary => spec.summary,
:built_at => spec.date,
:indexed => true
)
end
def platform_as_number
if platformed?
0
else
1
end
end
def <=>(other)
self_version = self.to_gem_version
other_version = other.to_gem_version
if self_version == other_version
self.platform_as_number <=> other.platform_as_number
else
self_version <=> other_version
end
end
def slug
full_name.gsub(/^#{rubygem.name}-/, '')
end
def downloads_count
Download.for(self)
end
def payload
{
'authors' => authors,
'built_at' => built_at,
'description' => description,
'downloads_count' => downloads_count,
'number' => number,
'summary' => summary,
'platform' => platform,
'prerelease' => prerelease,
}
end
def as_json(options={})
payload
end
def to_xml(options={})
payload.to_xml(options.merge(:root => 'version'))
end
def to_s
number
end
def to_title
if platformed?
"#{rubygem.name} (#{number}-#{platform})"
else
"#{rubygem.name} (#{number})"
end
end
def to_bundler
%{gem "#{rubygem.name}", "~> #{number}"}
end
def to_gem_version
Gem::Version.new(number)
end
def to_index
[rubygem.name, to_gem_version, platform]
end
def to_install
command = "gem install #{rubygem.name}"
latest = prerelease ? rubygem.versions.by_position.prerelease.first : rubygem.versions.most_recent
command << " -v #{number}" if latest != self
command << " --pre" if prerelease
command
end
private
def self.to_rows(scope)
sql = select("rubygems.name, number, platform").
indexed.send(scope).
from("rubygems, versions").
where("rubygems.id = versions.rubygem_id").
order("rubygems.name asc, position desc").to_sql
connection.select_rows(sql)
end
def platform_and_number_are_unique
if Version.exists?(:rubygem_id => rubygem_id,
:number => number,
:platform => platform)
errors[:base] << "A version already exists with this number or platform."
end
end
def authors_format
string_authors = authors.is_a?(Array) && authors.grep(String)
if string_authors.blank? || string_authors.size != authors.size
errors.add :authors, "must be an Array of Strings"
end
end
def update_prerelease
self[:prerelease] = !!to_gem_version.prerelease?
true
end
def join_authors
self.authors = self.authors.join(', ') if self.authors.is_a?(Array)
end
def full_nameify!
self.full_name = "#{rubygem.name}-#{number}"
self.full_name << "-#{platform}" if platformed?
Version.update_all({:full_name => full_name}, {:id => id})
$redis.hmset(Version.info_key(full_name),
:name, rubygem.name,
:number, number,
:platform, platform)
push
end
end
Add limit option (default to 5) to Version.just_updated
class Version < ActiveRecord::Base
belongs_to :rubygem
has_many :dependencies, :order => 'rubygems.name ASC', :include => :rubygem, :dependent => :destroy
before_save :update_prerelease
after_validation :join_authors
after_create :full_nameify!
after_save :reorder_versions
validates :number, :format => {:with => /\A#{Gem::Version::VERSION_PATTERN}\z/}
validates :platform, :format => {:with => Rubygem::NAME_PATTERN}
validate :platform_and_number_are_unique, :on => :create
validate :authors_format, :on => :create
def self.owned_by(user)
where(:rubygem_id => user.rubygem_ids)
end
def self.subscribed_to_by(user)
where(:rubygem_id => user.subscribed_gem_ids).
by_created_at
end
def self.with_deps
includes(:dependencies)
end
def self.latest
where(:latest => true)
end
def self.prerelease
where(:prerelease => true)
end
def self.release
where(:prerelease => false)
end
def self.indexed
where(:indexed => true)
end
def self.by_position
order('position')
end
def self.by_built_at
order("versions.built_at desc")
end
def self.by_created_at
order('versions.created_at desc')
end
def self.rows_for_index
to_rows(:release)
end
def self.rows_for_latest_index
to_rows(:latest)
end
def self.rows_for_prerelease_index
to_rows(:prerelease)
end
def self.most_recent
latest.find_by_platform('ruby') || latest.first || first
end
def self.just_updated(limit=5)
where("versions.rubygem_id IN (SELECT versions.rubygem_id FROM versions GROUP BY versions.rubygem_id HAVING COUNT(versions.id) > 1)").
joins(:rubygem).
indexed.
by_created_at.
limit(limit)
end
def self.published(limit)
where("built_at <= ?", DateTime.now.utc).
indexed.
by_built_at.
limit(limit)
end
def self.find_from_slug!(rubygem_id, slug)
rubygem = Rubygem.find(rubygem_id)
find_by_full_name!("#{rubygem.name}-#{slug}")
end
def self.rubygem_name_for(full_name)
$redis.hget(info_key(full_name), :name)
end
def self.info_key(full_name)
"v:#{full_name}"
end
def platformed?
platform != "ruby"
end
def reorder_versions
rubygem.reorder_versions
end
def yank!
update_attributes!(:indexed => false)
$redis.lrem(Rubygem.versions_key(rubygem.name), 1, full_name)
end
def unyank!
update_attributes!(:indexed => true)
push
end
def push
$redis.lpush(Rubygem.versions_key(rubygem.name), full_name)
end
def yanked?
!indexed
end
def info
[ description, summary, "This rubygem does not have a description or summary." ].detect(&:present?)
end
def update_attributes_from_gem_specification!(spec)
update_attributes!(
:authors => spec.authors,
:description => spec.description,
:summary => spec.summary,
:built_at => spec.date,
:indexed => true
)
end
def platform_as_number
if platformed?
0
else
1
end
end
def <=>(other)
self_version = self.to_gem_version
other_version = other.to_gem_version
if self_version == other_version
self.platform_as_number <=> other.platform_as_number
else
self_version <=> other_version
end
end
def slug
full_name.gsub(/^#{rubygem.name}-/, '')
end
def downloads_count
Download.for(self)
end
def payload
{
'authors' => authors,
'built_at' => built_at,
'description' => description,
'downloads_count' => downloads_count,
'number' => number,
'summary' => summary,
'platform' => platform,
'prerelease' => prerelease,
}
end
def as_json(options={})
payload
end
def to_xml(options={})
payload.to_xml(options.merge(:root => 'version'))
end
def to_s
number
end
def to_title
if platformed?
"#{rubygem.name} (#{number}-#{platform})"
else
"#{rubygem.name} (#{number})"
end
end
def to_bundler
%{gem "#{rubygem.name}", "~> #{number}"}
end
def to_gem_version
Gem::Version.new(number)
end
def to_index
[rubygem.name, to_gem_version, platform]
end
def to_install
command = "gem install #{rubygem.name}"
latest = prerelease ? rubygem.versions.by_position.prerelease.first : rubygem.versions.most_recent
command << " -v #{number}" if latest != self
command << " --pre" if prerelease
command
end
private
def self.to_rows(scope)
sql = select("rubygems.name, number, platform").
indexed.send(scope).
from("rubygems, versions").
where("rubygems.id = versions.rubygem_id").
order("rubygems.name asc, position desc").to_sql
connection.select_rows(sql)
end
def platform_and_number_are_unique
if Version.exists?(:rubygem_id => rubygem_id,
:number => number,
:platform => platform)
errors[:base] << "A version already exists with this number or platform."
end
end
def authors_format
string_authors = authors.is_a?(Array) && authors.grep(String)
if string_authors.blank? || string_authors.size != authors.size
errors.add :authors, "must be an Array of Strings"
end
end
def update_prerelease
self[:prerelease] = !!to_gem_version.prerelease?
true
end
def join_authors
self.authors = self.authors.join(', ') if self.authors.is_a?(Array)
end
def full_nameify!
self.full_name = "#{rubygem.name}-#{number}"
self.full_name << "-#{platform}" if platformed?
Version.update_all({:full_name => full_name}, {:id => id})
$redis.hmset(Version.info_key(full_name),
:name, rubygem.name,
:number, number,
:platform, platform)
push
end
end
|
class VmScan < Job
#
# TODO: until we get location/offset read capability for OpenStack
# image data, OpenStack fleecing is prone to timeout (based on image size).
# We adjust the queue timeout in server_smart_proxy.rb, but that's not enough,
# we also need to adjust the job timeout here.
#
DEFAULT_TIMEOUT = defined?(RSpec) ? 300 : 3000
def self.current_job_timeout(timeout_adjustment = 1)
timeout_adjustment = 1 if defined?(RSpec)
DEFAULT_TIMEOUT * timeout_adjustment
end
def load_transitions
self.state ||= 'initialize'
{
:initializing => {'initialize' => 'waiting_to_start'},
:snapshot_delete => {'scanning' => 'snapshot_delete'},
:broker_unavailable => {'snapshot_create' => 'wait_for_broker'},
:scan_retry => {'scanning' => 'scanning'},
:abort_retry => {'scanning' => 'scanning'},
:abort_job => {'*' => 'aborting'},
:cancel => {'*' => 'canceling'},
:finish => {'*' => 'finished'},
:error => {'*' => '*'},
:start => {'waiting_to_start' => 'wait_for_policy'},
:start_snapshot => {'wait_for_policy' => 'snapshot_create',
'wait_for_broker' => 'snapshot_create'},
:snapshot_complete => {'snapshot_create' => 'scanning',
'snapshot_delete' => 'synchronizing'},
:data => {'snapshot_create' => 'scanning',
'scanning' => 'scanning',
'snapshot_delete' => 'snapshot_delete',
'synchronizing' => 'synchronizing',
'finished' => 'finished'}
}
end
def call_check_policy
_log.info "Enter"
begin
vm = VmOrTemplate.find(target_id)
q_options = {
:miq_callback => {
:class_name => self.class.to_s,
:instance_id => id,
:method_name => :check_policy_complete,
:args => [MiqServer.my_zone] # Store the zone where the scan job was initiated.
}
}
inputs = {:vm => vm, :host => vm.host}
MiqEvent.raise_evm_job_event(vm, {:type => "scan", :suffix => "start"}, inputs, q_options)
rescue => err
_log.log_backtrace(err)
signal(:abort, err.message, "error")
end
end
def check_policy_complete(from_zone, status, message, result)
unless status == 'ok'
_log.error("Status = #{status}, message = #{message}")
signal(:abort, message, "error")
return
end
if result.kind_of?(MiqAeEngine::MiqAeWorkspaceRuntime)
event = result.get_obj_from_path("/")['event_stream']
data = event.attributes["full_data"]
prof_policies = data.fetch_path(:policy, :actions, :assign_scan_profile) if data
if prof_policies
scan_profiles = []
prof_policies.each { |p| scan_profiles += p[:result] unless p[:result].nil? }
options[:scan_profiles] = scan_profiles unless scan_profiles.blank?
end
end
MiqQueue.put(
:class_name => self.class.to_s,
:instance_id => id,
:method_name => "signal",
:args => [:start_snapshot],
:zone => from_zone,
:role => "smartstate"
)
end
def call_snapshot_create
_log.info "Enter"
begin
vm = VmOrTemplate.find(target_id)
context[:snapshot_mor] = nil
options[:snapshot] = :skipped
options[:use_existing_snapshot] = false
# TODO: should this logic be moved to a VM subclass implementation?
# or, make type-specific Job classes.
if vm.kind_of?(ManageIQ::Providers::Openstack::CloudManager::Vm) ||
vm.kind_of?(ManageIQ::Providers::Microsoft::InfraManager::Vm)
return unless create_snapshot(vm)
elsif vm.kind_of?(ManageIQ::Providers::Azure::CloudManager::Vm) && vm.require_snapshot_for_scan?
return unless create_snapshot(vm)
elsif vm.require_snapshot_for_scan?
proxy = MiqServer.find(miq_server_id)
# Check if the broker is available
if MiqServer.use_broker_for_embedded_proxy? && !MiqVimBrokerWorker.available?
_log.warn("VimBroker is not available")
signal(:broker_unavailable)
return
end
if proxy && proxy.forceVmScan
options[:snapshot] = :smartProxy
_log.info("Skipping snapshot creation, it will be performed by the SmartProxy")
context[:snapshot_mor] = options[:snapshot_description] = snapshotDescription("(embedded)")
start_user_event_message(vm)
else
set_status("Creating VM snapshot")
return unless create_snapshot(vm)
end
else
start_user_event_message(vm)
end
signal(:snapshot_complete)
rescue => err
_log.log_backtrace(err)
signal(:abort, err.message, "error")
return
rescue Timeout::Error
msg = case options[:snapshot]
when :smartProxy, :skipped then "Request to log snapshot user event with EMS timed out."
else "Request to create snapshot timed out"
end
_log.error(msg)
signal(:abort, msg, "error")
end
end
def wait_for_vim_broker
_log.info "Enter"
i = 0
loop do
set_status("Waiting for VimBroker to become available (#{i += 1})")
sleep(60)
_log.info "Checking VimBroker connection status. Count=[#{i}]"
break if MiqVimBrokerWorker.available?
end
signal(:start_snapshot)
end
def call_scan
_log.info "Enter"
begin
host = MiqServer.find(miq_server_id)
vm = VmOrTemplate.find(target_id)
# Send down metadata to allow the host to make decisions.
scan_args = create_scan_args(vm)
options[:ems_list] = ems_list = scan_args["ems"]
options[:categories] = vm.scan_profile_categories(scan_args["vmScanProfiles"])
# If the host supports VixDisk Lib then we need to validate that the host has the required credentials set.
if vm.vendor == 'vmware'
scan_ci_type = ems_list['connect_to']
if host.is_vix_disk? && ems_list[scan_ci_type] && (ems_list[scan_ci_type][:username].nil? || ems_list[scan_ci_type][:password].nil?)
context[:snapshot_mor] = nil unless options[:snapshot] == :created
raise _("no credentials defined for %{type} %{name}") % {:type => scan_ci_type,
:name => ems_list[scan_ci_type][:hostname]}
end
end
if ems_list[scan_ci_type]
_log.info "[#{host.name}] communicates with [#{scan_ci_type}:#{ems_list[scan_ci_type][:hostname]}"\
"(#{ems_list[scan_ci_type][:address]})] to scan vm [#{vm.name}]"
end
vm.scan_metadata(options[:categories], "taskid" => jobid, "host" => host, "args" => [YAML.dump(scan_args)])
rescue Timeout::Error
message = "timed out attempting to scan, aborting"
_log.error(message)
signal(:abort, message, "error")
return
rescue => message
_log.error(message.to_s)
_log.error(message.backtrace.join("\n"))
signal(:abort, message.message, "error")
end
set_status("Scanning for metadata from VM")
end
def config_snapshot
snapshot = {"use_existing" => options[:use_existing_snapshot],
"description" => options[:snapshot_description]}
snapshot['create_free_percent'] = ::Settings.snapshots.create_free_percent
snapshot['remove_free_percent'] = ::Settings.snapshots.remove_free_percent
snapshot
end
def config_ems_list(vm)
ems_list = vm.ems_host_list
ems_list['connect_to'] = vm.scan_via_ems? ? 'ems' : 'host'
# Disable connecting to EMS for COS SmartProxy. Embedded Proxy will
# enable this if needed in the scan_sync_vm method in server_smart_proxy.rb.
ems_list['connect'] = false if vm.vendor == 'redhat'
ems_list
end
def create_scan_args(vm)
scan_args = {"ems" => config_ems_list(vm), "snapshot" => config_snapshot}
# Check if Policy returned scan profiles to use, otherwise use the default profile if available.
scan_args["vmScanProfiles"] = options[:scan_profiles] || vm.scan_profile_list
scan_args['snapshot']['forceFleeceDefault'] = false if vm.scan_via_ems? && vm.template?
scan_args['permissions'] = {'group' => 36} if vm.vendor == 'redhat'
scan_args
end
def call_snapshot_delete
_log.info "Enter"
# TODO: remove snapshot here if Vm was running
vm = VmOrTemplate.find(target_id)
if context[:snapshot_mor]
mor = context[:snapshot_mor]
context[:snapshot_mor] = nil
if options[:snapshot] == :smartProxy
set_status("Snapshot delete was performed by the SmartProxy")
else
set_status("Deleting VM snapshot: reference: [#{mor}]")
end
if vm.ext_management_system
_log.info("Deleting snapshot: reference: [#{mor}]")
begin
# TODO: should this logic be moved to a VM subclass implementation?
# or, make type-specific Job classes.
if vm.kind_of?(ManageIQ::Providers::Openstack::CloudManager::Vm)
vm.ext_management_system.vm_delete_evm_snapshot(vm, mor)
elsif vm.kind_of?(ManageIQ::Providers::Microsoft::InfraManager::Vm) ||
vm.kind_of?(ManageIQ::Providers::Azure::CloudManager::Vm)
vm.ext_management_system.vm_delete_evm_snapshot(vm, :snMor => mor)
else
delete_snapshot(mor)
end
rescue => err
_log.error(err.to_s)
return
rescue Timeout::Error
msg = "Request to delete snapshot timed out"
_log.error(msg)
end
unless options[:snapshot] == :smartProxy
_log.info("Deleted snapshot: reference: [#{mor}]")
set_status("Snapshot deleted: reference: [#{mor}]")
end
else
_log.error("Deleting snapshot: reference: [#{mor}], No #{ui_lookup(:table => "ext_management_systems")} available to delete snapshot")
set_status("No #{ui_lookup(:table => "ext_management_systems")} available to delete snapshot, skipping", "error")
end
else
set_status("Snapshot was not taken, delete not required") if options[:snapshot] == :skipped
end_user_event_message(vm)
end
signal(:snapshot_complete)
end
def call_synchronize
_log.info "Enter"
begin
host = MiqServer.find(miq_server_id)
vm = VmOrTemplate.find(target_id)
vm.sync_metadata(options[:categories],
"taskid" => jobid,
"host" => host
)
rescue Timeout::Error
message = "timed out attempting to synchronize, aborting"
_log.error(message)
signal(:abort, message, "error")
return
rescue => message
_log.error(message.to_s)
signal(:abort, message.message, "error")
return
end
set_status("Synchronizing metadata from VM")
dispatch_finish # let the dispatcher know that it is ok to start the next job since we are no longer holding then snapshot.
end
def synchronizing
_log.info "."
end
def scanning
_log.info "." if context[:scan_attempted]
context[:scan_attempted] = true
end
def process_data(*args)
_log.info "starting..."
data = args.first
set_status("Processing VM data")
doc = MiqXml.load(data)
_log.info "Document=#{doc.root.name.downcase}"
if doc.root.name.downcase == "summary"
doc.root.each_element do |s|
case s.name.downcase
when "syncmetadata"
request_docs = []
all_docs = []
s.each_element do |e|
_log.info("Summary XML [#{e}]")
request_docs << e.attributes['original_filename'] if e.attributes['items_total'] && e.attributes['items_total'].to_i.zero?
all_docs << e.attributes['original_filename']
end
if request_docs.empty? || (request_docs.length != all_docs.length)
_log.info("sending :finish")
vm = VmOrTemplate.find_by(:id => target_id)
# Collect any VIM data here
# TODO: Make this a separate state?
if vm.respond_to?(:refresh_on_scan)
begin
vm.refresh_on_scan
rescue => err
_log.error("refreshing data from VIM: #{err.message}")
_log.log_backtrace(err)
end
vm.reload
end
# Generate the vm state from the model upon completion
begin
vm.save_drift_state unless vm.nil?
rescue => err
_log.error("saving VM drift state: #{err.message}")
_log.log_backtrace(err)
end
signal(:finish, "Process completed successfully", "ok")
begin
raise _("Unable to find Vm") if vm.nil?
inputs = {:vm => vm, :host => vm.host}
MiqEvent.raise_evm_job_event(vm, {:type => "scan", :suffix => "complete"}, inputs)
rescue => err
_log.warn("#{err.message}, unable to raise policy event: [vm_scan_complete]")
end
else
message = "scan operation yielded no data. aborting"
_log.error(message)
signal(:abort, message, "error")
end
when "scanmetadata"
_log.info("sending :synchronize")
vm = VmOrTemplate.find(options[:target_id])
result = vm.save_scan_history(s.attributes.to_h(false).merge("taskid" => doc.root.attributes["taskid"])) if s.attributes
if result.status_code == 16 # fatal error on proxy
signal(:abort_retry, result.message, "error", false)
else
signal(:snapshot_delete)
end
else
_log.info("no action taken")
end
end
end
# got data to process
end
def delete_snapshot(mor, vm = nil)
vm ||= VmOrTemplate.find(target_id)
if mor
begin
if vm.ext_management_system
if options[:snapshot] == :smartProxy
end_user_event_message(vm)
delete_snapshot_by_description(mor, vm)
else
user_event = end_user_event_message(vm, false)
vm.ext_management_system.vm_remove_snapshot(vm, :snMor => mor, :user_event => user_event)
end
else
raise _("No %{table} available to delete snapshot") %
{:table => ui_lookup(:table => "ext_management_systems")}
end
rescue => err
_log.error(err.message)
_log.debug err.backtrace.join("\n")
end
else
end_user_event_message(vm)
end
end
def delete_snapshot_by_description(mor, vm)
if mor
ems_type = 'host'
options[:ems_list] = vm.ems_host_list
miqVimHost = options[:ems_list][ems_type]
miqVim = nil
# Make sure we were given a host to connect to and have a non-nil encrypted password
if miqVimHost && !miqVimHost[:password].nil?
begin
password_decrypt = MiqPassword.decrypt(miqVimHost[:password])
if MiqServer.use_broker_for_embedded_proxy?(ems_type)
$vim_broker_client ||= MiqVimBroker.new(:client, MiqVimBrokerWorker.drb_port)
miqVim = $vim_broker_client.getMiqVim(miqVimHost[:address], miqVimHost[:username], password_decrypt)
else
require 'VMwareWebService/MiqVim'
miqVim = MiqVim.new(miqVimHost[:address], miqVimHost[:username], password_decrypt)
end
vimVm = miqVim.getVimVm(vm.path)
vimVm.removeSnapshotByDescription(mor, true) unless vimVm.nil?
ensure
vimVm.release if vimVm rescue nil
miqVim.disconnect unless miqVim.nil?
end
end
end
end
def start_user_event_message(vm, send = true)
return if vm.vendor == "amazon"
user_event = "EVM SmartState Analysis Initiated for VM [#{vm.name}]"
log_user_event(user_event, vm) if send
user_event
end
def end_user_event_message(vm, send = true)
return if vm.vendor == "amazon"
user_event = "EVM SmartState Analysis completed for VM [#{vm.name}]"
unless options[:end_message_sent]
log_user_event(user_event, vm) if send
options[:end_message_sent] = true
end
user_event
end
def snapshotDescription(type = nil)
Snapshot.evm_snapshot_description(jobid, type)
end
def process_cancel(*args)
options = args.first || {}
_log.info "job canceling, #{options[:message]}"
begin
delete_snapshot(context[:snapshot_mor])
rescue => err
_log.log_backtrace(err)
end
super
end
# Logic to determine if we should abort the job or retry the scan depending on the error
def call_abort_retry(*args)
message, status, skip_retry = args
if message.to_s.include?("Could not find VM: [") && options[:scan_count].to_i.zero?
# We may need to skip calling the retry if this method is called twice.
return if skip_retry == true
options[:scan_count] = options[:scan_count].to_i + 1
vm = VmOrTemplate.find(target_id)
EmsRefresh.refresh(vm)
vm.reload
_log.info("Retrying VM scan for [#{vm.name}] due to error [#{message}]")
signal(:scan_retry)
else
signal(:abort, *args[0, 2])
end
end
def process_abort(*args)
begin
vm = VmOrTemplate.find_by(:id => target_id)
unless context[:snapshot_mor].nil?
mor = context[:snapshot_mor]
context[:snapshot_mor] = nil
set_status("Deleting snapshot before aborting job")
if vm.kind_of?(ManageIQ::Providers::Openstack::CloudManager::Vm)
vm.ext_management_system.vm_delete_evm_snapshot(vm, mor)
elsif vm.kind_of?(ManageIQ::Providers::Microsoft::InfraManager::Vm) ||
vm.kind_of?(ManageIQ::Providers::Azure::CloudManager::Vm)
vm.ext_management_system.vm_delete_evm_snapshot(vm, :snMor => mor)
else
delete_snapshot(mor)
end
end
if vm
inputs = {:vm => vm, :host => vm.host}
MiqEvent.raise_evm_job_event(vm, {:type => "scan", :suffix => "abort"}, inputs)
end
rescue => err
_log.log_backtrace(err)
end
super
end
# Signals
def snapshot_complete
if state == 'scanning'
scanning
call_scan
else
call_synchronize
end
end
def data(*args)
process_data(*args)
if state == 'scanning'
scanning
elsif state == 'synchronizing'
synchronizing
# state == 'snapshot_delete'
# do nothing?
end
end
def scan_retry
scanning
call_scan
end
def abort_retry(*args)
scanning
call_abort_retry(*args)
end
# All other signals
alias_method :initializing, :dispatch_start
alias_method :start, :call_check_policy
alias_method :start_snapshot, :call_snapshot_create
alias_method :snapshot_delete, :call_snapshot_delete
alias_method :broker_unavailable, :wait_for_vim_broker
alias_method :abort_job, :process_abort
alias_method :cancel, :process_cancel
alias_method :finish, :process_finished
alias_method :error, :process_error
private
def create_snapshot(vm)
if vm.ext_management_system
sn_description = snapshotDescription
_log.info("Creating snapshot, description: [#{sn_description}]")
user_event = start_user_event_message(vm, false)
options[:snapshot] = :server
begin
# TODO: should this be a vm method?
sn = vm.ext_management_system.vm_create_evm_snapshot(vm, :desc => sn_description, :user_event => user_event).to_s
rescue Exception => err
msg = "Failed to create evm snapshot with EMS. Error: [#{err.class.name}]: [#{err}]"
_log.error(msg)
err.kind_of?(MiqException::MiqVimBrokerUnavailable) ? signal(:broker_unavailable) : signal(:abort, msg, "error")
return false
end
context[:snapshot_mor] = sn
_log.info("Created snapshot, description: [#{sn_description}], reference: [#{context[:snapshot_mor]}]")
set_status("Snapshot created: reference: [#{context[:snapshot_mor]}]")
options[:snapshot] = :created
options[:use_existing_snapshot] = true
return true
else
signal(:abort, "No #{ui_lookup(:table => "ext_management_systems")} available to create snapshot, skipping", "error")
return false
end
end
def log_user_event(user_event, vm)
if vm.ext_management_system
begin
vm.ext_management_system.vm_log_user_event(vm, user_event)
rescue => err
_log.warn "Failed to log user event with EMS. Error: [#{err.class.name}]: #{err} Event message [#{user_event}]"
end
end
end
end
Check if Vm Requires a Snapshot before Deleting Snapshot
Review comment pointed out that while we are validating that a VM requires
a snapshot (for a managed disk) before taking the snapshot, we are not
checking that the snapshot is required before deleting it either in the
success or abort case.
class VmScan < Job
#
# TODO: until we get location/offset read capability for OpenStack
# image data, OpenStack fleecing is prone to timeout (based on image size).
# We adjust the queue timeout in server_smart_proxy.rb, but that's not enough,
# we also need to adjust the job timeout here.
#
DEFAULT_TIMEOUT = defined?(RSpec) ? 300 : 3000
def self.current_job_timeout(timeout_adjustment = 1)
timeout_adjustment = 1 if defined?(RSpec)
DEFAULT_TIMEOUT * timeout_adjustment
end
def load_transitions
self.state ||= 'initialize'
{
:initializing => {'initialize' => 'waiting_to_start'},
:snapshot_delete => {'scanning' => 'snapshot_delete'},
:broker_unavailable => {'snapshot_create' => 'wait_for_broker'},
:scan_retry => {'scanning' => 'scanning'},
:abort_retry => {'scanning' => 'scanning'},
:abort_job => {'*' => 'aborting'},
:cancel => {'*' => 'canceling'},
:finish => {'*' => 'finished'},
:error => {'*' => '*'},
:start => {'waiting_to_start' => 'wait_for_policy'},
:start_snapshot => {'wait_for_policy' => 'snapshot_create',
'wait_for_broker' => 'snapshot_create'},
:snapshot_complete => {'snapshot_create' => 'scanning',
'snapshot_delete' => 'synchronizing'},
:data => {'snapshot_create' => 'scanning',
'scanning' => 'scanning',
'snapshot_delete' => 'snapshot_delete',
'synchronizing' => 'synchronizing',
'finished' => 'finished'}
}
end
def call_check_policy
_log.info "Enter"
begin
vm = VmOrTemplate.find(target_id)
q_options = {
:miq_callback => {
:class_name => self.class.to_s,
:instance_id => id,
:method_name => :check_policy_complete,
:args => [MiqServer.my_zone] # Store the zone where the scan job was initiated.
}
}
inputs = {:vm => vm, :host => vm.host}
MiqEvent.raise_evm_job_event(vm, {:type => "scan", :suffix => "start"}, inputs, q_options)
rescue => err
_log.log_backtrace(err)
signal(:abort, err.message, "error")
end
end
def check_policy_complete(from_zone, status, message, result)
unless status == 'ok'
_log.error("Status = #{status}, message = #{message}")
signal(:abort, message, "error")
return
end
if result.kind_of?(MiqAeEngine::MiqAeWorkspaceRuntime)
event = result.get_obj_from_path("/")['event_stream']
data = event.attributes["full_data"]
prof_policies = data.fetch_path(:policy, :actions, :assign_scan_profile) if data
if prof_policies
scan_profiles = []
prof_policies.each { |p| scan_profiles += p[:result] unless p[:result].nil? }
options[:scan_profiles] = scan_profiles unless scan_profiles.blank?
end
end
MiqQueue.put(
:class_name => self.class.to_s,
:instance_id => id,
:method_name => "signal",
:args => [:start_snapshot],
:zone => from_zone,
:role => "smartstate"
)
end
def call_snapshot_create
_log.info "Enter"
begin
vm = VmOrTemplate.find(target_id)
context[:snapshot_mor] = nil
options[:snapshot] = :skipped
options[:use_existing_snapshot] = false
# TODO: should this logic be moved to a VM subclass implementation?
# or, make type-specific Job classes.
if vm.kind_of?(ManageIQ::Providers::Openstack::CloudManager::Vm) ||
vm.kind_of?(ManageIQ::Providers::Microsoft::InfraManager::Vm)
return unless create_snapshot(vm)
elsif vm.kind_of?(ManageIQ::Providers::Azure::CloudManager::Vm) && vm.require_snapshot_for_scan?
return unless create_snapshot(vm)
elsif vm.require_snapshot_for_scan?
proxy = MiqServer.find(miq_server_id)
# Check if the broker is available
if MiqServer.use_broker_for_embedded_proxy? && !MiqVimBrokerWorker.available?
_log.warn("VimBroker is not available")
signal(:broker_unavailable)
return
end
if proxy && proxy.forceVmScan
options[:snapshot] = :smartProxy
_log.info("Skipping snapshot creation, it will be performed by the SmartProxy")
context[:snapshot_mor] = options[:snapshot_description] = snapshotDescription("(embedded)")
start_user_event_message(vm)
else
set_status("Creating VM snapshot")
return unless create_snapshot(vm)
end
else
start_user_event_message(vm)
end
signal(:snapshot_complete)
rescue => err
_log.log_backtrace(err)
signal(:abort, err.message, "error")
return
rescue Timeout::Error
msg = case options[:snapshot]
when :smartProxy, :skipped then "Request to log snapshot user event with EMS timed out."
else "Request to create snapshot timed out"
end
_log.error(msg)
signal(:abort, msg, "error")
end
end
def wait_for_vim_broker
_log.info "Enter"
i = 0
loop do
set_status("Waiting for VimBroker to become available (#{i += 1})")
sleep(60)
_log.info "Checking VimBroker connection status. Count=[#{i}]"
break if MiqVimBrokerWorker.available?
end
signal(:start_snapshot)
end
def call_scan
_log.info "Enter"
begin
host = MiqServer.find(miq_server_id)
vm = VmOrTemplate.find(target_id)
# Send down metadata to allow the host to make decisions.
scan_args = create_scan_args(vm)
options[:ems_list] = ems_list = scan_args["ems"]
options[:categories] = vm.scan_profile_categories(scan_args["vmScanProfiles"])
# If the host supports VixDisk Lib then we need to validate that the host has the required credentials set.
if vm.vendor == 'vmware'
scan_ci_type = ems_list['connect_to']
if host.is_vix_disk? && ems_list[scan_ci_type] && (ems_list[scan_ci_type][:username].nil? || ems_list[scan_ci_type][:password].nil?)
context[:snapshot_mor] = nil unless options[:snapshot] == :created
raise _("no credentials defined for %{type} %{name}") % {:type => scan_ci_type,
:name => ems_list[scan_ci_type][:hostname]}
end
end
if ems_list[scan_ci_type]
_log.info "[#{host.name}] communicates with [#{scan_ci_type}:#{ems_list[scan_ci_type][:hostname]}"\
"(#{ems_list[scan_ci_type][:address]})] to scan vm [#{vm.name}]"
end
vm.scan_metadata(options[:categories], "taskid" => jobid, "host" => host, "args" => [YAML.dump(scan_args)])
rescue Timeout::Error
message = "timed out attempting to scan, aborting"
_log.error(message)
signal(:abort, message, "error")
return
rescue => message
_log.error(message.to_s)
_log.error(message.backtrace.join("\n"))
signal(:abort, message.message, "error")
end
set_status("Scanning for metadata from VM")
end
def config_snapshot
snapshot = {"use_existing" => options[:use_existing_snapshot],
"description" => options[:snapshot_description]}
snapshot['create_free_percent'] = ::Settings.snapshots.create_free_percent
snapshot['remove_free_percent'] = ::Settings.snapshots.remove_free_percent
snapshot
end
def config_ems_list(vm)
ems_list = vm.ems_host_list
ems_list['connect_to'] = vm.scan_via_ems? ? 'ems' : 'host'
# Disable connecting to EMS for COS SmartProxy. Embedded Proxy will
# enable this if needed in the scan_sync_vm method in server_smart_proxy.rb.
ems_list['connect'] = false if vm.vendor == 'redhat'
ems_list
end
def create_scan_args(vm)
scan_args = {"ems" => config_ems_list(vm), "snapshot" => config_snapshot}
# Check if Policy returned scan profiles to use, otherwise use the default profile if available.
scan_args["vmScanProfiles"] = options[:scan_profiles] || vm.scan_profile_list
scan_args['snapshot']['forceFleeceDefault'] = false if vm.scan_via_ems? && vm.template?
scan_args['permissions'] = {'group' => 36} if vm.vendor == 'redhat'
scan_args
end
def call_snapshot_delete
_log.info "Enter"
# TODO: remove snapshot here if Vm was running
vm = VmOrTemplate.find(target_id)
if context[:snapshot_mor]
mor = context[:snapshot_mor]
context[:snapshot_mor] = nil
if options[:snapshot] == :smartProxy
set_status("Snapshot delete was performed by the SmartProxy")
else
set_status("Deleting VM snapshot: reference: [#{mor}]")
end
if vm.ext_management_system
_log.info("Deleting snapshot: reference: [#{mor}]")
begin
# TODO: should this logic be moved to a VM subclass implementation?
# or, make type-specific Job classes.
if vm.kind_of?(ManageIQ::Providers::Openstack::CloudManager::Vm)
vm.ext_management_system.vm_delete_evm_snapshot(vm, mor)
elsif vm.kind_of?(ManageIQ::Providers::Microsoft::InfraManager::Vm) ||
(vm.kind_of?(ManageIQ::Providers::Azure::CloudManager::Vm) && vm.require_snapshot_for_scan?)
vm.ext_management_system.vm_delete_evm_snapshot(vm, :snMor => mor)
else
delete_snapshot(mor)
end
rescue => err
_log.error(err.to_s)
return
rescue Timeout::Error
msg = "Request to delete snapshot timed out"
_log.error(msg)
end
unless options[:snapshot] == :smartProxy
_log.info("Deleted snapshot: reference: [#{mor}]")
set_status("Snapshot deleted: reference: [#{mor}]")
end
else
_log.error("Deleting snapshot: reference: [#{mor}], No #{ui_lookup(:table => "ext_management_systems")} available to delete snapshot")
set_status("No #{ui_lookup(:table => "ext_management_systems")} available to delete snapshot, skipping", "error")
end
else
set_status("Snapshot was not taken, delete not required") if options[:snapshot] == :skipped
end_user_event_message(vm)
end
signal(:snapshot_complete)
end
def call_synchronize
_log.info "Enter"
begin
host = MiqServer.find(miq_server_id)
vm = VmOrTemplate.find(target_id)
vm.sync_metadata(options[:categories],
"taskid" => jobid,
"host" => host
)
rescue Timeout::Error
message = "timed out attempting to synchronize, aborting"
_log.error(message)
signal(:abort, message, "error")
return
rescue => message
_log.error(message.to_s)
signal(:abort, message.message, "error")
return
end
set_status("Synchronizing metadata from VM")
dispatch_finish # let the dispatcher know that it is ok to start the next job since we are no longer holding then snapshot.
end
def synchronizing
_log.info "."
end
def scanning
_log.info "." if context[:scan_attempted]
context[:scan_attempted] = true
end
def process_data(*args)
_log.info "starting..."
data = args.first
set_status("Processing VM data")
doc = MiqXml.load(data)
_log.info "Document=#{doc.root.name.downcase}"
if doc.root.name.downcase == "summary"
doc.root.each_element do |s|
case s.name.downcase
when "syncmetadata"
request_docs = []
all_docs = []
s.each_element do |e|
_log.info("Summary XML [#{e}]")
request_docs << e.attributes['original_filename'] if e.attributes['items_total'] && e.attributes['items_total'].to_i.zero?
all_docs << e.attributes['original_filename']
end
if request_docs.empty? || (request_docs.length != all_docs.length)
_log.info("sending :finish")
vm = VmOrTemplate.find_by(:id => target_id)
# Collect any VIM data here
# TODO: Make this a separate state?
if vm.respond_to?(:refresh_on_scan)
begin
vm.refresh_on_scan
rescue => err
_log.error("refreshing data from VIM: #{err.message}")
_log.log_backtrace(err)
end
vm.reload
end
# Generate the vm state from the model upon completion
begin
vm.save_drift_state unless vm.nil?
rescue => err
_log.error("saving VM drift state: #{err.message}")
_log.log_backtrace(err)
end
signal(:finish, "Process completed successfully", "ok")
begin
raise _("Unable to find Vm") if vm.nil?
inputs = {:vm => vm, :host => vm.host}
MiqEvent.raise_evm_job_event(vm, {:type => "scan", :suffix => "complete"}, inputs)
rescue => err
_log.warn("#{err.message}, unable to raise policy event: [vm_scan_complete]")
end
else
message = "scan operation yielded no data. aborting"
_log.error(message)
signal(:abort, message, "error")
end
when "scanmetadata"
_log.info("sending :synchronize")
vm = VmOrTemplate.find(options[:target_id])
result = vm.save_scan_history(s.attributes.to_h(false).merge("taskid" => doc.root.attributes["taskid"])) if s.attributes
if result.status_code == 16 # fatal error on proxy
signal(:abort_retry, result.message, "error", false)
else
signal(:snapshot_delete)
end
else
_log.info("no action taken")
end
end
end
# got data to process
end
def delete_snapshot(mor, vm = nil)
vm ||= VmOrTemplate.find(target_id)
if mor
begin
if vm.ext_management_system
if options[:snapshot] == :smartProxy
end_user_event_message(vm)
delete_snapshot_by_description(mor, vm)
else
user_event = end_user_event_message(vm, false)
vm.ext_management_system.vm_remove_snapshot(vm, :snMor => mor, :user_event => user_event)
end
else
raise _("No %{table} available to delete snapshot") %
{:table => ui_lookup(:table => "ext_management_systems")}
end
rescue => err
_log.error(err.message)
_log.debug err.backtrace.join("\n")
end
else
end_user_event_message(vm)
end
end
def delete_snapshot_by_description(mor, vm)
if mor
ems_type = 'host'
options[:ems_list] = vm.ems_host_list
miqVimHost = options[:ems_list][ems_type]
miqVim = nil
# Make sure we were given a host to connect to and have a non-nil encrypted password
if miqVimHost && !miqVimHost[:password].nil?
begin
password_decrypt = MiqPassword.decrypt(miqVimHost[:password])
if MiqServer.use_broker_for_embedded_proxy?(ems_type)
$vim_broker_client ||= MiqVimBroker.new(:client, MiqVimBrokerWorker.drb_port)
miqVim = $vim_broker_client.getMiqVim(miqVimHost[:address], miqVimHost[:username], password_decrypt)
else
require 'VMwareWebService/MiqVim'
miqVim = MiqVim.new(miqVimHost[:address], miqVimHost[:username], password_decrypt)
end
vimVm = miqVim.getVimVm(vm.path)
vimVm.removeSnapshotByDescription(mor, true) unless vimVm.nil?
ensure
vimVm.release if vimVm rescue nil
miqVim.disconnect unless miqVim.nil?
end
end
end
end
def start_user_event_message(vm, send = true)
return if vm.vendor == "amazon"
user_event = "EVM SmartState Analysis Initiated for VM [#{vm.name}]"
log_user_event(user_event, vm) if send
user_event
end
def end_user_event_message(vm, send = true)
return if vm.vendor == "amazon"
user_event = "EVM SmartState Analysis completed for VM [#{vm.name}]"
unless options[:end_message_sent]
log_user_event(user_event, vm) if send
options[:end_message_sent] = true
end
user_event
end
def snapshotDescription(type = nil)
Snapshot.evm_snapshot_description(jobid, type)
end
def process_cancel(*args)
options = args.first || {}
_log.info "job canceling, #{options[:message]}"
begin
delete_snapshot(context[:snapshot_mor])
rescue => err
_log.log_backtrace(err)
end
super
end
# Logic to determine if we should abort the job or retry the scan depending on the error
def call_abort_retry(*args)
message, status, skip_retry = args
if message.to_s.include?("Could not find VM: [") && options[:scan_count].to_i.zero?
# We may need to skip calling the retry if this method is called twice.
return if skip_retry == true
options[:scan_count] = options[:scan_count].to_i + 1
vm = VmOrTemplate.find(target_id)
EmsRefresh.refresh(vm)
vm.reload
_log.info("Retrying VM scan for [#{vm.name}] due to error [#{message}]")
signal(:scan_retry)
else
signal(:abort, *args[0, 2])
end
end
def process_abort(*args)
begin
vm = VmOrTemplate.find_by(:id => target_id)
unless context[:snapshot_mor].nil?
mor = context[:snapshot_mor]
context[:snapshot_mor] = nil
set_status("Deleting snapshot before aborting job")
if vm.kind_of?(ManageIQ::Providers::Openstack::CloudManager::Vm)
vm.ext_management_system.vm_delete_evm_snapshot(vm, mor)
elsif vm.kind_of?(ManageIQ::Providers::Microsoft::InfraManager::Vm) ||
(vm.kind_of?(ManageIQ::Providers::Azure::CloudManager::Vm) && vm.require_snapshot_for_scan?)
vm.ext_management_system.vm_delete_evm_snapshot(vm, :snMor => mor)
else
delete_snapshot(mor)
end
end
if vm
inputs = {:vm => vm, :host => vm.host}
MiqEvent.raise_evm_job_event(vm, {:type => "scan", :suffix => "abort"}, inputs)
end
rescue => err
_log.log_backtrace(err)
end
super
end
# Signals
def snapshot_complete
if state == 'scanning'
scanning
call_scan
else
call_synchronize
end
end
def data(*args)
process_data(*args)
if state == 'scanning'
scanning
elsif state == 'synchronizing'
synchronizing
# state == 'snapshot_delete'
# do nothing?
end
end
def scan_retry
scanning
call_scan
end
def abort_retry(*args)
scanning
call_abort_retry(*args)
end
# All other signals
alias_method :initializing, :dispatch_start
alias_method :start, :call_check_policy
alias_method :start_snapshot, :call_snapshot_create
alias_method :snapshot_delete, :call_snapshot_delete
alias_method :broker_unavailable, :wait_for_vim_broker
alias_method :abort_job, :process_abort
alias_method :cancel, :process_cancel
alias_method :finish, :process_finished
alias_method :error, :process_error
private
def create_snapshot(vm)
if vm.ext_management_system
sn_description = snapshotDescription
_log.info("Creating snapshot, description: [#{sn_description}]")
user_event = start_user_event_message(vm, false)
options[:snapshot] = :server
begin
# TODO: should this be a vm method?
sn = vm.ext_management_system.vm_create_evm_snapshot(vm, :desc => sn_description, :user_event => user_event).to_s
rescue Exception => err
msg = "Failed to create evm snapshot with EMS. Error: [#{err.class.name}]: [#{err}]"
_log.error(msg)
err.kind_of?(MiqException::MiqVimBrokerUnavailable) ? signal(:broker_unavailable) : signal(:abort, msg, "error")
return false
end
context[:snapshot_mor] = sn
_log.info("Created snapshot, description: [#{sn_description}], reference: [#{context[:snapshot_mor]}]")
set_status("Snapshot created: reference: [#{context[:snapshot_mor]}]")
options[:snapshot] = :created
options[:use_existing_snapshot] = true
return true
else
signal(:abort, "No #{ui_lookup(:table => "ext_management_systems")} available to create snapshot, skipping", "error")
return false
end
end
def log_user_event(user_event, vm)
if vm.ext_management_system
begin
vm.ext_management_system.vm_log_user_event(vm, user_event)
rescue => err
_log.warn "Failed to log user event with EMS. Error: [#{err.class.name}]: #{err} Event message [#{user_event}]"
end
end
end
end
|
# coding: utf-8
class Website < ActiveRecord::Base
attr_accessible :blog_id, :can_users_create_accounts, :cardsave_active,
:cardsave_merchant_id, :cardsave_password, :cardsave_pre_shared_key,
:css_url, :default_locale, :domain, :email, :footer_html,
:google_analytics_code, :google_domain_name, :google_ftp_password,
:google_ftp_username, :invoice_details, :name, :page_image_size,
:page_thumbnail_size, :paypal_active, :paypal_email_address,
:paypal_identity_token, :private, :product_image_size,
:product_thumbnail_size, :rbswp_active, :rbswp_installation_id,
:rbswp_payment_response_password, :rbswp_test_mode, :shipping_amount,
:shop, :show_vat_inclusive_prices, :skip_payment, :subdomain,
:terms_and_conditions, :use_default_css, :vat_number
validates_uniqueness_of :google_analytics_code, :allow_blank => true
validates_format_of :google_analytics_code, :with => /\AUA-\d\d\d\d\d\d(\d)?(\d)?-\d\Z/, :allow_blank => true
validates_presence_of :name
validates_inclusion_of :private, :in => [true, false]
validates_inclusion_of :render_blog_before_content, :in => [true, false]
# RBS WorldPay validations
validates_inclusion_of :rbswp_active, :in => [true, false]
validates_inclusion_of :rbswp_test_mode, :in => [true, false]
# these details are required only if RBS WorldPay is active
validates_presence_of :rbswp_installation_id, :if => Proc.new { |website| website.rbswp_active? }
validates_presence_of :rbswp_payment_response_password, :if => Proc.new { |website| website.rbswp_active? }
has_one :preferred_delivery_date_settings, :dependent => :delete
has_many :countries, :order => :name, :dependent => :destroy
has_many :discounts, :order => :name
has_many :liquid_templates, :order => :name, :dependent => :destroy
has_many :products, :order => :name, :dependent => :destroy
has_many :google_products, class_name: 'Product', conditions: { submit_to_google: true }
has_many :product_groups
has_many :orders, :order => 'created_at DESC', :dependent => :destroy
has_many :pages, :order => 'name', :dependent => :destroy
has_many :images, :dependent => :destroy
has_many :forums, :dependent => :destroy
has_many :enquiries, :dependent => :destroy
has_many :shipping_zones, :order => 'name', :dependent => :destroy
has_many :shipping_classes, :through => :shipping_zones
has_many :shipping_table_rows, :finder_sql =>
'SELECT `shipping_table_rows`.* ' +
'FROM `shipping_table_rows` ' +
'INNER JOIN `shipping_classes` ON `shipping_table_rows`.shipping_class_id = `shipping_classes`.id ' +
'INNER JOIN `shipping_zones` ON `shipping_classes`.shipping_zone_id = `shipping_zones`.id ' +
'WHERE ((`shipping_zones`.website_id = #{id})) ' +
'ORDER BY `shipping_table_rows`.trigger'
has_many :users, :order => 'name', :dependent => :destroy
belongs_to :blog, :class_name => 'Forum'
after_create :populate_countries
def self.for(domain, subdomains)
website = find_by_domain(domain)
unless subdomains.blank?
website ||= find_by_subdomain(subdomains.first)
end
website
end
def shipping_countries
c = countries.where('shipping_zone_id IS NOT NULL')
c.empty? ? countries : c
end
def only_accept_payment_on_account?
accept_payment_on_account and !(rbswp_active)
end
def populate_countries
countries << Country.create([
{ :name => 'Afghanistan', :iso_3166_1_alpha_2 => 'AF' },
{ :name => 'Åland Islands', :iso_3166_1_alpha_2 => 'AX' },
{ :name => 'Albania', :iso_3166_1_alpha_2 => 'AL' },
{ :name => 'Algeria', :iso_3166_1_alpha_2 => 'DZ' },
{ :name => 'American Samoa', :iso_3166_1_alpha_2 => 'AS' },
{ :name => 'Andorra', :iso_3166_1_alpha_2 => 'AD' },
{ :name => 'Angola', :iso_3166_1_alpha_2 => 'AO' },
{ :name => 'Anguilla', :iso_3166_1_alpha_2 => 'AI' },
{ :name => 'Antarctica', :iso_3166_1_alpha_2 => 'AQ' },
{ :name => 'Antigua and Barbuda', :iso_3166_1_alpha_2 => 'AG' },
{ :name => 'Argentina', :iso_3166_1_alpha_2 => 'AR' },
{ :name => 'Armenia', :iso_3166_1_alpha_2 => 'AM' },
{ :name => 'Aruba', :iso_3166_1_alpha_2 => 'AW' },
{ :name => 'Australia', :iso_3166_1_alpha_2 => 'AU' },
{ :name => 'Austria', :iso_3166_1_alpha_2 => 'AT' },
{ :name => 'Azerbaijan', :iso_3166_1_alpha_2 => 'AZ' },
{ :name => 'Bahamas', :iso_3166_1_alpha_2 => 'BS' },
{ :name => 'Bahrain', :iso_3166_1_alpha_2 => 'BH' },
{ :name => 'Bangladesh', :iso_3166_1_alpha_2 => 'BD' },
{ :name => 'Barbados', :iso_3166_1_alpha_2 => 'BB' },
{ :name => 'Belarus', :iso_3166_1_alpha_2 => 'BY' },
{ :name => 'Belgium', :iso_3166_1_alpha_2 => 'BE' },
{ :name => 'Belize', :iso_3166_1_alpha_2 => 'BZ' },
{ :name => 'Benin', :iso_3166_1_alpha_2 => 'BJ' },
{ :name => 'Bermuda', :iso_3166_1_alpha_2 => 'BM' },
{ :name => 'Bhutan', :iso_3166_1_alpha_2 => 'BT' },
{ :name => 'Bolivia', :iso_3166_1_alpha_2 => 'BO' },
{ :name => 'Bonaire, Sint Eustatius and Saba', :iso_3166_1_alpha_2 => 'BQ' },
{ :name => 'Bosnia and Herzegovina', :iso_3166_1_alpha_2 => 'BA' },
{ :name => 'Botswana', :iso_3166_1_alpha_2 => 'BW' },
{ :name => 'Bouvet Island', :iso_3166_1_alpha_2 => 'BV' },
{ :name => 'Brazil', :iso_3166_1_alpha_2 => 'BR' },
{ :name => 'British Indian Ocean Territory', :iso_3166_1_alpha_2 => 'IO' },
{ :name => 'Brunei', :iso_3166_1_alpha_2 => 'BN' },
{ :name => 'Bulgaria', :iso_3166_1_alpha_2 => 'BG' },
{ :name => 'Burkina Faso', :iso_3166_1_alpha_2 => 'BF' },
{ :name => 'Burundi', :iso_3166_1_alpha_2 => 'BI' },
{ :name => 'Cambodia', :iso_3166_1_alpha_2 => 'KH' },
{ :name => 'Cameroon', :iso_3166_1_alpha_2 => 'CM' },
{ :name => 'Canada', :iso_3166_1_alpha_2 => 'CA' },
{ :name => 'Cape Verde', :iso_3166_1_alpha_2 => 'CV' },
{ :name => 'Cayman Islands', :iso_3166_1_alpha_2 => 'KY' },
{ :name => 'Central African Republic', :iso_3166_1_alpha_2 => 'CF' },
{ :name => 'Chad', :iso_3166_1_alpha_2 => 'TD' },
{ :name => 'Chile', :iso_3166_1_alpha_2 => 'CL' },
{ :name => 'China', :iso_3166_1_alpha_2 => 'CN' },
{ :name => 'Christmas Island', :iso_3166_1_alpha_2 => 'CX' },
{ :name => 'Cocos (Keeling) Islands', :iso_3166_1_alpha_2 => 'CC' },
{ :name => 'Colombia', :iso_3166_1_alpha_2 => 'CO' },
{ :name => 'Comoros', :iso_3166_1_alpha_2 => 'KM' },
{ :name => 'Congo', :iso_3166_1_alpha_2 => 'CG' },
{ :name => 'Congo, the Democratic Republic of', :iso_3166_1_alpha_2 => 'CD' },
{ :name => 'Cook Islands', :iso_3166_1_alpha_2 => 'CK' },
{ :name => 'Costa Rica', :iso_3166_1_alpha_2 => 'CR' },
{ :name => 'Côte d\'Ivoire', :iso_3166_1_alpha_2 => 'CI' },
{ :name => 'Croatia', :iso_3166_1_alpha_2 => 'HR' },
{ :name => 'Cuba', :iso_3166_1_alpha_2 => 'CU' },
{ :name => 'Curaçao', :iso_3166_1_alpha_2 => 'CW' },
{ :name => 'Cyprus', :iso_3166_1_alpha_2 => 'CY' },
{ :name => 'Czech Republic', :iso_3166_1_alpha_2 => 'CZ' },
{ :name => 'Denmark', :iso_3166_1_alpha_2 => 'DK' },
{ :name => 'Djibouti', :iso_3166_1_alpha_2 => 'DJ' },
{ :name => 'Dominica', :iso_3166_1_alpha_2 => 'DM' },
{ :name => 'Dominican Republic', :iso_3166_1_alpha_2 => 'DO' },
{ :name => 'Ecuador', :iso_3166_1_alpha_2 => 'EC' },
{ :name => 'Egypt', :iso_3166_1_alpha_2 => 'EG' },
{ :name => 'El Salvador', :iso_3166_1_alpha_2 => 'SV' },
{ :name => 'Equatorial Guinea', :iso_3166_1_alpha_2 => 'GQ' },
{ :name => 'Eritrea', :iso_3166_1_alpha_2 => 'ER' },
{ :name => 'Estonia', :iso_3166_1_alpha_2 => 'EE' },
{ :name => 'Ethiopia', :iso_3166_1_alpha_2 => 'ET' },
{ :name => 'Falkland Islands (Malvinas)', :iso_3166_1_alpha_2 => 'FK' },
{ :name => 'Faroe Islands', :iso_3166_1_alpha_2 => 'FO' },
{ :name => 'Fiji', :iso_3166_1_alpha_2 => 'FJ' },
{ :name => 'Finland', :iso_3166_1_alpha_2 => 'FI' },
{ :name => 'France', :iso_3166_1_alpha_2 => 'FR' },
{ :name => 'French Guiana', :iso_3166_1_alpha_2 => 'GF' },
{ :name => 'French Polynesia', :iso_3166_1_alpha_2 => 'PF' },
{ :name => 'French Southern Territories', :iso_3166_1_alpha_2 => 'TF' },
{ :name => 'Gabon', :iso_3166_1_alpha_2 => 'GA' },
{ :name => 'Gambia', :iso_3166_1_alpha_2 => 'GM' },
{ :name => 'Georgia', :iso_3166_1_alpha_2 => 'GE' },
{ :name => 'Germany', :iso_3166_1_alpha_2 => 'DE' },
{ :name => 'Ghana', :iso_3166_1_alpha_2 => 'GH' },
{ :name => 'Gibraltar', :iso_3166_1_alpha_2 => 'GI' },
{ :name => 'Greece', :iso_3166_1_alpha_2 => 'GR' },
{ :name => 'Greenland', :iso_3166_1_alpha_2 => 'GL' },
{ :name => 'Grenada', :iso_3166_1_alpha_2 => 'GD' },
{ :name => 'Guadeloupe', :iso_3166_1_alpha_2 => 'GP' },
{ :name => 'Guam', :iso_3166_1_alpha_2 => 'GU' },
{ :name => 'Guatemala', :iso_3166_1_alpha_2 => 'GT' },
{ :name => 'Guernsey', :iso_3166_1_alpha_2 => 'GG' },
{ :name => 'Guinea', :iso_3166_1_alpha_2 => 'GN' },
{ :name => 'Guinea-Bissau', :iso_3166_1_alpha_2 => 'GW' },
{ :name => 'Guyana', :iso_3166_1_alpha_2 => 'GY' },
{ :name => 'Haiti', :iso_3166_1_alpha_2 => 'HT' },
{ :name => 'Heard Island and McDonald Islands', :iso_3166_1_alpha_2 => 'HM' },
{ :name => 'Holy See (Vatican City State)', :iso_3166_1_alpha_2 => 'VA' },
{ :name => 'Honduras', :iso_3166_1_alpha_2 => 'HN' },
{ :name => 'Hong Kong', :iso_3166_1_alpha_2 => 'HK' },
{ :name => 'Hungary', :iso_3166_1_alpha_2 => 'HU' },
{ :name => 'Iceland', :iso_3166_1_alpha_2 => 'IS' },
{ :name => 'India', :iso_3166_1_alpha_2 => 'IN' },
{ :name => 'Indonesia', :iso_3166_1_alpha_2 => 'ID' },
{ :name => 'Iran', :iso_3166_1_alpha_2 => 'IR' },
{ :name => 'Iraq', :iso_3166_1_alpha_2 => 'IQ' },
{ :name => 'Ireland', :iso_3166_1_alpha_2 => 'IE' },
{ :name => 'Isle of Man', :iso_3166_1_alpha_2 => 'IM' },
{ :name => 'Israel', :iso_3166_1_alpha_2 => 'IS' },
{ :name => 'Italy', :iso_3166_1_alpha_2 => 'IT' },
{ :name => 'Jamaica', :iso_3166_1_alpha_2 => 'JM' },
{ :name => 'Japan', :iso_3166_1_alpha_2 => 'JP' },
{ :name => 'Jersey', :iso_3166_1_alpha_2 => 'JE' },
{ :name => 'Jordan', :iso_3166_1_alpha_2 => 'JO' },
{ :name => 'Kazakhstan', :iso_3166_1_alpha_2 => 'KZ' },
{ :name => 'Kenya', :iso_3166_1_alpha_2 => 'KE' },
{ :name => 'Kiribati', :iso_3166_1_alpha_2 => 'KI' },
{ :name => 'Kuwait', :iso_3166_1_alpha_2 => 'KW' },
{ :name => 'Kyrgyzstan', :iso_3166_1_alpha_2 => 'KG' },
{ :name => 'Lao People\'s Democratic Republic', :iso_3166_1_alpha_2 => 'LA' },
{ :name => 'Latvia', :iso_3166_1_alpha_2 => 'LV' },
{ :name => 'Lebanon', :iso_3166_1_alpha_2 => 'LB' },
{ :name => 'Lesotho', :iso_3166_1_alpha_2 => 'LS' },
{ :name => 'Liberia', :iso_3166_1_alpha_2 => 'LR' },
{ :name => 'Libya', :iso_3166_1_alpha_2 => 'LY' },
{ :name => 'Liechtenstein', :iso_3166_1_alpha_2 => 'LI' },
{ :name => 'Lithuania', :iso_3166_1_alpha_2 => 'LT' },
{ :name => 'Luxembourg', :iso_3166_1_alpha_2 => 'LU' },
{ :name => 'Macao', :iso_3166_1_alpha_2 => 'MO' },
{ :name => 'Macedonia, the former Yugoslav Republic of', :iso_3166_1_alpha_2 => 'MK' },
{ :name => 'Madagascar', :iso_3166_1_alpha_2 => 'MG' },
{ :name => 'Malawi', :iso_3166_1_alpha_2 => 'MW' },
{ :name => 'Malaysia', :iso_3166_1_alpha_2 => 'MY' },
{ :name => 'Maldives', :iso_3166_1_alpha_2 => 'MV' },
{ :name => 'Mali', :iso_3166_1_alpha_2 => 'ML' },
{ :name => 'Malta', :iso_3166_1_alpha_2 => 'MT' },
{ :name => 'Marshall Islands', :iso_3166_1_alpha_2 => 'MH' },
{ :name => 'Martinique', :iso_3166_1_alpha_2 => 'MQ' },
{ :name => 'Mauritania', :iso_3166_1_alpha_2 => 'MR' },
{ :name => 'Mauritius', :iso_3166_1_alpha_2 => 'MU' },
{ :name => 'Mayotte', :iso_3166_1_alpha_2 => 'YT' },
{ :name => 'Mexico', :iso_3166_1_alpha_2 => 'MX' },
{ :name => 'Micronesia, Federated States of', :iso_3166_1_alpha_2 => 'FM' },
{ :name => 'Moldova', :iso_3166_1_alpha_2 => 'MD' },
{ :name => 'Monaco', :iso_3166_1_alpha_2 => 'MC' },
{ :name => 'Mongolia', :iso_3166_1_alpha_2 => 'MN' },
{ :name => 'Montenegro', :iso_3166_1_alpha_2 => 'ME' },
{ :name => 'Montserrat', :iso_3166_1_alpha_2 => 'MS' },
{ :name => 'Morocco', :iso_3166_1_alpha_2 => 'MA' },
{ :name => 'Mozambique', :iso_3166_1_alpha_2 => 'MZ' },
{ :name => 'Myanmar', :iso_3166_1_alpha_2 => 'MM' },
{ :name => 'Namibia', :iso_3166_1_alpha_2 => 'NA' },
{ :name => 'Nauru', :iso_3166_1_alpha_2 => 'NR' },
{ :name => 'Nepal', :iso_3166_1_alpha_2 => 'NP' },
{ :name => 'Netherlands', :iso_3166_1_alpha_2 => 'NL' },
{ :name => 'New Caledonia', :iso_3166_1_alpha_2 => 'NC' },
{ :name => 'New Zealand', :iso_3166_1_alpha_2 => 'NZ' },
{ :name => 'Nicaragua', :iso_3166_1_alpha_2 => 'NI' },
{ :name => 'Niger', :iso_3166_1_alpha_2 => 'NE' },
{ :name => 'Nigeria', :iso_3166_1_alpha_2 => 'NG' },
{ :name => 'Niue', :iso_3166_1_alpha_2 => 'NU' },
{ :name => 'Norfolk Island', :iso_3166_1_alpha_2 => 'NF' },
{ :name => 'North Korea', :iso_3166_1_alpha_2 => 'KP' },
{ :name => 'Northern Mariana Islands', :iso_3166_1_alpha_2 => 'MP' },
{ :name => 'Norway', :iso_3166_1_alpha_2 => 'NO' },
{ :name => 'Oman', :iso_3166_1_alpha_2 => 'OM' },
{ :name => 'Pakistan', :iso_3166_1_alpha_2 => 'PK' },
{ :name => 'Palau', :iso_3166_1_alpha_2 => 'PW' },
{ :name => 'Palestinian Territory, Occupied', :iso_3166_1_alpha_2 => 'PS' },
{ :name => 'Panama', :iso_3166_1_alpha_2 => 'PA' },
{ :name => 'Papua New Guinea', :iso_3166_1_alpha_2 => 'PG' },
{ :name => 'Paraguay', :iso_3166_1_alpha_2 => 'PY' },
{ :name => 'Peru', :iso_3166_1_alpha_2 => 'PE' },
{ :name => 'Philippines', :iso_3166_1_alpha_2 => 'PH' },
{ :name => 'Pitcairn', :iso_3166_1_alpha_2 => 'PN' },
{ :name => 'Poland', :iso_3166_1_alpha_2 => 'PL' },
{ :name => 'Portugal', :iso_3166_1_alpha_2 => 'PT' },
{ :name => 'Puerto Rico', :iso_3166_1_alpha_2 => 'PR' },
{ :name => 'Qatar', :iso_3166_1_alpha_2 => 'QA' },
{ :name => 'Réunion', :iso_3166_1_alpha_2 => 'RE' },
{ :name => 'Romania', :iso_3166_1_alpha_2 => 'RO' },
{ :name => 'Russia', :iso_3166_1_alpha_2 => 'RU' },
{ :name => 'Rwanda', :iso_3166_1_alpha_2 => 'RW' },
{ :name => 'Saint Barthélemy', :iso_3166_1_alpha_2 => 'BL' },
{ :name => 'Saint Helena, Ascension and Tristan da Cunha', :iso_3166_1_alpha_2 => 'SH' },
{ :name => 'Saint Kitts and Nevis', :iso_3166_1_alpha_2 => 'KN' },
{ :name => 'Saint Lucia', :iso_3166_1_alpha_2 => 'LC' },
{ :name => 'Saint Martin (French part)', :iso_3166_1_alpha_2 => 'MF' },
{ :name => 'Saint Pierre and Miquelon', :iso_3166_1_alpha_2 => 'PM' },
{ :name => 'Saint Vincent and the Grenadines', :iso_3166_1_alpha_2 => 'VC' },
{ :name => 'Samoa', :iso_3166_1_alpha_2 => 'WS' },
{ :name => 'San Marino', :iso_3166_1_alpha_2 => 'SM' },
{ :name => 'Sao Tome and Principe', :iso_3166_1_alpha_2 => 'ST' },
{ :name => 'Saudi Arabia', :iso_3166_1_alpha_2 => 'SA' },
{ :name => 'Senegal', :iso_3166_1_alpha_2 => 'SN' },
{ :name => 'Serbia', :iso_3166_1_alpha_2 => 'RS' },
{ :name => 'Seychelles', :iso_3166_1_alpha_2 => 'SC' },
{ :name => 'Sierra Leone', :iso_3166_1_alpha_2 => 'SL' },
{ :name => 'Singapore', :iso_3166_1_alpha_2 => 'SG' },
{ :name => 'Sint Maarten (Dutch part)', :iso_3166_1_alpha_2 => 'SX' },
{ :name => 'Slovakia', :iso_3166_1_alpha_2 => 'SK' },
{ :name => 'Slovenia', :iso_3166_1_alpha_2 => 'SI' },
{ :name => 'Solomon Islands', :iso_3166_1_alpha_2 => 'SB' },
{ :name => 'Somalia', :iso_3166_1_alpha_2 => 'SO' },
{ :name => 'South Africa', :iso_3166_1_alpha_2 => 'ZA' },
{ :name => 'South Georgia and the South Sandwich Islands', :iso_3166_1_alpha_2 => 'GS' },
{ :name => 'South Korea', :iso_3166_1_alpha_2 => 'KR' },
{ :name => 'Spain', :iso_3166_1_alpha_2 => 'ES' },
{ :name => 'Sri Lanka', :iso_3166_1_alpha_2 => 'LK' },
{ :name => 'Sudan', :iso_3166_1_alpha_2 => 'SD' },
{ :name => 'Suriname', :iso_3166_1_alpha_2 => 'SR' },
{ :name => 'Svalbard and Jan Mayen', :iso_3166_1_alpha_2 => 'SJ' },
{ :name => 'Swaziland', :iso_3166_1_alpha_2 => 'SZ' },
{ :name => 'Sweden', :iso_3166_1_alpha_2 => 'SE' },
{ :name => 'Switzerland', :iso_3166_1_alpha_2 => 'CH' },
{ :name => 'Syria', :iso_3166_1_alpha_2 => 'SY' },
{ :name => 'Taiwan, Province of China', :iso_3166_1_alpha_2 => 'TW' },
{ :name => 'Tajikistan', :iso_3166_1_alpha_2 => 'TJ' },
{ :name => 'Tanzania', :iso_3166_1_alpha_2 => 'TZ' },
{ :name => 'Thailand', :iso_3166_1_alpha_2 => 'TH' },
{ :name => 'Timor-Lest', :iso_3166_1_alpha_2 => 'TL' },
{ :name => 'Togo', :iso_3166_1_alpha_2 => 'TG' },
{ :name => 'Tokelau', :iso_3166_1_alpha_2 => 'TK' },
{ :name => 'Tonga', :iso_3166_1_alpha_2 => 'TO' },
{ :name => 'Trinidad and Tobago', :iso_3166_1_alpha_2 => 'TT' },
{ :name => 'Tunisia', :iso_3166_1_alpha_2 => 'TN' },
{ :name => 'Turkey', :iso_3166_1_alpha_2 => 'TR' },
{ :name => 'Turkmenistan', :iso_3166_1_alpha_2 => 'TM' },
{ :name => 'Turks and Caicos Islands', :iso_3166_1_alpha_2 => 'TC' },
{ :name => 'Tuvalu', :iso_3166_1_alpha_2 => 'TV' },
{ :name => 'Uganda', :iso_3166_1_alpha_2 => 'UG' },
{ :name => 'Ukraine', :iso_3166_1_alpha_2 => 'UA' },
{ :name => 'United Arab Emirates', :iso_3166_1_alpha_2 => 'AE' },
{ :name => 'United Kingdom', :iso_3166_1_alpha_2 => 'GB' },
{ :name => 'United States', :iso_3166_1_alpha_2 => 'US' },
{ :name => 'United States Minor Outlying Islands', :iso_3166_1_alpha_2 => 'UM' },
{ :name => 'Uruguay', :iso_3166_1_alpha_2 => 'UY' },
{ :name => 'Uzbekistan', :iso_3166_1_alpha_2 => 'UZ' },
{ :name => 'Vanuatu', :iso_3166_1_alpha_2 => 'VU' },
{ :name => 'Venezuela', :iso_3166_1_alpha_2 => 'VE' },
{ :name => 'Vietnam', :iso_3166_1_alpha_2 => 'VN' },
{ :name => 'Virgin Islands, British', :iso_3166_1_alpha_2 => 'VG' },
{ :name => 'Virgin Islands, U.S.', :iso_3166_1_alpha_2 => 'VI' },
{ :name => 'Wallis and Futuna', :iso_3166_1_alpha_2 => 'WF' },
{ :name => 'Western Sahara', :iso_3166_1_alpha_2 => 'EH' },
{ :name => 'Yemen', :iso_3166_1_alpha_2 => 'YE' },
{ :name => 'Zambia', :iso_3166_1_alpha_2 => 'ZM' },
{ :name => 'Zimbabwe', :iso_3166_1_alpha_2 => 'ZW' }
])
end
end
Fix Israel ISO code
# coding: utf-8
class Website < ActiveRecord::Base
attr_accessible :blog_id, :can_users_create_accounts, :cardsave_active,
:cardsave_merchant_id, :cardsave_password, :cardsave_pre_shared_key,
:css_url, :default_locale, :domain, :email, :footer_html,
:google_analytics_code, :google_domain_name, :google_ftp_password,
:google_ftp_username, :invoice_details, :name, :page_image_size,
:page_thumbnail_size, :paypal_active, :paypal_email_address,
:paypal_identity_token, :private, :product_image_size,
:product_thumbnail_size, :rbswp_active, :rbswp_installation_id,
:rbswp_payment_response_password, :rbswp_test_mode, :shipping_amount,
:shop, :show_vat_inclusive_prices, :skip_payment, :subdomain,
:terms_and_conditions, :use_default_css, :vat_number
validates_uniqueness_of :google_analytics_code, :allow_blank => true
validates_format_of :google_analytics_code, :with => /\AUA-\d\d\d\d\d\d(\d)?(\d)?-\d\Z/, :allow_blank => true
validates_presence_of :name
validates_inclusion_of :private, :in => [true, false]
validates_inclusion_of :render_blog_before_content, :in => [true, false]
# RBS WorldPay validations
validates_inclusion_of :rbswp_active, :in => [true, false]
validates_inclusion_of :rbswp_test_mode, :in => [true, false]
# these details are required only if RBS WorldPay is active
validates_presence_of :rbswp_installation_id, :if => Proc.new { |website| website.rbswp_active? }
validates_presence_of :rbswp_payment_response_password, :if => Proc.new { |website| website.rbswp_active? }
has_one :preferred_delivery_date_settings, :dependent => :delete
has_many :countries, :order => :name, :dependent => :destroy
has_many :discounts, :order => :name
has_many :liquid_templates, :order => :name, :dependent => :destroy
has_many :products, :order => :name, :dependent => :destroy
has_many :google_products, class_name: 'Product', conditions: { submit_to_google: true }
has_many :product_groups
has_many :orders, :order => 'created_at DESC', :dependent => :destroy
has_many :pages, :order => 'name', :dependent => :destroy
has_many :images, :dependent => :destroy
has_many :forums, :dependent => :destroy
has_many :enquiries, :dependent => :destroy
has_many :shipping_zones, :order => 'name', :dependent => :destroy
has_many :shipping_classes, :through => :shipping_zones
has_many :shipping_table_rows, :finder_sql =>
'SELECT `shipping_table_rows`.* ' +
'FROM `shipping_table_rows` ' +
'INNER JOIN `shipping_classes` ON `shipping_table_rows`.shipping_class_id = `shipping_classes`.id ' +
'INNER JOIN `shipping_zones` ON `shipping_classes`.shipping_zone_id = `shipping_zones`.id ' +
'WHERE ((`shipping_zones`.website_id = #{id})) ' +
'ORDER BY `shipping_table_rows`.trigger'
has_many :users, :order => 'name', :dependent => :destroy
belongs_to :blog, :class_name => 'Forum'
after_create :populate_countries
def self.for(domain, subdomains)
website = find_by_domain(domain)
unless subdomains.blank?
website ||= find_by_subdomain(subdomains.first)
end
website
end
def shipping_countries
c = countries.where('shipping_zone_id IS NOT NULL')
c.empty? ? countries : c
end
def only_accept_payment_on_account?
accept_payment_on_account and !(rbswp_active)
end
def populate_countries
countries << Country.create([
{ :name => 'Afghanistan', :iso_3166_1_alpha_2 => 'AF' },
{ :name => 'Åland Islands', :iso_3166_1_alpha_2 => 'AX' },
{ :name => 'Albania', :iso_3166_1_alpha_2 => 'AL' },
{ :name => 'Algeria', :iso_3166_1_alpha_2 => 'DZ' },
{ :name => 'American Samoa', :iso_3166_1_alpha_2 => 'AS' },
{ :name => 'Andorra', :iso_3166_1_alpha_2 => 'AD' },
{ :name => 'Angola', :iso_3166_1_alpha_2 => 'AO' },
{ :name => 'Anguilla', :iso_3166_1_alpha_2 => 'AI' },
{ :name => 'Antarctica', :iso_3166_1_alpha_2 => 'AQ' },
{ :name => 'Antigua and Barbuda', :iso_3166_1_alpha_2 => 'AG' },
{ :name => 'Argentina', :iso_3166_1_alpha_2 => 'AR' },
{ :name => 'Armenia', :iso_3166_1_alpha_2 => 'AM' },
{ :name => 'Aruba', :iso_3166_1_alpha_2 => 'AW' },
{ :name => 'Australia', :iso_3166_1_alpha_2 => 'AU' },
{ :name => 'Austria', :iso_3166_1_alpha_2 => 'AT' },
{ :name => 'Azerbaijan', :iso_3166_1_alpha_2 => 'AZ' },
{ :name => 'Bahamas', :iso_3166_1_alpha_2 => 'BS' },
{ :name => 'Bahrain', :iso_3166_1_alpha_2 => 'BH' },
{ :name => 'Bangladesh', :iso_3166_1_alpha_2 => 'BD' },
{ :name => 'Barbados', :iso_3166_1_alpha_2 => 'BB' },
{ :name => 'Belarus', :iso_3166_1_alpha_2 => 'BY' },
{ :name => 'Belgium', :iso_3166_1_alpha_2 => 'BE' },
{ :name => 'Belize', :iso_3166_1_alpha_2 => 'BZ' },
{ :name => 'Benin', :iso_3166_1_alpha_2 => 'BJ' },
{ :name => 'Bermuda', :iso_3166_1_alpha_2 => 'BM' },
{ :name => 'Bhutan', :iso_3166_1_alpha_2 => 'BT' },
{ :name => 'Bolivia', :iso_3166_1_alpha_2 => 'BO' },
{ :name => 'Bonaire, Sint Eustatius and Saba', :iso_3166_1_alpha_2 => 'BQ' },
{ :name => 'Bosnia and Herzegovina', :iso_3166_1_alpha_2 => 'BA' },
{ :name => 'Botswana', :iso_3166_1_alpha_2 => 'BW' },
{ :name => 'Bouvet Island', :iso_3166_1_alpha_2 => 'BV' },
{ :name => 'Brazil', :iso_3166_1_alpha_2 => 'BR' },
{ :name => 'British Indian Ocean Territory', :iso_3166_1_alpha_2 => 'IO' },
{ :name => 'Brunei', :iso_3166_1_alpha_2 => 'BN' },
{ :name => 'Bulgaria', :iso_3166_1_alpha_2 => 'BG' },
{ :name => 'Burkina Faso', :iso_3166_1_alpha_2 => 'BF' },
{ :name => 'Burundi', :iso_3166_1_alpha_2 => 'BI' },
{ :name => 'Cambodia', :iso_3166_1_alpha_2 => 'KH' },
{ :name => 'Cameroon', :iso_3166_1_alpha_2 => 'CM' },
{ :name => 'Canada', :iso_3166_1_alpha_2 => 'CA' },
{ :name => 'Cape Verde', :iso_3166_1_alpha_2 => 'CV' },
{ :name => 'Cayman Islands', :iso_3166_1_alpha_2 => 'KY' },
{ :name => 'Central African Republic', :iso_3166_1_alpha_2 => 'CF' },
{ :name => 'Chad', :iso_3166_1_alpha_2 => 'TD' },
{ :name => 'Chile', :iso_3166_1_alpha_2 => 'CL' },
{ :name => 'China', :iso_3166_1_alpha_2 => 'CN' },
{ :name => 'Christmas Island', :iso_3166_1_alpha_2 => 'CX' },
{ :name => 'Cocos (Keeling) Islands', :iso_3166_1_alpha_2 => 'CC' },
{ :name => 'Colombia', :iso_3166_1_alpha_2 => 'CO' },
{ :name => 'Comoros', :iso_3166_1_alpha_2 => 'KM' },
{ :name => 'Congo', :iso_3166_1_alpha_2 => 'CG' },
{ :name => 'Congo, the Democratic Republic of', :iso_3166_1_alpha_2 => 'CD' },
{ :name => 'Cook Islands', :iso_3166_1_alpha_2 => 'CK' },
{ :name => 'Costa Rica', :iso_3166_1_alpha_2 => 'CR' },
{ :name => 'Côte d\'Ivoire', :iso_3166_1_alpha_2 => 'CI' },
{ :name => 'Croatia', :iso_3166_1_alpha_2 => 'HR' },
{ :name => 'Cuba', :iso_3166_1_alpha_2 => 'CU' },
{ :name => 'Curaçao', :iso_3166_1_alpha_2 => 'CW' },
{ :name => 'Cyprus', :iso_3166_1_alpha_2 => 'CY' },
{ :name => 'Czech Republic', :iso_3166_1_alpha_2 => 'CZ' },
{ :name => 'Denmark', :iso_3166_1_alpha_2 => 'DK' },
{ :name => 'Djibouti', :iso_3166_1_alpha_2 => 'DJ' },
{ :name => 'Dominica', :iso_3166_1_alpha_2 => 'DM' },
{ :name => 'Dominican Republic', :iso_3166_1_alpha_2 => 'DO' },
{ :name => 'Ecuador', :iso_3166_1_alpha_2 => 'EC' },
{ :name => 'Egypt', :iso_3166_1_alpha_2 => 'EG' },
{ :name => 'El Salvador', :iso_3166_1_alpha_2 => 'SV' },
{ :name => 'Equatorial Guinea', :iso_3166_1_alpha_2 => 'GQ' },
{ :name => 'Eritrea', :iso_3166_1_alpha_2 => 'ER' },
{ :name => 'Estonia', :iso_3166_1_alpha_2 => 'EE' },
{ :name => 'Ethiopia', :iso_3166_1_alpha_2 => 'ET' },
{ :name => 'Falkland Islands (Malvinas)', :iso_3166_1_alpha_2 => 'FK' },
{ :name => 'Faroe Islands', :iso_3166_1_alpha_2 => 'FO' },
{ :name => 'Fiji', :iso_3166_1_alpha_2 => 'FJ' },
{ :name => 'Finland', :iso_3166_1_alpha_2 => 'FI' },
{ :name => 'France', :iso_3166_1_alpha_2 => 'FR' },
{ :name => 'French Guiana', :iso_3166_1_alpha_2 => 'GF' },
{ :name => 'French Polynesia', :iso_3166_1_alpha_2 => 'PF' },
{ :name => 'French Southern Territories', :iso_3166_1_alpha_2 => 'TF' },
{ :name => 'Gabon', :iso_3166_1_alpha_2 => 'GA' },
{ :name => 'Gambia', :iso_3166_1_alpha_2 => 'GM' },
{ :name => 'Georgia', :iso_3166_1_alpha_2 => 'GE' },
{ :name => 'Germany', :iso_3166_1_alpha_2 => 'DE' },
{ :name => 'Ghana', :iso_3166_1_alpha_2 => 'GH' },
{ :name => 'Gibraltar', :iso_3166_1_alpha_2 => 'GI' },
{ :name => 'Greece', :iso_3166_1_alpha_2 => 'GR' },
{ :name => 'Greenland', :iso_3166_1_alpha_2 => 'GL' },
{ :name => 'Grenada', :iso_3166_1_alpha_2 => 'GD' },
{ :name => 'Guadeloupe', :iso_3166_1_alpha_2 => 'GP' },
{ :name => 'Guam', :iso_3166_1_alpha_2 => 'GU' },
{ :name => 'Guatemala', :iso_3166_1_alpha_2 => 'GT' },
{ :name => 'Guernsey', :iso_3166_1_alpha_2 => 'GG' },
{ :name => 'Guinea', :iso_3166_1_alpha_2 => 'GN' },
{ :name => 'Guinea-Bissau', :iso_3166_1_alpha_2 => 'GW' },
{ :name => 'Guyana', :iso_3166_1_alpha_2 => 'GY' },
{ :name => 'Haiti', :iso_3166_1_alpha_2 => 'HT' },
{ :name => 'Heard Island and McDonald Islands', :iso_3166_1_alpha_2 => 'HM' },
{ :name => 'Holy See (Vatican City State)', :iso_3166_1_alpha_2 => 'VA' },
{ :name => 'Honduras', :iso_3166_1_alpha_2 => 'HN' },
{ :name => 'Hong Kong', :iso_3166_1_alpha_2 => 'HK' },
{ :name => 'Hungary', :iso_3166_1_alpha_2 => 'HU' },
{ :name => 'Iceland', :iso_3166_1_alpha_2 => 'IS' },
{ :name => 'India', :iso_3166_1_alpha_2 => 'IN' },
{ :name => 'Indonesia', :iso_3166_1_alpha_2 => 'ID' },
{ :name => 'Iran', :iso_3166_1_alpha_2 => 'IR' },
{ :name => 'Iraq', :iso_3166_1_alpha_2 => 'IQ' },
{ :name => 'Ireland', :iso_3166_1_alpha_2 => 'IE' },
{ :name => 'Isle of Man', :iso_3166_1_alpha_2 => 'IM' },
{ :name => 'Israel', :iso_3166_1_alpha_2 => 'IL' },
{ :name => 'Italy', :iso_3166_1_alpha_2 => 'IT' },
{ :name => 'Jamaica', :iso_3166_1_alpha_2 => 'JM' },
{ :name => 'Japan', :iso_3166_1_alpha_2 => 'JP' },
{ :name => 'Jersey', :iso_3166_1_alpha_2 => 'JE' },
{ :name => 'Jordan', :iso_3166_1_alpha_2 => 'JO' },
{ :name => 'Kazakhstan', :iso_3166_1_alpha_2 => 'KZ' },
{ :name => 'Kenya', :iso_3166_1_alpha_2 => 'KE' },
{ :name => 'Kiribati', :iso_3166_1_alpha_2 => 'KI' },
{ :name => 'Kuwait', :iso_3166_1_alpha_2 => 'KW' },
{ :name => 'Kyrgyzstan', :iso_3166_1_alpha_2 => 'KG' },
{ :name => 'Lao People\'s Democratic Republic', :iso_3166_1_alpha_2 => 'LA' },
{ :name => 'Latvia', :iso_3166_1_alpha_2 => 'LV' },
{ :name => 'Lebanon', :iso_3166_1_alpha_2 => 'LB' },
{ :name => 'Lesotho', :iso_3166_1_alpha_2 => 'LS' },
{ :name => 'Liberia', :iso_3166_1_alpha_2 => 'LR' },
{ :name => 'Libya', :iso_3166_1_alpha_2 => 'LY' },
{ :name => 'Liechtenstein', :iso_3166_1_alpha_2 => 'LI' },
{ :name => 'Lithuania', :iso_3166_1_alpha_2 => 'LT' },
{ :name => 'Luxembourg', :iso_3166_1_alpha_2 => 'LU' },
{ :name => 'Macao', :iso_3166_1_alpha_2 => 'MO' },
{ :name => 'Macedonia, the former Yugoslav Republic of', :iso_3166_1_alpha_2 => 'MK' },
{ :name => 'Madagascar', :iso_3166_1_alpha_2 => 'MG' },
{ :name => 'Malawi', :iso_3166_1_alpha_2 => 'MW' },
{ :name => 'Malaysia', :iso_3166_1_alpha_2 => 'MY' },
{ :name => 'Maldives', :iso_3166_1_alpha_2 => 'MV' },
{ :name => 'Mali', :iso_3166_1_alpha_2 => 'ML' },
{ :name => 'Malta', :iso_3166_1_alpha_2 => 'MT' },
{ :name => 'Marshall Islands', :iso_3166_1_alpha_2 => 'MH' },
{ :name => 'Martinique', :iso_3166_1_alpha_2 => 'MQ' },
{ :name => 'Mauritania', :iso_3166_1_alpha_2 => 'MR' },
{ :name => 'Mauritius', :iso_3166_1_alpha_2 => 'MU' },
{ :name => 'Mayotte', :iso_3166_1_alpha_2 => 'YT' },
{ :name => 'Mexico', :iso_3166_1_alpha_2 => 'MX' },
{ :name => 'Micronesia, Federated States of', :iso_3166_1_alpha_2 => 'FM' },
{ :name => 'Moldova', :iso_3166_1_alpha_2 => 'MD' },
{ :name => 'Monaco', :iso_3166_1_alpha_2 => 'MC' },
{ :name => 'Mongolia', :iso_3166_1_alpha_2 => 'MN' },
{ :name => 'Montenegro', :iso_3166_1_alpha_2 => 'ME' },
{ :name => 'Montserrat', :iso_3166_1_alpha_2 => 'MS' },
{ :name => 'Morocco', :iso_3166_1_alpha_2 => 'MA' },
{ :name => 'Mozambique', :iso_3166_1_alpha_2 => 'MZ' },
{ :name => 'Myanmar', :iso_3166_1_alpha_2 => 'MM' },
{ :name => 'Namibia', :iso_3166_1_alpha_2 => 'NA' },
{ :name => 'Nauru', :iso_3166_1_alpha_2 => 'NR' },
{ :name => 'Nepal', :iso_3166_1_alpha_2 => 'NP' },
{ :name => 'Netherlands', :iso_3166_1_alpha_2 => 'NL' },
{ :name => 'New Caledonia', :iso_3166_1_alpha_2 => 'NC' },
{ :name => 'New Zealand', :iso_3166_1_alpha_2 => 'NZ' },
{ :name => 'Nicaragua', :iso_3166_1_alpha_2 => 'NI' },
{ :name => 'Niger', :iso_3166_1_alpha_2 => 'NE' },
{ :name => 'Nigeria', :iso_3166_1_alpha_2 => 'NG' },
{ :name => 'Niue', :iso_3166_1_alpha_2 => 'NU' },
{ :name => 'Norfolk Island', :iso_3166_1_alpha_2 => 'NF' },
{ :name => 'North Korea', :iso_3166_1_alpha_2 => 'KP' },
{ :name => 'Northern Mariana Islands', :iso_3166_1_alpha_2 => 'MP' },
{ :name => 'Norway', :iso_3166_1_alpha_2 => 'NO' },
{ :name => 'Oman', :iso_3166_1_alpha_2 => 'OM' },
{ :name => 'Pakistan', :iso_3166_1_alpha_2 => 'PK' },
{ :name => 'Palau', :iso_3166_1_alpha_2 => 'PW' },
{ :name => 'Palestinian Territory, Occupied', :iso_3166_1_alpha_2 => 'PS' },
{ :name => 'Panama', :iso_3166_1_alpha_2 => 'PA' },
{ :name => 'Papua New Guinea', :iso_3166_1_alpha_2 => 'PG' },
{ :name => 'Paraguay', :iso_3166_1_alpha_2 => 'PY' },
{ :name => 'Peru', :iso_3166_1_alpha_2 => 'PE' },
{ :name => 'Philippines', :iso_3166_1_alpha_2 => 'PH' },
{ :name => 'Pitcairn', :iso_3166_1_alpha_2 => 'PN' },
{ :name => 'Poland', :iso_3166_1_alpha_2 => 'PL' },
{ :name => 'Portugal', :iso_3166_1_alpha_2 => 'PT' },
{ :name => 'Puerto Rico', :iso_3166_1_alpha_2 => 'PR' },
{ :name => 'Qatar', :iso_3166_1_alpha_2 => 'QA' },
{ :name => 'Réunion', :iso_3166_1_alpha_2 => 'RE' },
{ :name => 'Romania', :iso_3166_1_alpha_2 => 'RO' },
{ :name => 'Russia', :iso_3166_1_alpha_2 => 'RU' },
{ :name => 'Rwanda', :iso_3166_1_alpha_2 => 'RW' },
{ :name => 'Saint Barthélemy', :iso_3166_1_alpha_2 => 'BL' },
{ :name => 'Saint Helena, Ascension and Tristan da Cunha', :iso_3166_1_alpha_2 => 'SH' },
{ :name => 'Saint Kitts and Nevis', :iso_3166_1_alpha_2 => 'KN' },
{ :name => 'Saint Lucia', :iso_3166_1_alpha_2 => 'LC' },
{ :name => 'Saint Martin (French part)', :iso_3166_1_alpha_2 => 'MF' },
{ :name => 'Saint Pierre and Miquelon', :iso_3166_1_alpha_2 => 'PM' },
{ :name => 'Saint Vincent and the Grenadines', :iso_3166_1_alpha_2 => 'VC' },
{ :name => 'Samoa', :iso_3166_1_alpha_2 => 'WS' },
{ :name => 'San Marino', :iso_3166_1_alpha_2 => 'SM' },
{ :name => 'Sao Tome and Principe', :iso_3166_1_alpha_2 => 'ST' },
{ :name => 'Saudi Arabia', :iso_3166_1_alpha_2 => 'SA' },
{ :name => 'Senegal', :iso_3166_1_alpha_2 => 'SN' },
{ :name => 'Serbia', :iso_3166_1_alpha_2 => 'RS' },
{ :name => 'Seychelles', :iso_3166_1_alpha_2 => 'SC' },
{ :name => 'Sierra Leone', :iso_3166_1_alpha_2 => 'SL' },
{ :name => 'Singapore', :iso_3166_1_alpha_2 => 'SG' },
{ :name => 'Sint Maarten (Dutch part)', :iso_3166_1_alpha_2 => 'SX' },
{ :name => 'Slovakia', :iso_3166_1_alpha_2 => 'SK' },
{ :name => 'Slovenia', :iso_3166_1_alpha_2 => 'SI' },
{ :name => 'Solomon Islands', :iso_3166_1_alpha_2 => 'SB' },
{ :name => 'Somalia', :iso_3166_1_alpha_2 => 'SO' },
{ :name => 'South Africa', :iso_3166_1_alpha_2 => 'ZA' },
{ :name => 'South Georgia and the South Sandwich Islands', :iso_3166_1_alpha_2 => 'GS' },
{ :name => 'South Korea', :iso_3166_1_alpha_2 => 'KR' },
{ :name => 'Spain', :iso_3166_1_alpha_2 => 'ES' },
{ :name => 'Sri Lanka', :iso_3166_1_alpha_2 => 'LK' },
{ :name => 'Sudan', :iso_3166_1_alpha_2 => 'SD' },
{ :name => 'Suriname', :iso_3166_1_alpha_2 => 'SR' },
{ :name => 'Svalbard and Jan Mayen', :iso_3166_1_alpha_2 => 'SJ' },
{ :name => 'Swaziland', :iso_3166_1_alpha_2 => 'SZ' },
{ :name => 'Sweden', :iso_3166_1_alpha_2 => 'SE' },
{ :name => 'Switzerland', :iso_3166_1_alpha_2 => 'CH' },
{ :name => 'Syria', :iso_3166_1_alpha_2 => 'SY' },
{ :name => 'Taiwan, Province of China', :iso_3166_1_alpha_2 => 'TW' },
{ :name => 'Tajikistan', :iso_3166_1_alpha_2 => 'TJ' },
{ :name => 'Tanzania', :iso_3166_1_alpha_2 => 'TZ' },
{ :name => 'Thailand', :iso_3166_1_alpha_2 => 'TH' },
{ :name => 'Timor-Lest', :iso_3166_1_alpha_2 => 'TL' },
{ :name => 'Togo', :iso_3166_1_alpha_2 => 'TG' },
{ :name => 'Tokelau', :iso_3166_1_alpha_2 => 'TK' },
{ :name => 'Tonga', :iso_3166_1_alpha_2 => 'TO' },
{ :name => 'Trinidad and Tobago', :iso_3166_1_alpha_2 => 'TT' },
{ :name => 'Tunisia', :iso_3166_1_alpha_2 => 'TN' },
{ :name => 'Turkey', :iso_3166_1_alpha_2 => 'TR' },
{ :name => 'Turkmenistan', :iso_3166_1_alpha_2 => 'TM' },
{ :name => 'Turks and Caicos Islands', :iso_3166_1_alpha_2 => 'TC' },
{ :name => 'Tuvalu', :iso_3166_1_alpha_2 => 'TV' },
{ :name => 'Uganda', :iso_3166_1_alpha_2 => 'UG' },
{ :name => 'Ukraine', :iso_3166_1_alpha_2 => 'UA' },
{ :name => 'United Arab Emirates', :iso_3166_1_alpha_2 => 'AE' },
{ :name => 'United Kingdom', :iso_3166_1_alpha_2 => 'GB' },
{ :name => 'United States', :iso_3166_1_alpha_2 => 'US' },
{ :name => 'United States Minor Outlying Islands', :iso_3166_1_alpha_2 => 'UM' },
{ :name => 'Uruguay', :iso_3166_1_alpha_2 => 'UY' },
{ :name => 'Uzbekistan', :iso_3166_1_alpha_2 => 'UZ' },
{ :name => 'Vanuatu', :iso_3166_1_alpha_2 => 'VU' },
{ :name => 'Venezuela', :iso_3166_1_alpha_2 => 'VE' },
{ :name => 'Vietnam', :iso_3166_1_alpha_2 => 'VN' },
{ :name => 'Virgin Islands, British', :iso_3166_1_alpha_2 => 'VG' },
{ :name => 'Virgin Islands, U.S.', :iso_3166_1_alpha_2 => 'VI' },
{ :name => 'Wallis and Futuna', :iso_3166_1_alpha_2 => 'WF' },
{ :name => 'Western Sahara', :iso_3166_1_alpha_2 => 'EH' },
{ :name => 'Yemen', :iso_3166_1_alpha_2 => 'YE' },
{ :name => 'Zambia', :iso_3166_1_alpha_2 => 'ZM' },
{ :name => 'Zimbabwe', :iso_3166_1_alpha_2 => 'ZW' }
])
end
end |
class Worklog < ActiveRecord::Base
include HourlyRateHelper
include TotalHelper
total_and_currency_for attribute_name: :total, cents_attribute: :total_cents
include TimeFilter
attr_accessible :client_id,
:end_time,
:start_time,
:user_id,
:hourly_rate,
:hourly_rate_cents,
:total,
:summary,
:from_date,
:from_time,
:to_date,
:to_time
attr_accessor :from_date,
:from_time,
:to_date,
:to_time
default_scope where(deleted_at: nil)
def self.deleted
self.unscoped.where('deleted_at IS NOT NULL')
end
belongs_to :user
belongs_to :client
belongs_to :client_share
belongs_to :invoice
validates :user, :client, :start_time, :end_time, presence: true
validate :end_time_greater_than_start_time
validate :duration_less_than_a_year
before_validation :set_client_share
before_validation :persist_hourly_rate_from_client, on: :create
before_validation :set_total
after_create :email_user_of_shared_client_worklog
scope :paid, where(invoice_id: !nil)
scope :unpaid, where(invoice_id: nil)
scope :no_invoice, where(invoice_id: nil)
scope :oldest_first, order("end_time ASC")
def self.to_csv(worklogs)
CSV.generate do |csv|
csv << self.columns_to_export
worklogs.each do |worklog|
csv << worklog.array_data_to_export
end
end
end
def self.range_duration_seconds(worklogs)
return 0 if worklogs.empty?
sum_start = worklogs.map{|w| w.start_time.to_i}.reduce(:+)
sum_end = worklogs.map{|w| w.end_time.to_i}.reduce(:+)
sum_end - sum_start
end
def self.hours_from_seconds(seconds)
seconds / 1.hour
end
def self.remaining_minutes_from_seconds(seconds)
seconds / 1.minute % 60
end
def self.columns_to_export
["Client", "Start time", "End time", "Hours", "Minutes", "Hourly Rate", "Total", "Summary"]
end
def array_data_to_export
[client.name,
I18n.localize(start_time),
I18n.localize(end_time),
duration_hours,
duration_minutes,
hourly_rate,
total.to_s,
summary]
end
def invoiced?
invoice_id
end
def yes_or_no_boolean(boolean_var)
boolean_var ? "Yes" : "No"
end
def duration
return if !end_time || !start_time
(end_time - start_time).to_i
end
def duration_hours
self.class.hours_from_seconds duration
end
def duration_minutes
self.class.remaining_minutes_from_seconds duration
end
def calc_total
Money.new cent_rate_per_second(hourly_rate_cents) * duration, currency
end
def cent_rate_per_second(cents_per_hour)
cents_per_hour.to_f / 3600
end
def end_time_ok
return if !end_time || !start_time
end_time > start_time
end
def set_time_helpers_to_now!
set_time_helpers_to_time!(Time.zone.now, Time.zone.now)
end
def set_time_helpers_to_saved_times!
set_time_helpers_to_time!(start_time, end_time)
end
def set_time_helpers_to_time!(start_time, end_time)
self.from_date = start_time.strftime("%d/%m/%Y")
self.to_date = end_time.strftime("%d/%m/%Y")
self.from_time = start_time.strftime("%H:%M:%S")
self.to_time = end_time.strftime("%H:%M:%S")
end
def from_converted
begin
date = self.from_date.split("/").reverse.map(&:to_i)
time = self.from_time.split(":").map(&:to_i)
from_to_time(date, time)
rescue
nil
end
end
def from_to_time(date, time)
Time.zone.local(date[0], date[1], date[2], time[0], time[1], time[2])
end
def to_converted
begin
date = self.to_date.split("/").reverse.map(&:to_i)
time = self.to_time.split(":").map(&:to_i)
from_to_time(date, time)
rescue
nil
end
end
def convert_time_helpers_to_date_time!
self.start_time = from_converted
self.end_time = to_converted
end
def restore_based_on_saved_info
return if !user
self.class.new(user.temp_worklog_save.restoreable_options)
end
def title
"#{end_time.strftime("%d.%m.%Y")} - #{duration_hours.to_s}h:#{duration_minutes.to_s}min. #{total.to_s}#{total.currency.symbol}"
end
def invoice_title(invoice)
"Work: #{end_time.strftime("%d.%m.%Y")} - #{duration_hours.to_s}h:#{duration_minutes.to_s}min x #{hourly_rate}#{hourly_rate.currency.symbol}"
end
def self.updated_since(unixtimestamp)
self.unscoped.where("updated_at >= ?", Time.at(unixtimestamp.to_i).to_datetime)
end
def created_for_shared_client?
# We own the client
if user.clients.where(id: client_id).any?
false
else
true
end
end
def created_for_user
if created_for_shared_client?
client.user
else
user
end
end
def email_user_of_shared_client_worklog
if created_for_shared_client? && client.email_when_team_adds_worklog
begin
WorklogMailer.worklog_for_shared_client_created(self).deliver
rescue
end
end
true
end
# Active record callbacks #
def persist_hourly_rate_from_client
if client_share.present?
self.hourly_rate = client_share.hourly_rate
elsif not_set_by_user
self.hourly_rate = client.hourly_rate
end
end
def not_set_by_user
# This check only works for new records, as the hourly rate is persisted
# after.
return if !new_record?
hourly_rate.cents == 0
end
def set_total
self.total = self.calc_total
end
# Validations #
def multi_errors_add(attributes, message)
attributes.each do |attri|
errors.add(attri, message)
end
end
def duration_less_than_a_year
if duration && duration > 1.year && end_time_ok
multi_errors_add([:start_time, :end_time, :from_date, :from_time, :to_time, :to_date], "Must be smaller than a year")
end
end
def end_time_greater_than_start_time
if !end_time_ok
multi_errors_add([:end_time, :to_time, :to_date], "Must be greater than the start.")
end
end
def set_client_share
if user && client && created_for_shared_client?
self.client_share = user.client_shares.where(client_id: self.client_id).first
end
true
end
end
add error msg in case worklog can't be sent
class Worklog < ActiveRecord::Base
include HourlyRateHelper
include TotalHelper
total_and_currency_for attribute_name: :total, cents_attribute: :total_cents
include TimeFilter
attr_accessible :client_id,
:end_time,
:start_time,
:user_id,
:hourly_rate,
:hourly_rate_cents,
:total,
:summary,
:from_date,
:from_time,
:to_date,
:to_time
attr_accessor :from_date,
:from_time,
:to_date,
:to_time
default_scope where(deleted_at: nil)
def self.deleted
self.unscoped.where('deleted_at IS NOT NULL')
end
belongs_to :user
belongs_to :client
belongs_to :client_share
belongs_to :invoice
validates :user, :client, :start_time, :end_time, presence: true
validate :end_time_greater_than_start_time
validate :duration_less_than_a_year
before_validation :set_client_share
before_validation :persist_hourly_rate_from_client, on: :create
before_validation :set_total
after_create :email_user_of_shared_client_worklog
scope :paid, where(invoice_id: !nil)
scope :unpaid, where(invoice_id: nil)
scope :no_invoice, where(invoice_id: nil)
scope :oldest_first, order("end_time ASC")
def self.to_csv(worklogs)
CSV.generate do |csv|
csv << self.columns_to_export
worklogs.each do |worklog|
csv << worklog.array_data_to_export
end
end
end
def self.range_duration_seconds(worklogs)
return 0 if worklogs.empty?
sum_start = worklogs.map{|w| w.start_time.to_i}.reduce(:+)
sum_end = worklogs.map{|w| w.end_time.to_i}.reduce(:+)
sum_end - sum_start
end
def self.hours_from_seconds(seconds)
seconds / 1.hour
end
def self.remaining_minutes_from_seconds(seconds)
seconds / 1.minute % 60
end
def self.columns_to_export
["Client", "Start time", "End time", "Hours", "Minutes", "Hourly Rate", "Total", "Summary"]
end
def array_data_to_export
[client.name,
I18n.localize(start_time),
I18n.localize(end_time),
duration_hours,
duration_minutes,
hourly_rate,
total.to_s,
summary]
end
def invoiced?
invoice_id
end
def yes_or_no_boolean(boolean_var)
boolean_var ? "Yes" : "No"
end
def duration
return if !end_time || !start_time
(end_time - start_time).to_i
end
def duration_hours
self.class.hours_from_seconds duration
end
def duration_minutes
self.class.remaining_minutes_from_seconds duration
end
def calc_total
Money.new cent_rate_per_second(hourly_rate_cents) * duration, currency
end
def cent_rate_per_second(cents_per_hour)
cents_per_hour.to_f / 3600
end
def end_time_ok
return if !end_time || !start_time
end_time > start_time
end
def set_time_helpers_to_now!
set_time_helpers_to_time!(Time.zone.now, Time.zone.now)
end
def set_time_helpers_to_saved_times!
set_time_helpers_to_time!(start_time, end_time)
end
def set_time_helpers_to_time!(start_time, end_time)
self.from_date = start_time.strftime("%d/%m/%Y")
self.to_date = end_time.strftime("%d/%m/%Y")
self.from_time = start_time.strftime("%H:%M:%S")
self.to_time = end_time.strftime("%H:%M:%S")
end
def from_converted
begin
date = self.from_date.split("/").reverse.map(&:to_i)
time = self.from_time.split(":").map(&:to_i)
from_to_time(date, time)
rescue
nil
end
end
def from_to_time(date, time)
Time.zone.local(date[0], date[1], date[2], time[0], time[1], time[2])
end
def to_converted
begin
date = self.to_date.split("/").reverse.map(&:to_i)
time = self.to_time.split(":").map(&:to_i)
from_to_time(date, time)
rescue
nil
end
end
def convert_time_helpers_to_date_time!
self.start_time = from_converted
self.end_time = to_converted
end
def restore_based_on_saved_info
return if !user
self.class.new(user.temp_worklog_save.restoreable_options)
end
def title
"#{end_time.strftime("%d.%m.%Y")} - #{duration_hours.to_s}h:#{duration_minutes.to_s}min. #{total.to_s}#{total.currency.symbol}"
end
def invoice_title(invoice)
"Work: #{end_time.strftime("%d.%m.%Y")} - #{duration_hours.to_s}h:#{duration_minutes.to_s}min x #{hourly_rate}#{hourly_rate.currency.symbol}"
end
def self.updated_since(unixtimestamp)
self.unscoped.where("updated_at >= ?", Time.at(unixtimestamp.to_i).to_datetime)
end
def created_for_shared_client?
# We own the client
if user.clients.where(id: client_id).any?
false
else
true
end
end
def created_for_user
if created_for_shared_client?
client.user
else
user
end
end
def email_user_of_shared_client_worklog
if created_for_shared_client? && client.email_when_team_adds_worklog
begin
WorklogMailer.worklog_for_shared_client_created(self).deliver
rescue => e
Rails.logger.fatal "Could not deliver worklog message: #{e.message.to_s} - #{e.backtrace.join("\n")}"
end
end
true
end
# Active record callbacks #
def persist_hourly_rate_from_client
if client_share.present?
self.hourly_rate = client_share.hourly_rate
elsif not_set_by_user
self.hourly_rate = client.hourly_rate
end
end
def not_set_by_user
# This check only works for new records, as the hourly rate is persisted
# after.
return if !new_record?
hourly_rate.cents == 0
end
def set_total
self.total = self.calc_total
end
# Validations #
def multi_errors_add(attributes, message)
attributes.each do |attri|
errors.add(attri, message)
end
end
def duration_less_than_a_year
if duration && duration > 1.year && end_time_ok
multi_errors_add([:start_time, :end_time, :from_date, :from_time, :to_time, :to_date], "Must be smaller than a year")
end
end
def end_time_greater_than_start_time
if !end_time_ok
multi_errors_add([:end_time, :to_time, :to_date], "Must be greater than the start.")
end
end
def set_client_share
if user && client && created_for_shared_client?
self.client_share = user.client_shares.where(client_id: self.client_id).first
end
true
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{meta_search}
s.version = "0.5.3"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Ernie Miller"]
s.date = %q{2010-07-26}
s.description = %q{
Allows simple search forms to be created against an AR3 model
and its associations, has useful view helpers for sort links
and multiparameter fields as well.
}
s.email = %q{ernie@metautonomo.us}
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = [
".document",
".gitignore",
".gitmodules",
"CHANGELOG",
"Gemfile",
"LICENSE",
"README.rdoc",
"Rakefile",
"VERSION",
"lib/meta_search.rb",
"lib/meta_search/builder.rb",
"lib/meta_search/exceptions.rb",
"lib/meta_search/helpers.rb",
"lib/meta_search/helpers/form_builder.rb",
"lib/meta_search/helpers/form_helper.rb",
"lib/meta_search/helpers/url_helper.rb",
"lib/meta_search/method.rb",
"lib/meta_search/model_compatibility.rb",
"lib/meta_search/searches/active_record.rb",
"lib/meta_search/utility.rb",
"lib/meta_search/where.rb",
"meta_search.gemspec",
"test/fixtures/companies.yml",
"test/fixtures/company.rb",
"test/fixtures/data_type.rb",
"test/fixtures/data_types.yml",
"test/fixtures/developer.rb",
"test/fixtures/developers.yml",
"test/fixtures/developers_projects.yml",
"test/fixtures/note.rb",
"test/fixtures/notes.yml",
"test/fixtures/project.rb",
"test/fixtures/projects.yml",
"test/fixtures/schema.rb",
"test/helper.rb",
"test/test_search.rb",
"test/test_view_helpers.rb"
]
s.homepage = %q{http://metautonomo.us/projects/metasearch/}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.6}
s.summary = %q{ActiveRecord 3 object-based searching for your form_for enjoyment.}
s.test_files = [
"test/fixtures/company.rb",
"test/fixtures/data_type.rb",
"test/fixtures/developer.rb",
"test/fixtures/note.rb",
"test/fixtures/project.rb",
"test/fixtures/schema.rb",
"test/helper.rb",
"test/test_search.rb",
"test/test_view_helpers.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_runtime_dependency(%q<activerecord>, [">= 3.0.0.beta4"])
s.add_runtime_dependency(%q<activesupport>, [">= 3.0.0.beta4"])
s.add_runtime_dependency(%q<actionpack>, [">= 3.0.0.beta4"])
s.add_runtime_dependency(%q<arel>, [">= 0.4.0"])
else
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<activerecord>, [">= 3.0.0.beta4"])
s.add_dependency(%q<activesupport>, [">= 3.0.0.beta4"])
s.add_dependency(%q<actionpack>, [">= 3.0.0.beta4"])
s.add_dependency(%q<arel>, [">= 0.4.0"])
end
else
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<activerecord>, [">= 3.0.0.beta4"])
s.add_dependency(%q<activesupport>, [">= 3.0.0.beta4"])
s.add_dependency(%q<actionpack>, [">= 3.0.0.beta4"])
s.add_dependency(%q<arel>, [">= 0.4.0"])
end
end
Regenerated gemspec for version 0.5.4
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{meta_search}
s.version = "0.5.4"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Ernie Miller"]
s.date = %q{2010-07-28}
s.description = %q{
Allows simple search forms to be created against an AR3 model
and its associations, has useful view helpers for sort links
and multiparameter fields as well.
}
s.email = %q{ernie@metautonomo.us}
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = [
".document",
".gitignore",
".gitmodules",
"CHANGELOG",
"Gemfile",
"LICENSE",
"README.rdoc",
"Rakefile",
"VERSION",
"lib/meta_search.rb",
"lib/meta_search/builder.rb",
"lib/meta_search/exceptions.rb",
"lib/meta_search/helpers.rb",
"lib/meta_search/helpers/form_builder.rb",
"lib/meta_search/helpers/form_helper.rb",
"lib/meta_search/helpers/url_helper.rb",
"lib/meta_search/method.rb",
"lib/meta_search/model_compatibility.rb",
"lib/meta_search/searches/active_record.rb",
"lib/meta_search/utility.rb",
"lib/meta_search/where.rb",
"meta_search.gemspec",
"test/fixtures/companies.yml",
"test/fixtures/company.rb",
"test/fixtures/data_type.rb",
"test/fixtures/data_types.yml",
"test/fixtures/developer.rb",
"test/fixtures/developers.yml",
"test/fixtures/developers_projects.yml",
"test/fixtures/note.rb",
"test/fixtures/notes.yml",
"test/fixtures/project.rb",
"test/fixtures/projects.yml",
"test/fixtures/schema.rb",
"test/helper.rb",
"test/test_search.rb",
"test/test_view_helpers.rb"
]
s.homepage = %q{http://metautonomo.us/projects/metasearch/}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.7}
s.summary = %q{ActiveRecord 3 object-based searching for your form_for enjoyment.}
s.test_files = [
"test/fixtures/company.rb",
"test/fixtures/data_type.rb",
"test/fixtures/developer.rb",
"test/fixtures/note.rb",
"test/fixtures/project.rb",
"test/fixtures/schema.rb",
"test/helper.rb",
"test/test_search.rb",
"test/test_view_helpers.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_runtime_dependency(%q<activerecord>, [">= 3.0.0.beta4"])
s.add_runtime_dependency(%q<activesupport>, [">= 3.0.0.beta4"])
s.add_runtime_dependency(%q<actionpack>, [">= 3.0.0.beta4"])
s.add_runtime_dependency(%q<arel>, [">= 0.4.0"])
else
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<activerecord>, [">= 3.0.0.beta4"])
s.add_dependency(%q<activesupport>, [">= 3.0.0.beta4"])
s.add_dependency(%q<actionpack>, [">= 3.0.0.beta4"])
s.add_dependency(%q<arel>, [">= 0.4.0"])
end
else
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<activerecord>, [">= 3.0.0.beta4"])
s.add_dependency(%q<activesupport>, [">= 3.0.0.beta4"])
s.add_dependency(%q<actionpack>, [">= 3.0.0.beta4"])
s.add_dependency(%q<arel>, [">= 0.4.0"])
end
end
|
#:
#: * `rmtree` [`--force`] [`--dry-run`] [`--quiet`] formula1 [formula2] [formula3]... [`--ignore` formulaX]
#:
#: Remove a formula entirely, including all of its dependencies,
#: unless of course, they are used by another formula.
#:
#: Warning:
#:
#: Not all formulae declare their dependencies and therefore this command may end
#: up removing something you still need. It should be used with caution.
#:
#: With `--force`, you can override the dependency check for the top-level formula you
#: are trying to remove. If you try to remove 'ruby' for example, you most likely will
#: not be able to do this because other fomulae specify this as a dependency. This
#: option will let you remove 'ruby'. This will NOT bypass dependency checks for the
#: formula's children. If 'ruby' depends on 'git', then 'git' will still not be removed.
#:
#: With `--ignore`, you can ignore some dependencies from being removed. This option
#: must come after the formulae to remove.
#:
#: You can use `--dry-run` to see what would be removed without actually removing
#: anything.
#:
#: `--quiet` will hide output.
#:
#: `brew rmtree` <formula>
#: Removes <formula> and its dependencies.
#:
#: `brew rmtree` <formula> <formula2>
#: Removes <formula> and <formula2> and their dependencies.
#:
#: `brew rmtree` --force <formula>
#: Force the removal of <formula> even if other formulae depend on it.
#:
#: `brew rmtree` <formula> --ignore <formula2>
#: Remove <formula>, but don't remove its dependency of <formula2>
require 'keg'
require 'formula'
require 'formulary'
require 'dependencies'
require 'shellwords'
require 'set'
require 'cmd/deps'
# I am not a ruby-ist and so my style may offend some
module BrewRmtree
@dry_run = false
@used_by_table = {}
@dependency_table = {}
module_function
def bash(command)
escaped_command = Shellwords.escape(command)
return %x! bash -c #{escaped_command} !
end
# replaces Kernel#puts w/ do-nothing method
def puts_off
Kernel.module_eval %q{
def puts(*args)
end
def print(*args)
end
}
end
# restores Kernel#puts to its original definition
def puts_on
Kernel.module_eval %q{
def puts(*args)
$stdout.puts(*args)
end
def print(*args)
$stdout.print(*args)
end
}
end
# Sets the text to output with the spinner
def set_spinner_progress(txt)
@spinner[:progress] = txt
end
def show_wait_spinner(fps=10)
chars = %w[| / - \\]
delay = 1.0/fps
iter = 0
@spinner = Thread.new do
Thread.current[:progress] = ""
progress_size = 0
while iter do # Keep spinning until told otherwise
print ' ' + chars[(iter+=1) % chars.length] + Thread.current[:progress]
progress_size = Thread.current[:progress].length
sleep delay
print "\b"*(progress_size + 2)
end
end
yield.tap{ # After yielding to the block, save the return value
iter = false # Tell the thread to exit, cleaning up after itself…
@spinner.join # …and wait for it to do so.
} # Use the block's return value as the method's
end
# Remove a particular keg
def remove_keg(keg_name, dry_run)
if dry_run
puts "Would have removed #{keg_name}"
return
end
# Remove old versions of keg
puts bash "brew cleanup #{keg_name} 2>/dev/null"
# Remove current keg
puts bash "brew uninstall #{keg_name}"
end
# A list of dependencies of keg_name that are still installed after removal
# of the keg
def orphaned_dependencies(keg_name)
bash("join <(sort <(brew leaves)) <(sort <(brew deps #{keg_name}))").split("\n")
end
# A list of kegs that use keg_name, using homebrew code instead of shell cmd
def uses(keg_name, recursive=true, ignores=[])
# https://raw.githubusercontent.com/Homebrew/brew/master/Library/Homebrew/cmd/uses.rb
formulae = [Formulary.factory(keg_name)]
uses = Formula.installed.select do |f|
formulae.all? do |ff|
begin
if recursive
deps = f.recursive_dependencies do |dependent, dep|
if dep.recommended?
Dependency.prune if ignores.include?("recommended?") || dependent.build.without?(dep)
elsif dep.optional?
Dependency.prune if !includes.include?("optional?") && !dependent.build.with?(dep)
elsif dep.build?
Dependency.prune unless includes.include?("build?")
end
# If a tap isn't installed, we can't find the dependencies of one
# its formulae, and an exception will be thrown if we try.
if dep.is_a?(TapDependency) && !dep.tap.installed?
Dependency.keep_but_prune_recursive_deps
end
end
dep_formulae = deps.flat_map do |dep|
begin
dep.to_formula
rescue
[]
end
end
reqs_by_formula = ([f] + dep_formulae).flat_map do |formula|
formula.requirements.map { |req| [formula, req] }
end
reqs_by_formula.reject! do |dependent, req|
if req.recommended?
ignores.include?("recommended?") || dependent.build.without?(req)
elsif req.optional?
!includes.include?("optional?") && !dependent.build.with?(req)
elsif req.build?
!includes.include?("build?")
end
end
reqs = reqs_by_formula.map(&:last)
else
includes, ignores = Homebrew.argv_includes_ignores(["--installed"])
deps = f.deps.reject do |dep|
ignores.any? { |ignore| dep.send(ignore) } && includes.none? { |include| dep.send(include) }
end
# deps.reject! do |dep|
# # Exclude build dependencies or not required and can be built without it
# dep.build? || (!dep.required? && as_formula(dep.name).build.without?(dep))
# end
reqs = f.requirements.reject do |req|
ignores.any? { |ignore| req.send(ignore) } && includes.none? { |include| req.send(include) }
end
end
next true if deps.any? do |dep|
begin
dep.to_formula.full_name == ff.full_name
rescue
dep.name == ff.name
end
end
reqs.any? { |req| req.name == ff.name }
rescue FormulaUnavailableError
# Silently ignore this case as we don't care about things used in
# taps that aren't currently tapped.
next
end
end
end
uses.map(&:full_name)
end
def deps_for_formula(f)
# https://github.com/Homebrew/brew/blob/d1b83819deacd99b55c9d400149dc9b49fa795df/Library/Homebrew/cmd/deps.rb#L137
includes, ignores = Homebrew.argv_includes_ignores(["--installed"])
deps = f.runtime_dependencies
reqs = Homebrew.reject_ignores(f.requirements, ignores, includes)
deps + reqs.to_a
end
# Gather complete list of packages used by root package
def dependency_tree(keg_name, recursive=true)
deps_for_formula(as_formula(keg_name)
).map{ |x| as_formula(x) }
.reject{ |x| x.nil? }
.select(&:installed?
)
end
# Returns a set of dependencies as their keg name
def dependency_tree_as_keg_names(keg_name, recursive=true)
@dependency_table[keg_name] ||= dependency_tree(keg_name, recursive).map!(&:name)
end
# Return a formula for keg_name
def as_formula(keg_name)
if keg_name.is_a? Dependency
return find_active_formula(keg_name.name)
end
if keg_name.is_a? Requirement
begin
return find_active_formula(keg_name.to_dependency.name)
rescue
return nil
end
end
return find_active_formula(keg_name)
end
# Given a formula name, find the formula for the active version.
# Default formulae are for the latest version which may not be installed causing issue #28.
def find_active_formula(name)
latest_formula = Formulary.factory(name)
active_version = latest_formula.linked_version
active_prefix = latest_formula.installed_prefixes.last
begin
return Formulary.factory("#{active_prefix}/.brew/#{name}.rb")
rescue
return latest_formula
end
end
def used_by(dep_name, del_formula)
@used_by_table[dep_name] ||= uses(dep_name, false).to_set.delete(del_formula.full_name)
end
# Return list of installed formula that will still use this dependency
# after deletion and thus cannot be removed.
def still_used_by(dep_name, del_formula, full_dep_list)
# List of formulae that use this keg and aren't in the tree
# of dependencies to be removed
return used_by(dep_name, del_formula).subtract(full_dep_list)
end
def cant_remove(dep_set)
!dep_set.empty?
end
def can_remove(dep_set)
dep_set.empty?
end
def removable_in_tree(tree)
tree.select {|dep,used_by_set| can_remove(used_by_set)}
end
def unremovable_in_tree(tree)
tree.select {|dep,used_by_set| cant_remove(used_by_set)}
end
def describe_build_tree_will_remove(tree)
will_remove = removable_in_tree(tree)
puts ""
puts "Can safely be removed"
puts "----------------------"
puts will_remove.map { |dep,_| dep }.sort.join("\n")
end
def describe_build_tree_wont_remove(tree)
wont_remove = unremovable_in_tree(tree)
puts ""
puts "Won't be removed"
puts "-----------------"
puts wont_remove.map { |dep,used_by| "#{dep} is used by #{used_by.to_a.join(', ')}" }.sort.join("\n")
end
# Print out interpretation of dependency analysis
def describe_build_tree(tree)
describe_build_tree_will_remove(tree)
describe_build_tree_wont_remove(tree)
end
# Simple prompt helper
def should_proceed(prompt)
input = [(print "#{prompt}[y/N]: "), STDIN.gets.chomp()][1]
if ['y', 'yes'].include?(input.downcase)
return true
end
return false
end
def should_proceed_or_quit(prompt)
puts ""
unless should_proceed(prompt)
puts ""
onoe "User quit"
exit 0
end
return true
end
# Will mark any children and parents of dep as unremovable if dep is unremovable
def revisit_neighbors(of_dependency, del_formula, dep_set, wont_remove_because)
# Prevent subsequent related formula from being flagged for removal
dep_set.delete(of_dependency)
# Update users of the dependency
used_by(of_dependency, del_formula).each do |user_of_d|
# Only update those we visited and think we can remove
if wont_remove_because.has_key? user_of_d and can_remove(wont_remove_because[user_of_d])
wont_remove_because[user_of_d] << of_dependency
revisit_neighbors(user_of_d, del_formula, dep_set, wont_remove_because)
end
end
# Update dependencies of the dependency
dependency_tree_as_keg_names(of_dependency, false).each do |d|
# Only update those we visited and think we can remove
if wont_remove_because.has_key? d and can_remove(wont_remove_because[d])
wont_remove_because[d] << of_dependency
revisit_neighbors(d, del_formula, dep_set, wont_remove_because)
end
end
end
# Walk the tree and decide which ones are safe to remove
def build_tree(keg_name, ignored_kegs=[])
# List used to save the status of all dependency packages
wont_remove_because = {}
ohai "Examining installed formulae required by #{keg_name}..."
show_wait_spinner{
# Convert the keg_name the user provided into homebrew formula
f = as_formula(keg_name)
# Get the complete list of dependencies and convert it to just keg names
dep_arr = dependency_tree_as_keg_names(keg_name)
dep_set = dep_arr.to_set
# For each possible dependency that we want to remove, check if anything
# uses it, which is not also in the list of dependencies. That means it
# isn't safe to remove.
dep_arr.each do |dep|
# Set the progress text for spinner thread
set_spinner_progress " #{wont_remove_because.size} / #{dep_arr.length} "
# Save the list of formulae that use this keg and aren't in the tree
# of dependencies to be removed
wont_remove_because[dep] = still_used_by(dep, f, dep_set)
# Allow user to keep dependencies that aren't used anymore by saying
# something phony uses it
if ignored_kegs.include?(dep)
if wont_remove_because[dep].empty?
wont_remove_because[dep] << "ignored"
end
end
# Revisit any formulae already visited and related to this dependency
# because at the time they didn't have this new information
if cant_remove(wont_remove_because[dep])
# This dependency can't be removed. Users and dependencies need to be reconsidered.
revisit_neighbors(dep, f, dep_set, wont_remove_because)
end
set_spinner_progress " #{wont_remove_because.size} / #{dep_arr.length} "
end
}
print "\n"
return wont_remove_because
end
def order_to_be_removed_v2(start_from, wont_remove_because)
# Maintain stuff we delete
deleted_formulae = [start_from]
# Stuff we *should* be able to delete, albeit using faulty logic from before
maybe_dependencies_to_delete = removable_in_tree(wont_remove_because).map { |d,_| d }
# Keep deleting things that we *think* we can delete. As we go through the list,
# more things should become deletable. But when no new things become deletable,
# then we are done. This is hacky logic v2
last_size = 0
while maybe_dependencies_to_delete.size != last_size
last_size = maybe_dependencies_to_delete.size
maybe_dependencies_to_delete.each do |dep|
_used_by = uses(dep, false).to_set.subtract(deleted_formulae.to_set)
# puts "Deleted formulae are #{deleted_formulae.inspect()}"
# puts "#{dep} is used by #{_used_by.inspect()}"
if _used_by.size == 0
deleted_formulae << dep
maybe_dependencies_to_delete.delete dep
end
end
end
return deleted_formulae, maybe_dependencies_to_delete
end
def rmtree(keg_name, force=false, ignored_kegs=[])
# Does anything use keg such that we can't remove it?
if !force
keg_used_by = uses(keg_name, false)
if !keg_used_by.empty?
puts "#{keg_name} can't be removed because other formula depend on it:"
puts keg_used_by.join(", ")
return
end
end
# Check if the formula is installed (outdated implies installed)
unless as_formula(keg_name).installed? || as_formula(keg_name).outdated?
onoe "#{keg_name} is not currently installed"
return
end
# Dependency list of what can be removed, and what can't, and why
wont_remove_because = build_tree(keg_name, ignored_kegs)
kegs_to_delete_in_order, maybe_dependencies_to_delete = order_to_be_removed_v2(keg_name, wont_remove_because)
# Dry run print out more information on what will happen
if @dry_run
# describe_build_tree(wont_remove_because)
puts ""
puts "Can safely be removed"
puts "----------------------"
kegs_to_delete_in_order.each do |k|
puts k
end
describe_build_tree_wont_remove(wont_remove_because)
if @dry_run
maybe_dependencies_to_delete.each do |dep|
_used_by = uses(dep, false).to_set.subtract(kegs_to_delete_in_order)
puts "#{dep} is used by #{_used_by.to_a.join(', ')}"
end
end
puts ""
puts "Order of operations"
puts "-------------------"
puts kegs_to_delete_in_order
else
# Confirm with user packages that can and will be removed
# describe_build_tree_will_remove(wont_remove_because)
puts ""
puts "Can safely be removed"
puts "----------------------"
kegs_to_delete_in_order.each do |k|
puts k
end
should_proceed_or_quit("Proceed?")
ohai "Cleaning up packages safe to remove"
end
# Remove packages
# remove_keg(keg_name, @dry_run)
#removable_in_tree(wont_remove_because).map { |d,_| remove_keg(d, @dry_run) }
kegs_to_delete_in_order.each { |d| remove_keg(d, @dry_run) }
end
def main
force = false
ignored_kegs = []
rm_kegs = []
quiet = false
if ARGV.size < 1 or ['-h', '?', '--help'].include? ARGV.first
abort `brew rmtree --help`
end
raise KegUnspecifiedError if ARGV.named.empty?
loop { case ARGV[0]
when '--quiet' then ARGV.shift; quiet = true
when '--dry-run' then ARGV.shift; @dry_run = true
when '--force' then ARGV.shift; force = true
when '--ignore' then ARGV.shift; ignored_kegs.push(*ARGV); break
when /^-/ then onoe "Unknown option: #{ARGV.shift.inspect}"; abort `brew rmtree --help`
when /^[^-]/ then rm_kegs.push(ARGV.shift)
else break
end; }
# Turn off output if 'quiet' is specified
if quiet
puts_off
end
if @dry_run
puts "This is a dry-run, nothing will be deleted"
end
# Convert ignored kegs into full names
ignored_kegs.map! { |k| as_formula(k).full_name }
rm_kegs.each { |keg_name| rmtree keg_name, force, ignored_kegs }
end
end
BrewRmtree.main
exit 0
fix(main): replace ARGV with Homebrew.args
#:
#: * `rmtree` [`--force`] [`--dry-run`] [`--quiet`] formula1 [formula2] [formula3]... [`--ignore` formulaX]
#:
#: Remove a formula entirely, including all of its dependencies,
#: unless of course, they are used by another formula.
#:
#: Warning:
#:
#: Not all formulae declare their dependencies and therefore this command may end
#: up removing something you still need. It should be used with caution.
#:
#: With `--force`, you can override the dependency check for the top-level formula you
#: are trying to remove. If you try to remove 'ruby' for example, you most likely will
#: not be able to do this because other fomulae specify this as a dependency. This
#: option will let you remove 'ruby'. This will NOT bypass dependency checks for the
#: formula's children. If 'ruby' depends on 'git', then 'git' will still not be removed.
#:
#: With `--ignore`, you can ignore some dependencies from being removed. This option
#: must come after the formulae to remove.
#:
#: You can use `--dry-run` to see what would be removed without actually removing
#: anything.
#:
#: `--quiet` will hide output.
#:
#: `brew rmtree` <formula>
#: Removes <formula> and its dependencies.
#:
#: `brew rmtree` <formula> <formula2>
#: Removes <formula> and <formula2> and their dependencies.
#:
#: `brew rmtree` --force <formula>
#: Force the removal of <formula> even if other formulae depend on it.
#:
#: `brew rmtree` <formula> --ignore <formula2>
#: Remove <formula>, but don't remove its dependency of <formula2>
require 'keg'
require 'formula'
require 'formulary'
require 'dependencies'
require 'shellwords'
require 'set'
require 'cmd/deps'
# I am not a ruby-ist and so my style may offend some
module BrewRmtree
@dry_run = false
@used_by_table = {}
@dependency_table = {}
module_function
def bash(command)
escaped_command = Shellwords.escape(command)
return %x! bash -c #{escaped_command} !
end
# replaces Kernel#puts w/ do-nothing method
def puts_off
Kernel.module_eval %q{
def puts(*args)
end
def print(*args)
end
}
end
# restores Kernel#puts to its original definition
def puts_on
Kernel.module_eval %q{
def puts(*args)
$stdout.puts(*args)
end
def print(*args)
$stdout.print(*args)
end
}
end
# Sets the text to output with the spinner
def set_spinner_progress(txt)
@spinner[:progress] = txt
end
def show_wait_spinner(fps=10)
chars = %w[| / - \\]
delay = 1.0/fps
iter = 0
@spinner = Thread.new do
Thread.current[:progress] = ""
progress_size = 0
while iter do # Keep spinning until told otherwise
print ' ' + chars[(iter+=1) % chars.length] + Thread.current[:progress]
progress_size = Thread.current[:progress].length
sleep delay
print "\b"*(progress_size + 2)
end
end
yield.tap{ # After yielding to the block, save the return value
iter = false # Tell the thread to exit, cleaning up after itself…
@spinner.join # …and wait for it to do so.
} # Use the block's return value as the method's
end
# Remove a particular keg
def remove_keg(keg_name, dry_run)
if dry_run
puts "Would have removed #{keg_name}"
return
end
# Remove old versions of keg
puts bash "brew cleanup #{keg_name} 2>/dev/null"
# Remove current keg
puts bash "brew uninstall #{keg_name}"
end
# A list of dependencies of keg_name that are still installed after removal
# of the keg
def orphaned_dependencies(keg_name)
bash("join <(sort <(brew leaves)) <(sort <(brew deps #{keg_name}))").split("\n")
end
# A list of kegs that use keg_name, using homebrew code instead of shell cmd
def uses(keg_name, recursive=true, ignores=[])
# https://raw.githubusercontent.com/Homebrew/brew/master/Library/Homebrew/cmd/uses.rb
formulae = [Formulary.factory(keg_name)]
uses = Formula.installed.select do |f|
formulae.all? do |ff|
begin
if recursive
deps = f.recursive_dependencies do |dependent, dep|
if dep.recommended?
Dependency.prune if ignores.include?("recommended?") || dependent.build.without?(dep)
elsif dep.optional?
Dependency.prune if !includes.include?("optional?") && !dependent.build.with?(dep)
elsif dep.build?
Dependency.prune unless includes.include?("build?")
end
# If a tap isn't installed, we can't find the dependencies of one
# its formulae, and an exception will be thrown if we try.
if dep.is_a?(TapDependency) && !dep.tap.installed?
Dependency.keep_but_prune_recursive_deps
end
end
dep_formulae = deps.flat_map do |dep|
begin
dep.to_formula
rescue
[]
end
end
reqs_by_formula = ([f] + dep_formulae).flat_map do |formula|
formula.requirements.map { |req| [formula, req] }
end
reqs_by_formula.reject! do |dependent, req|
if req.recommended?
ignores.include?("recommended?") || dependent.build.without?(req)
elsif req.optional?
!includes.include?("optional?") && !dependent.build.with?(req)
elsif req.build?
!includes.include?("build?")
end
end
reqs = reqs_by_formula.map(&:last)
else
includes, ignores = Homebrew.argv_includes_ignores(["--installed"])
deps = f.deps.reject do |dep|
ignores.any? { |ignore| dep.send(ignore) } && includes.none? { |include| dep.send(include) }
end
# deps.reject! do |dep|
# # Exclude build dependencies or not required and can be built without it
# dep.build? || (!dep.required? && as_formula(dep.name).build.without?(dep))
# end
reqs = f.requirements.reject do |req|
ignores.any? { |ignore| req.send(ignore) } && includes.none? { |include| req.send(include) }
end
end
next true if deps.any? do |dep|
begin
dep.to_formula.full_name == ff.full_name
rescue
dep.name == ff.name
end
end
reqs.any? { |req| req.name == ff.name }
rescue FormulaUnavailableError
# Silently ignore this case as we don't care about things used in
# taps that aren't currently tapped.
next
end
end
end
uses.map(&:full_name)
end
def deps_for_formula(f)
# https://github.com/Homebrew/brew/blob/d1b83819deacd99b55c9d400149dc9b49fa795df/Library/Homebrew/cmd/deps.rb#L137
includes, ignores = Homebrew.argv_includes_ignores(["--installed"])
deps = f.runtime_dependencies
reqs = Homebrew.reject_ignores(f.requirements, ignores, includes)
deps + reqs.to_a
end
# Gather complete list of packages used by root package
def dependency_tree(keg_name, recursive=true)
deps_for_formula(as_formula(keg_name)
).map{ |x| as_formula(x) }
.reject{ |x| x.nil? }
.select(&:installed?
)
end
# Returns a set of dependencies as their keg name
def dependency_tree_as_keg_names(keg_name, recursive=true)
@dependency_table[keg_name] ||= dependency_tree(keg_name, recursive).map!(&:name)
end
# Return a formula for keg_name
def as_formula(keg_name)
if keg_name.is_a? Dependency
return find_active_formula(keg_name.name)
end
if keg_name.is_a? Requirement
begin
return find_active_formula(keg_name.to_dependency.name)
rescue
return nil
end
end
return find_active_formula(keg_name)
end
# Given a formula name, find the formula for the active version.
# Default formulae are for the latest version which may not be installed causing issue #28.
def find_active_formula(name)
latest_formula = Formulary.factory(name)
active_version = latest_formula.linked_version
active_prefix = latest_formula.installed_prefixes.last
begin
return Formulary.factory("#{active_prefix}/.brew/#{name}.rb")
rescue
return latest_formula
end
end
def used_by(dep_name, del_formula)
@used_by_table[dep_name] ||= uses(dep_name, false).to_set.delete(del_formula.full_name)
end
# Return list of installed formula that will still use this dependency
# after deletion and thus cannot be removed.
def still_used_by(dep_name, del_formula, full_dep_list)
# List of formulae that use this keg and aren't in the tree
# of dependencies to be removed
return used_by(dep_name, del_formula).subtract(full_dep_list)
end
def cant_remove(dep_set)
!dep_set.empty?
end
def can_remove(dep_set)
dep_set.empty?
end
def removable_in_tree(tree)
tree.select {|dep,used_by_set| can_remove(used_by_set)}
end
def unremovable_in_tree(tree)
tree.select {|dep,used_by_set| cant_remove(used_by_set)}
end
def describe_build_tree_will_remove(tree)
will_remove = removable_in_tree(tree)
puts ""
puts "Can safely be removed"
puts "----------------------"
puts will_remove.map { |dep,_| dep }.sort.join("\n")
end
def describe_build_tree_wont_remove(tree)
wont_remove = unremovable_in_tree(tree)
puts ""
puts "Won't be removed"
puts "-----------------"
puts wont_remove.map { |dep,used_by| "#{dep} is used by #{used_by.to_a.join(', ')}" }.sort.join("\n")
end
# Print out interpretation of dependency analysis
def describe_build_tree(tree)
describe_build_tree_will_remove(tree)
describe_build_tree_wont_remove(tree)
end
# Simple prompt helper
def should_proceed(prompt)
input = [(print "#{prompt}[y/N]: "), STDIN.gets.chomp()][1]
if ['y', 'yes'].include?(input.downcase)
return true
end
return false
end
def should_proceed_or_quit(prompt)
puts ""
unless should_proceed(prompt)
puts ""
onoe "User quit"
exit 0
end
return true
end
# Will mark any children and parents of dep as unremovable if dep is unremovable
def revisit_neighbors(of_dependency, del_formula, dep_set, wont_remove_because)
# Prevent subsequent related formula from being flagged for removal
dep_set.delete(of_dependency)
# Update users of the dependency
used_by(of_dependency, del_formula).each do |user_of_d|
# Only update those we visited and think we can remove
if wont_remove_because.has_key? user_of_d and can_remove(wont_remove_because[user_of_d])
wont_remove_because[user_of_d] << of_dependency
revisit_neighbors(user_of_d, del_formula, dep_set, wont_remove_because)
end
end
# Update dependencies of the dependency
dependency_tree_as_keg_names(of_dependency, false).each do |d|
# Only update those we visited and think we can remove
if wont_remove_because.has_key? d and can_remove(wont_remove_because[d])
wont_remove_because[d] << of_dependency
revisit_neighbors(d, del_formula, dep_set, wont_remove_because)
end
end
end
# Walk the tree and decide which ones are safe to remove
def build_tree(keg_name, ignored_kegs=[])
# List used to save the status of all dependency packages
wont_remove_because = {}
ohai "Examining installed formulae required by #{keg_name}..."
show_wait_spinner{
# Convert the keg_name the user provided into homebrew formula
f = as_formula(keg_name)
# Get the complete list of dependencies and convert it to just keg names
dep_arr = dependency_tree_as_keg_names(keg_name)
dep_set = dep_arr.to_set
# For each possible dependency that we want to remove, check if anything
# uses it, which is not also in the list of dependencies. That means it
# isn't safe to remove.
dep_arr.each do |dep|
# Set the progress text for spinner thread
set_spinner_progress " #{wont_remove_because.size} / #{dep_arr.length} "
# Save the list of formulae that use this keg and aren't in the tree
# of dependencies to be removed
wont_remove_because[dep] = still_used_by(dep, f, dep_set)
# Allow user to keep dependencies that aren't used anymore by saying
# something phony uses it
if ignored_kegs.include?(dep)
if wont_remove_because[dep].empty?
wont_remove_because[dep] << "ignored"
end
end
# Revisit any formulae already visited and related to this dependency
# because at the time they didn't have this new information
if cant_remove(wont_remove_because[dep])
# This dependency can't be removed. Users and dependencies need to be reconsidered.
revisit_neighbors(dep, f, dep_set, wont_remove_because)
end
set_spinner_progress " #{wont_remove_because.size} / #{dep_arr.length} "
end
}
print "\n"
return wont_remove_because
end
def order_to_be_removed_v2(start_from, wont_remove_because)
# Maintain stuff we delete
deleted_formulae = [start_from]
# Stuff we *should* be able to delete, albeit using faulty logic from before
maybe_dependencies_to_delete = removable_in_tree(wont_remove_because).map { |d,_| d }
# Keep deleting things that we *think* we can delete. As we go through the list,
# more things should become deletable. But when no new things become deletable,
# then we are done. This is hacky logic v2
last_size = 0
while maybe_dependencies_to_delete.size != last_size
last_size = maybe_dependencies_to_delete.size
maybe_dependencies_to_delete.each do |dep|
_used_by = uses(dep, false).to_set.subtract(deleted_formulae.to_set)
# puts "Deleted formulae are #{deleted_formulae.inspect()}"
# puts "#{dep} is used by #{_used_by.inspect()}"
if _used_by.size == 0
deleted_formulae << dep
maybe_dependencies_to_delete.delete dep
end
end
end
return deleted_formulae, maybe_dependencies_to_delete
end
def rmtree(keg_name, force=false, ignored_kegs=[])
# Does anything use keg such that we can't remove it?
if !force
keg_used_by = uses(keg_name, false)
if !keg_used_by.empty?
puts "#{keg_name} can't be removed because other formula depend on it:"
puts keg_used_by.join(", ")
return
end
end
# Check if the formula is installed (outdated implies installed)
unless as_formula(keg_name).installed? || as_formula(keg_name).outdated?
onoe "#{keg_name} is not currently installed"
return
end
# Dependency list of what can be removed, and what can't, and why
wont_remove_because = build_tree(keg_name, ignored_kegs)
kegs_to_delete_in_order, maybe_dependencies_to_delete = order_to_be_removed_v2(keg_name, wont_remove_because)
# Dry run print out more information on what will happen
if @dry_run
# describe_build_tree(wont_remove_because)
puts ""
puts "Can safely be removed"
puts "----------------------"
kegs_to_delete_in_order.each do |k|
puts k
end
describe_build_tree_wont_remove(wont_remove_because)
if @dry_run
maybe_dependencies_to_delete.each do |dep|
_used_by = uses(dep, false).to_set.subtract(kegs_to_delete_in_order)
puts "#{dep} is used by #{_used_by.to_a.join(', ')}"
end
end
puts ""
puts "Order of operations"
puts "-------------------"
puts kegs_to_delete_in_order
else
# Confirm with user packages that can and will be removed
# describe_build_tree_will_remove(wont_remove_because)
puts ""
puts "Can safely be removed"
puts "----------------------"
kegs_to_delete_in_order.each do |k|
puts k
end
should_proceed_or_quit("Proceed?")
ohai "Cleaning up packages safe to remove"
end
# Remove packages
# remove_keg(keg_name, @dry_run)
#removable_in_tree(wont_remove_because).map { |d,_| remove_keg(d, @dry_run) }
kegs_to_delete_in_order.each { |d| remove_keg(d, @dry_run) }
end
def main
force = false
ignored_kegs = []
rm_kegs = []
quiet = false
if ARGV.size < 1 or ['-h', '?', '--help'].include? ARGV.first
abort `brew rmtree --help`
end
raise KegUnspecifiedError if Homebrew.args.no_named?
loop { case ARGV[0]
when '--quiet' then ARGV.shift; quiet = true
when '--dry-run' then ARGV.shift; @dry_run = true
when '--force' then ARGV.shift; force = true
when '--ignore' then ARGV.shift; ignored_kegs.push(*ARGV); break
when /^-/ then onoe "Unknown option: #{ARGV.shift.inspect}"; abort `brew rmtree --help`
when /^[^-]/ then rm_kegs.push(ARGV.shift)
else break
end; }
# Turn off output if 'quiet' is specified
if quiet
puts_off
end
if @dry_run
puts "This is a dry-run, nothing will be deleted"
end
# Convert ignored kegs into full names
ignored_kegs.map! { |k| as_formula(k).full_name }
rm_kegs.each { |keg_name| rmtree keg_name, force, ignored_kegs }
end
end
BrewRmtree.main
exit 0
|
#:
#: * `rmtree` [`--force`] [`-n`|`--dry-run`] [`--quiet`] [`--ignore=`formulaX,formulaY] formula1 [formula2] [formula3]...
#:
#: Remove a formula entirely, including all of its dependencies,
#: unless of course, they are used by another formula.
#:
#: Warning:
#:
#: Not all formulae declare their dependencies and therefore this command may end
#: up removing something you still need. It should be used with caution.
#:
#: With `--force`, you can override the dependency check for the top-level formula you
#: are trying to remove. If you try to remove 'ruby' for example, you most likely will
#: not be able to do this because other fomulae specify this as a dependency. This
#: option will let you remove 'ruby'. This will NOT bypass dependency checks for the
#: formula's children. If 'ruby' depends on 'git', then 'git' will still not be removed.
#:
#: With `--ignore`, you can ignore some dependencies from being removed.
#:
#: You can use `--dry-run` (alias `-n`) to see what would be removed without
#: actually removing anything.
#:
#: `--quiet` will hide output.
#:
#: `brew rmtree` <formula>
#: Removes <formula> and its dependencies.
#:
#: `brew rmtree` <formula> <formula2>
#: Removes <formula> and <formula2> and their dependencies.
#:
#: `brew rmtree` --force <formula>
#: Force the removal of <formula> even if other formulae depend on it.
#:
#: `brew rmtree` --ignore=<formula2> <formula>
#: Remove <formula>, but don't remove its dependency of <formula2>
require 'keg'
require 'formula'
require 'formulary'
require 'dependencies'
require 'shellwords'
require 'set'
require 'cmd/deps'
require 'cli/parser'
# I am not a ruby-ist and so my style may offend some
module BrewRmtree
@dry_run = false
@used_by_table = {}
@dependency_table = {}
module_function
def bash(command)
escaped_command = Shellwords.escape(command)
return %x! bash -c #{escaped_command} !
end
# replaces Kernel#puts w/ do-nothing method
def puts_off
Kernel.module_eval %q{
def puts(*args)
end
def print(*args)
end
}
end
# restores Kernel#puts to its original definition
def puts_on
Kernel.module_eval %q{
def puts(*args)
$stdout.puts(*args)
end
def print(*args)
$stdout.print(*args)
end
}
end
# Sets the text to output with the spinner
def set_spinner_progress(txt)
@spinner[:progress] = txt
end
def show_wait_spinner(fps=10)
chars = %w[| / - \\]
delay = 1.0/fps
iter = 0
@spinner = Thread.new do
Thread.current[:progress] = ""
progress_size = 0
while iter do # Keep spinning until told otherwise
print ' ' + chars[(iter+=1) % chars.length] + Thread.current[:progress]
progress_size = Thread.current[:progress].length
sleep delay
print "\b"*(progress_size + 2)
end
end
yield.tap{ # After yielding to the block, save the return value
iter = false # Tell the thread to exit, cleaning up after itself…
@spinner.join # …and wait for it to do so.
} # Use the block's return value as the method's
end
# Remove a particular keg
def remove_keg(keg_name, dry_run)
if dry_run
puts "Would have removed #{keg_name}"
return
end
# Remove old versions of keg
puts bash "brew cleanup #{keg_name} 2>/dev/null"
# Remove current keg
puts bash "brew uninstall #{keg_name}"
end
# A list of dependencies of keg_name that are still installed after removal
# of the keg
def orphaned_dependencies(keg_name)
bash("join <(sort <(brew leaves)) <(sort <(brew deps #{keg_name}))").split("\n")
end
# A list of kegs that use keg_name, using homebrew code instead of shell cmd
def uses(keg_name, recursive=true, ignores=[])
# https://raw.githubusercontent.com/Homebrew/brew/master/Library/Homebrew/cmd/uses.rb
formulae = [Formulary.factory(keg_name)]
uses = Formula.installed.select do |f|
formulae.all? do |ff|
begin
if recursive
deps = f.recursive_dependencies do |dependent, dep|
if dep.recommended?
Dependency.prune if ignores.include?("recommended?") || dependent.build.without?(dep)
elsif dep.optional?
Dependency.prune if !includes.include?("optional?") && !dependent.build.with?(dep)
elsif dep.build?
Dependency.prune unless includes.include?("build?")
end
# If a tap isn't installed, we can't find the dependencies of one
# its formulae, and an exception will be thrown if we try.
if dep.is_a?(TapDependency) && !dep.tap.installed?
Dependency.keep_but_prune_recursive_deps
end
end
dep_formulae = deps.flat_map do |dep|
begin
dep.to_formula
rescue
[]
end
end
reqs_by_formula = ([f] + dep_formulae).flat_map do |formula|
formula.requirements.map { |req| [formula, req] }
end
reqs_by_formula.reject! do |dependent, req|
if req.recommended?
ignores.include?("recommended?") || dependent.build.without?(req)
elsif req.optional?
!includes.include?("optional?") && !dependent.build.with?(req)
elsif req.build?
!includes.include?("build?")
end
end
reqs = reqs_by_formula.map(&:last)
else
includes, ignores = Homebrew.argv_includes_ignores(["--installed"])
deps = f.deps.reject do |dep|
ignores.any? { |ignore| dep.send(ignore) } && includes.none? { |include| dep.send(include) }
end
# deps.reject! do |dep|
# # Exclude build dependencies or not required and can be built without it
# dep.build? || (!dep.required? && as_formula(dep.name).build.without?(dep))
# end
reqs = f.requirements.reject do |req|
ignores.any? { |ignore| req.send(ignore) } && includes.none? { |include| req.send(include) }
end
end
next true if deps.any? do |dep|
begin
dep.to_formula.full_name == ff.full_name
rescue
dep.name == ff.name
end
end
reqs.any? { |req| req.name == ff.name }
rescue FormulaUnavailableError
# Silently ignore this case as we don't care about things used in
# taps that aren't currently tapped.
next
end
end
end
uses.map(&:full_name)
end
def deps_for_formula(f)
# https://github.com/Homebrew/brew/blob/d1b83819deacd99b55c9d400149dc9b49fa795df/Library/Homebrew/cmd/deps.rb#L137
includes, ignores = Homebrew.argv_includes_ignores(["--installed"])
deps = f.runtime_dependencies
reqs = Homebrew.reject_ignores(f.requirements, ignores, includes)
deps + reqs.to_a
end
# Gather complete list of packages used by root package
def dependency_tree(keg_name, recursive=true)
deps_for_formula(as_formula(keg_name)
).map{ |x| as_formula(x) }
.reject{ |x| x.nil? }
.select(&:any_version_installed?
)
end
# Returns a set of dependencies as their keg name
def dependency_tree_as_keg_names(keg_name, recursive=true)
@dependency_table[keg_name] ||= dependency_tree(keg_name, recursive).map!(&:name)
end
# Return a formula for keg_name
def as_formula(keg_name)
if keg_name.is_a? Dependency
return find_active_formula(keg_name.name)
end
if keg_name.is_a? Requirement
begin
return find_active_formula(keg_name.to_dependency.name)
rescue
return nil
end
end
return find_active_formula(keg_name)
end
# Given a formula name, find the formula for the active version.
# Default formulae are for the latest version which may not be installed causing issue #28.
def find_active_formula(name)
latest_formula = Formulary.factory(name)
active_version = latest_formula.linked_version
active_prefix = latest_formula.installed_prefixes.last
begin
return Formulary.factory("#{active_prefix}/.brew/#{name}.rb")
rescue
return latest_formula
end
end
def used_by(dep_name, del_formula)
@used_by_table[dep_name] ||= uses(dep_name, false).to_set.delete(del_formula.full_name)
end
# Return list of installed formula that will still use this dependency
# after deletion and thus cannot be removed.
def still_used_by(dep_name, del_formula, full_dep_list)
# List of formulae that use this keg and aren't in the tree
# of dependencies to be removed
return used_by(dep_name, del_formula).subtract(full_dep_list)
end
def cant_remove(dep_set)
!dep_set.empty?
end
def can_remove(dep_set)
dep_set.empty?
end
def removable_in_tree(tree)
tree.select {|dep,used_by_set| can_remove(used_by_set)}
end
def unremovable_in_tree(tree)
tree.select {|dep,used_by_set| cant_remove(used_by_set)}
end
def describe_build_tree_will_remove(tree)
will_remove = removable_in_tree(tree)
puts ""
puts "Can safely be removed"
puts "----------------------"
puts will_remove.map { |dep,_| dep }.sort.join("\n")
end
def describe_build_tree_wont_remove(tree)
wont_remove = unremovable_in_tree(tree)
puts ""
puts "Won't be removed"
puts "-----------------"
puts wont_remove.map { |dep,used_by| "#{dep} is used by #{used_by.to_a.join(', ')}" }.sort.join("\n")
end
# Print out interpretation of dependency analysis
def describe_build_tree(tree)
describe_build_tree_will_remove(tree)
describe_build_tree_wont_remove(tree)
end
# Simple prompt helper
def should_proceed(prompt)
input = [(print "#{prompt}[y/N]: "), STDIN.gets.chomp()][1]
if ['y', 'yes'].include?(input.downcase)
return true
end
return false
end
def should_proceed_or_quit(prompt)
puts ""
unless should_proceed(prompt)
puts ""
onoe "User quit"
exit 0
end
return true
end
# Will mark any children and parents of dep as unremovable if dep is unremovable
def revisit_neighbors(of_dependency, del_formula, dep_set, wont_remove_because)
# Prevent subsequent related formula from being flagged for removal
dep_set.delete(of_dependency)
# Update users of the dependency
used_by(of_dependency, del_formula).each do |user_of_d|
# Only update those we visited and think we can remove
if wont_remove_because.has_key? user_of_d and can_remove(wont_remove_because[user_of_d])
wont_remove_because[user_of_d] << of_dependency
revisit_neighbors(user_of_d, del_formula, dep_set, wont_remove_because)
end
end
# Update dependencies of the dependency
dependency_tree_as_keg_names(of_dependency, false).each do |d|
# Only update those we visited and think we can remove
if wont_remove_because.has_key? d and can_remove(wont_remove_because[d])
wont_remove_because[d] << of_dependency
revisit_neighbors(d, del_formula, dep_set, wont_remove_because)
end
end
end
# Walk the tree and decide which ones are safe to remove
def build_tree(keg_name, ignored_kegs=[])
# List used to save the status of all dependency packages
wont_remove_because = {}
ohai "Examining installed formulae required by #{keg_name}..."
show_wait_spinner{
# Convert the keg_name the user provided into homebrew formula
f = as_formula(keg_name)
# Get the complete list of dependencies and convert it to just keg names
dep_arr = dependency_tree_as_keg_names(keg_name)
dep_set = dep_arr.to_set
# For each possible dependency that we want to remove, check if anything
# uses it, which is not also in the list of dependencies. That means it
# isn't safe to remove.
dep_arr.each do |dep|
# Set the progress text for spinner thread
set_spinner_progress " #{wont_remove_because.size} / #{dep_arr.length} "
# Save the list of formulae that use this keg and aren't in the tree
# of dependencies to be removed
wont_remove_because[dep] = still_used_by(dep, f, dep_set)
# Allow user to keep dependencies that aren't used anymore by saying
# something phony uses it
if ignored_kegs.include?(dep)
if wont_remove_because[dep].empty?
wont_remove_because[dep] << "ignored"
end
end
# Revisit any formulae already visited and related to this dependency
# because at the time they didn't have this new information
if cant_remove(wont_remove_because[dep])
# This dependency can't be removed. Users and dependencies need to be reconsidered.
revisit_neighbors(dep, f, dep_set, wont_remove_because)
end
set_spinner_progress " #{wont_remove_because.size} / #{dep_arr.length} "
end
}
print "\n"
return wont_remove_because
end
def order_to_be_removed_v2(start_from, wont_remove_because)
# Maintain stuff we delete
deleted_formulae = [start_from]
# Stuff we *should* be able to delete, albeit using faulty logic from before
maybe_dependencies_to_delete = removable_in_tree(wont_remove_because).map { |d,_| d }
# Keep deleting things that we *think* we can delete. As we go through the list,
# more things should become deletable. But when no new things become deletable,
# then we are done. This is hacky logic v2
last_size = 0
while maybe_dependencies_to_delete.size != last_size
last_size = maybe_dependencies_to_delete.size
maybe_dependencies_to_delete.each do |dep|
_used_by = uses(dep, false).to_set.subtract(deleted_formulae.to_set)
# puts "Deleted formulae are #{deleted_formulae.inspect()}"
# puts "#{dep} is used by #{_used_by.inspect()}"
if _used_by.size == 0
deleted_formulae << dep
maybe_dependencies_to_delete.delete dep
end
end
end
return deleted_formulae, maybe_dependencies_to_delete
end
def rmtree(keg_name, force=false, ignored_kegs=[])
# Does anything use keg such that we can't remove it?
if !force
keg_used_by = uses(keg_name, false)
if !keg_used_by.empty?
puts "#{keg_name} can't be removed because other formula depend on it:"
puts keg_used_by.join(", ")
return
end
end
# Check if the formula is installed (outdated implies installed)
unless as_formula(keg_name).any_version_installed? || as_formula(keg_name).outdated?
onoe "#{keg_name} is not currently installed"
return
end
# Dependency list of what can be removed, and what can't, and why
wont_remove_because = build_tree(keg_name, ignored_kegs)
kegs_to_delete_in_order, maybe_dependencies_to_delete = order_to_be_removed_v2(keg_name, wont_remove_because)
# Dry run print out more information on what will happen
if @dry_run
# describe_build_tree(wont_remove_because)
puts ""
puts "Can safely be removed"
puts "----------------------"
kegs_to_delete_in_order.each do |k|
puts k
end
describe_build_tree_wont_remove(wont_remove_because)
if @dry_run
maybe_dependencies_to_delete.each do |dep|
_used_by = uses(dep, false).to_set.subtract(kegs_to_delete_in_order)
puts "#{dep} is used by #{_used_by.to_a.join(', ')}"
end
end
puts ""
puts "Order of operations"
puts "-------------------"
puts kegs_to_delete_in_order
else
# Confirm with user packages that can and will be removed
# describe_build_tree_will_remove(wont_remove_because)
puts ""
puts "Can safely be removed"
puts "----------------------"
kegs_to_delete_in_order.each do |k|
puts k
end
should_proceed_or_quit("Proceed?")
ohai "Cleaning up packages safe to remove"
end
# Remove packages
# remove_keg(keg_name, @dry_run)
#removable_in_tree(wont_remove_because).map { |d,_| remove_keg(d, @dry_run) }
kegs_to_delete_in_order.each { |d| remove_keg(d, @dry_run) }
end
def rmtree_args
Homebrew::CLI::Parser.new do
usage_banner <<~EOS
`rmtree` [<options>] [<formula>]
Remove a formula entirely, including all of its dependencies, unless of course,
they are used by another formula.
Warning:
Not all formulae declare their dependencies and therefore this command may end
up removing something you still need. It should be used with caution.
EOS
switch "--quiet",
description: "Hide output."
switch "-n", "--dry-run",
description: "See what would be removed without actually removing anything."
switch "--force",
description: "Force the removal of <formula> even if other formulae depend on it. " +
"You can override the dependency check for the top-level formula you " +
"are trying to remove. \nFor example, if you try to remove 'ruby', you most likely will " +
"not be able to do this because other fomulae specify this as a dependency. This " +
"option will enable you to remove 'ruby'. This will NOT bypass dependency checks for the " +
"formula's children. If 'ruby' depends on 'git', then 'git' will still not be removed. Sorry."
comma_array "--ignore=",
description: "Ignore some dependencies from being removed. Specify multiple values separated by a comma."
end
end
def main
rmtree_args.parse
force = Homebrew.args.force?
ignored_kegs = []
ignored_kegs.push(*Homebrew.args.ignore)
rm_kegs = Homebrew.args.named
quiet = Homebrew.args.quiet?
@dry_run = Homebrew.args.dry_run?
raise KegUnspecifiedError if Homebrew.args.no_named?
# Turn off output if 'quiet' is specified
if quiet
puts_off
end
if @dry_run
puts "This is a dry-run, nothing will be deleted"
end
# Convert ignored kegs into full names
ignored_kegs.map! { |k| as_formula(k).full_name }
rm_kegs.each { |keg_name| rmtree keg_name, force, ignored_kegs }
end
end
BrewRmtree.main
exit 0
fixed arg passing due to Homebrew/brew#8144 (#42)
#:
#: * `rmtree` [`--force`] [`-n`|`--dry-run`] [`--quiet`] [`--ignore=`formulaX,formulaY] formula1 [formula2] [formula3]...
#:
#: Remove a formula entirely, including all of its dependencies,
#: unless of course, they are used by another formula.
#:
#: Warning:
#:
#: Not all formulae declare their dependencies and therefore this command may end
#: up removing something you still need. It should be used with caution.
#:
#: With `--force`, you can override the dependency check for the top-level formula you
#: are trying to remove. If you try to remove 'ruby' for example, you most likely will
#: not be able to do this because other fomulae specify this as a dependency. This
#: option will let you remove 'ruby'. This will NOT bypass dependency checks for the
#: formula's children. If 'ruby' depends on 'git', then 'git' will still not be removed.
#:
#: With `--ignore`, you can ignore some dependencies from being removed.
#:
#: You can use `--dry-run` (alias `-n`) to see what would be removed without
#: actually removing anything.
#:
#: `--quiet` will hide output.
#:
#: `brew rmtree` <formula>
#: Removes <formula> and its dependencies.
#:
#: `brew rmtree` <formula> <formula2>
#: Removes <formula> and <formula2> and their dependencies.
#:
#: `brew rmtree` --force <formula>
#: Force the removal of <formula> even if other formulae depend on it.
#:
#: `brew rmtree` --ignore=<formula2> <formula>
#: Remove <formula>, but don't remove its dependency of <formula2>
require 'keg'
require 'formula'
require 'formulary'
require 'dependencies'
require 'shellwords'
require 'set'
require 'cmd/deps'
require 'cli/parser'
# I am not a ruby-ist and so my style may offend some
module BrewRmtree
@dry_run = false
@used_by_table = {}
@dependency_table = {}
module_function
def bash(command)
escaped_command = Shellwords.escape(command)
return %x! bash -c #{escaped_command} !
end
# replaces Kernel#puts w/ do-nothing method
def puts_off
Kernel.module_eval %q{
def puts(*args)
end
def print(*args)
end
}
end
# restores Kernel#puts to its original definition
def puts_on
Kernel.module_eval %q{
def puts(*args)
$stdout.puts(*args)
end
def print(*args)
$stdout.print(*args)
end
}
end
# Sets the text to output with the spinner
def set_spinner_progress(txt)
@spinner[:progress] = txt
end
def show_wait_spinner(fps=10)
chars = %w[| / - \\]
delay = 1.0/fps
iter = 0
@spinner = Thread.new do
Thread.current[:progress] = ""
progress_size = 0
while iter do # Keep spinning until told otherwise
print ' ' + chars[(iter+=1) % chars.length] + Thread.current[:progress]
progress_size = Thread.current[:progress].length
sleep delay
print "\b"*(progress_size + 2)
end
end
yield.tap{ # After yielding to the block, save the return value
iter = false # Tell the thread to exit, cleaning up after itself…
@spinner.join # …and wait for it to do so.
} # Use the block's return value as the method's
end
# Remove a particular keg
def remove_keg(keg_name, dry_run)
if dry_run
puts "Would have removed #{keg_name}"
return
end
# Remove old versions of keg
puts bash "brew cleanup #{keg_name} 2>/dev/null"
# Remove current keg
puts bash "brew uninstall #{keg_name}"
end
# A list of dependencies of keg_name that are still installed after removal
# of the keg
def orphaned_dependencies(keg_name)
bash("join <(sort <(brew leaves)) <(sort <(brew deps #{keg_name}))").split("\n")
end
# A list of kegs that use keg_name, using homebrew code instead of shell cmd
def uses(keg_name, recursive=true, ignores=[], args:)
# https://raw.githubusercontent.com/Homebrew/brew/master/Library/Homebrew/cmd/uses.rb
formulae = [Formulary.factory(keg_name)]
uses = Formula.installed.select do |f|
formulae.all? do |ff|
begin
if recursive
deps = f.recursive_dependencies do |dependent, dep|
if dep.recommended?
Dependency.prune if ignores.include?("recommended?") || dependent.build.without?(dep)
elsif dep.optional?
Dependency.prune if !includes.include?("optional?") && !dependent.build.with?(dep)
elsif dep.build?
Dependency.prune unless includes.include?("build?")
end
# If a tap isn't installed, we can't find the dependencies of one
# its formulae, and an exception will be thrown if we try.
if dep.is_a?(TapDependency) && !dep.tap.installed?
Dependency.keep_but_prune_recursive_deps
end
end
dep_formulae = deps.flat_map do |dep|
begin
dep.to_formula
rescue
[]
end
end
reqs_by_formula = ([f] + dep_formulae).flat_map do |formula|
formula.requirements.map { |req| [formula, req] }
end
reqs_by_formula.reject! do |dependent, req|
if req.recommended?
ignores.include?("recommended?") || dependent.build.without?(req)
elsif req.optional?
!includes.include?("optional?") && !dependent.build.with?(req)
elsif req.build?
!includes.include?("build?")
end
end
reqs = reqs_by_formula.map(&:last)
else
includes, ignores = Homebrew.args_includes_ignores(args)
deps = f.deps.reject do |dep|
ignores.any? { |ignore| dep.send(ignore) } && includes.none? { |include| dep.send(include) }
end
# deps.reject! do |dep|
# # Exclude build dependencies or not required and can be built without it
# dep.build? || (!dep.required? && as_formula(dep.name).build.without?(dep))
# end
reqs = f.requirements.reject do |req|
ignores.any? { |ignore| req.send(ignore) } && includes.none? { |include| req.send(include) }
end
end
next true if deps.any? do |dep|
begin
dep.to_formula.full_name == ff.full_name
rescue
dep.name == ff.name
end
end
reqs.any? { |req| req.name == ff.name }
rescue FormulaUnavailableError
# Silently ignore this case as we don't care about things used in
# taps that aren't currently tapped.
next
end
end
end
uses.map(&:full_name)
end
def deps_for_formula(f, args:)
# https://github.com/Homebrew/brew/blob/d1b83819deacd99b55c9d400149dc9b49fa795df/Library/Homebrew/cmd/deps.rb#L137
includes, ignores = Homebrew.args_includes_ignores(args)
deps = f.runtime_dependencies
reqs = Homebrew.reject_ignores(f.requirements, ignores, includes)
deps + reqs.to_a
end
# Gather complete list of packages used by root package
def dependency_tree(keg_name, recursive=true, args:)
deps_for_formula(as_formula(keg_name), args: args
).map{ |x| as_formula(x) }
.reject{ |x| x.nil? }
.select(&:any_version_installed?
)
end
# Returns a set of dependencies as their keg name
def dependency_tree_as_keg_names(keg_name, recursive=true, args:)
@dependency_table[keg_name] ||= dependency_tree(keg_name, recursive, args: args).map!(&:name)
end
# Return a formula for keg_name
def as_formula(keg_name)
if keg_name.is_a? Dependency
return find_active_formula(keg_name.name)
end
if keg_name.is_a? Requirement
begin
return find_active_formula(keg_name.to_dependency.name)
rescue
return nil
end
end
return find_active_formula(keg_name)
end
# Given a formula name, find the formula for the active version.
# Default formulae are for the latest version which may not be installed causing issue #28.
def find_active_formula(name)
latest_formula = Formulary.factory(name)
active_version = latest_formula.linked_version
active_prefix = latest_formula.installed_prefixes.last
begin
return Formulary.factory("#{active_prefix}/.brew/#{name}.rb")
rescue
return latest_formula
end
end
def used_by(dep_name, del_formula, args:)
@used_by_table[dep_name] ||= uses(dep_name, false, args: args).to_set.delete(del_formula.full_name)
end
# Return list of installed formula that will still use this dependency
# after deletion and thus cannot be removed.
def still_used_by(dep_name, del_formula, full_dep_list, args:)
# List of formulae that use this keg and aren't in the tree
# of dependencies to be removed
return used_by(dep_name, del_formula, args: args).subtract(full_dep_list)
end
def cant_remove(dep_set)
!dep_set.empty?
end
def can_remove(dep_set)
dep_set.empty?
end
def removable_in_tree(tree)
tree.select {|dep,used_by_set| can_remove(used_by_set)}
end
def unremovable_in_tree(tree)
tree.select {|dep,used_by_set| cant_remove(used_by_set)}
end
def describe_build_tree_will_remove(tree)
will_remove = removable_in_tree(tree)
puts ""
puts "Can safely be removed"
puts "----------------------"
puts will_remove.map { |dep,_| dep }.sort.join("\n")
end
def describe_build_tree_wont_remove(tree)
wont_remove = unremovable_in_tree(tree)
puts ""
puts "Won't be removed"
puts "-----------------"
puts wont_remove.map { |dep,used_by| "#{dep} is used by #{used_by.to_a.join(', ')}" }.sort.join("\n")
end
# Print out interpretation of dependency analysis
def describe_build_tree(tree)
describe_build_tree_will_remove(tree)
describe_build_tree_wont_remove(tree)
end
# Simple prompt helper
def should_proceed(prompt)
input = [(print "#{prompt}[y/N]: "), STDIN.gets.chomp()][1]
if ['y', 'yes'].include?(input.downcase)
return true
end
return false
end
def should_proceed_or_quit(prompt)
puts ""
unless should_proceed(prompt)
puts ""
onoe "User quit"
exit 0
end
return true
end
# Will mark any children and parents of dep as unremovable if dep is unremovable
def revisit_neighbors(of_dependency, del_formula, dep_set, wont_remove_because, args:)
# Prevent subsequent related formula from being flagged for removal
dep_set.delete(of_dependency)
# Update users of the dependency
used_by(of_dependency, del_formula, args: args).each do |user_of_d|
# Only update those we visited and think we can remove
if wont_remove_because.has_key? user_of_d and can_remove(wont_remove_because[user_of_d])
wont_remove_because[user_of_d] << of_dependency
revisit_neighbors(user_of_d, del_formula, dep_set, wont_remove_because, args: args)
end
end
# Update dependencies of the dependency
dependency_tree_as_keg_names(of_dependency, false, args: args).each do |d|
# Only update those we visited and think we can remove
if wont_remove_because.has_key? d and can_remove(wont_remove_because[d])
wont_remove_because[d] << of_dependency
revisit_neighbors(d, del_formula, dep_set, wont_remove_because, args: args)
end
end
end
# Walk the tree and decide which ones are safe to remove
def build_tree(keg_name, ignored_kegs=[], args: )
# List used to save the status of all dependency packages
wont_remove_because = {}
ohai "Examining installed formulae required by #{keg_name}..."
show_wait_spinner{
# Convert the keg_name the user provided into homebrew formula
f = as_formula(keg_name)
# Get the complete list of dependencies and convert it to just keg names
dep_arr = dependency_tree_as_keg_names(keg_name, args: args)
dep_set = dep_arr.to_set
# For each possible dependency that we want to remove, check if anything
# uses it, which is not also in the list of dependencies. That means it
# isn't safe to remove.
dep_arr.each do |dep|
# Set the progress text for spinner thread
set_spinner_progress " #{wont_remove_because.size} / #{dep_arr.length} "
# Save the list of formulae that use this keg and aren't in the tree
# of dependencies to be removed
wont_remove_because[dep] = still_used_by(dep, f, dep_set, args: args)
# Allow user to keep dependencies that aren't used anymore by saying
# something phony uses it
if ignored_kegs.include?(dep)
if wont_remove_because[dep].empty?
wont_remove_because[dep] << "ignored"
end
end
# Revisit any formulae already visited and related to this dependency
# because at the time they didn't have this new information
if cant_remove(wont_remove_because[dep])
# This dependency can't be removed. Users and dependencies need to be reconsidered.
revisit_neighbors(dep, f, dep_set, wont_remove_because, args: args)
end
set_spinner_progress " #{wont_remove_because.size} / #{dep_arr.length} "
end
}
print "\n"
return wont_remove_because
end
def order_to_be_removed_v2(start_from, wont_remove_because, args:)
# Maintain stuff we delete
deleted_formulae = [start_from]
# Stuff we *should* be able to delete, albeit using faulty logic from before
maybe_dependencies_to_delete = removable_in_tree(wont_remove_because).map { |d,_| d }
# Keep deleting things that we *think* we can delete. As we go through the list,
# more things should become deletable. But when no new things become deletable,
# then we are done. This is hacky logic v2
last_size = 0
while maybe_dependencies_to_delete.size != last_size
last_size = maybe_dependencies_to_delete.size
maybe_dependencies_to_delete.each do |dep|
_used_by = uses(dep, false, args: args).to_set.subtract(deleted_formulae.to_set)
# puts "Deleted formulae are #{deleted_formulae.inspect()}"
# puts "#{dep} is used by #{_used_by.inspect()}"
if _used_by.size == 0
deleted_formulae << dep
maybe_dependencies_to_delete.delete dep
end
end
end
return deleted_formulae, maybe_dependencies_to_delete
end
def rmtree(keg_name, force=false, ignored_kegs=[], args:)
# Does anything use keg such that we can't remove it?
if !force
keg_used_by = uses(keg_name, false, args: args)
if !keg_used_by.empty?
puts "#{keg_name} can't be removed because other formula depend on it:"
puts keg_used_by.join(", ")
return
end
end
# Check if the formula is installed (outdated implies installed)
unless as_formula(keg_name).any_version_installed? || as_formula(keg_name).outdated?
onoe "#{keg_name} is not currently installed"
return
end
# Dependency list of what can be removed, and what can't, and why
wont_remove_because = build_tree(keg_name, ignored_kegs, args: args)
kegs_to_delete_in_order, maybe_dependencies_to_delete = order_to_be_removed_v2(keg_name, wont_remove_because,
args: args)
# Dry run print out more information on what will happen
if @dry_run
# describe_build_tree(wont_remove_because)
puts ""
puts "Can safely be removed"
puts "----------------------"
kegs_to_delete_in_order.each do |k|
puts k
end
describe_build_tree_wont_remove(wont_remove_because)
if @dry_run
maybe_dependencies_to_delete.each do |dep|
_used_by = uses(dep, false, args: args).to_set.subtract(kegs_to_delete_in_order)
puts "#{dep} is used by #{_used_by.to_a.join(', ')}"
end
end
puts ""
puts "Order of operations"
puts "-------------------"
puts kegs_to_delete_in_order
else
# Confirm with user packages that can and will be removed
# describe_build_tree_will_remove(wont_remove_because)
puts ""
puts "Can safely be removed"
puts "----------------------"
kegs_to_delete_in_order.each do |k|
puts k
end
should_proceed_or_quit("Proceed?")
ohai "Cleaning up packages safe to remove"
end
# Remove packages
# remove_keg(keg_name, @dry_run)
#removable_in_tree(wont_remove_because).map { |d,_| remove_keg(d, @dry_run) }
kegs_to_delete_in_order.each { |d| remove_keg(d, @dry_run) }
end
def rmtree_args
Homebrew::CLI::Parser.new do
usage_banner <<~EOS
`rmtree` [<options>] [<formula>]
Remove a formula entirely, including all of its dependencies, unless of course,
they are used by another formula.
Warning:
Not all formulae declare their dependencies and therefore this command may end
up removing something you still need. It should be used with caution.
EOS
switch "--quiet",
description: "Hide output."
switch "-n", "--dry-run",
description: "See what would be removed without actually removing anything."
switch "--force",
description: "Force the removal of <formula> even if other formulae depend on it. " +
"You can override the dependency check for the top-level formula you " +
"are trying to remove. \nFor example, if you try to remove 'ruby', you most likely will " +
"not be able to do this because other fomulae specify this as a dependency. This " +
"option will enable you to remove 'ruby'. This will NOT bypass dependency checks for the " +
"formula's children. If 'ruby' depends on 'git', then 'git' will still not be removed. Sorry."
comma_array "--ignore=",
description: "Ignore some dependencies from being removed. Specify multiple values separated by a comma."
end
end
def main
args = rmtree_args.parse
force = args.force?
ignored_kegs = []
ignored_kegs.push(*args.ignore)
rm_kegs = args.named
quiet = args.quiet?
@dry_run = args.dry_run?
raise KegUnspecifiedError if args.no_named?
# Turn off output if 'quiet' is specified
if quiet
puts_off
end
if @dry_run
puts "This is a dry-run, nothing will be deleted"
end
# Convert ignored kegs into full names
ignored_kegs.map! { |k| as_formula(k).full_name }
rm_kegs.each { |keg_name| rmtree keg_name, force, ignored_kegs, args: args }
end
end
BrewRmtree.main
exit 0
|
# frozen_string_literal: false
require "utils/github"
require "utils/formatter"
require_relative "lib/capture"
require_relative "lib/diffable"
require_relative "lib/travis"
module Hbc
class CLI
class Ci < AbstractCommand
def run
unless ENV.key?("TRAVIS")
raise CaskError, "This command isn’t meant to be run locally."
end
unless tap
raise CaskError, "This command must be run from inside a tap directory."
end
ruby_files_in_wrong_directory = modified_ruby_files - (modified_cask_files + modified_command_files)
unless ruby_files_in_wrong_directory.empty?
raise CaskError, "Casks are in the wrong directory:\n" +
ruby_files_in_wrong_directory.join("\n")
end
if modified_cask_files.count > 1 && tap.name != "homebrew/cask-fonts"
raise CaskError, "More than one cask modified; please submit a pull request for each cask separately."
end
overall_success = true
modified_cask_files.each do |path|
cask = CaskLoader.load(path)
overall_success &= step "brew cask audit #{cask.token}", "audit" do
Auditor.audit(cask, audit_download: true,
check_token_conflicts: added_cask_files.include?(path),
commit_range: ENV["TRAVIS_COMMIT_RANGE"])
end
overall_success &= step "brew cask style #{cask.token}", "style" do
Style.run(path)
end
was_installed = cask.installed?
cask_dependencies = CaskDependencies.new(cask).reject(&:installed?)
checks = {
installed_apps: Diffable.new do
sleep(5) # Allow `mdfind` to refresh.
system_command!("/usr/bin/mdfind", args: ["-onlyin", "/", "kMDItemContentType == com.apple.application-bundle"], print_stderr: false)
.stdout
.split("\n")
end,
installed_kexts: Diffable.new do
system_command!("/usr/sbin/kextstat", args: ["-kl"], print_stderr: false)
.stdout
.lines
.map { |l| l.match(/^.{52}([^\s]+)/)[1] }
.grep_v(/^com\.apple\./)
end,
installed_launchjobs: Diffable.new do
format_launchjob = lambda { |file|
name = file.basename(".plist").to_s
label = Plist.parse_xml(File.read(file))["Label"]
(name == label) ? name : "#{name} (#{label})"
}
[
"~/Library/LaunchAgents",
"~/Library/LaunchDaemons",
"/Library/LaunchAgents",
"/Library/LaunchDaemons",
].map { |p| Pathname(p).expand_path }
.select(&:directory?)
.flat_map(&:children)
.select { |child| child.extname == ".plist" }
.map(&format_launchjob)
end,
loaded_launchjobs: Diffable.new do
launchctl = lambda do |sudo|
system_command!("/bin/launchctl", args: ["list"], print_stderr: false, sudo: sudo)
.stdout
.lines.drop(1)
end
[false, true]
.flat_map(&launchctl)
.map { |l| l.split(/\s+/)[2] }
.grep_v(/^com\.apple\./)
end,
installed_pkgs: Diffable.new do
Pathname("/var/db/receipts")
.children
.grep(/\.plist$/)
.map(&:basename)
end,
}
overall_success &= step "brew cask install #{cask.token}", "install" do
Installer.new(cask, force: true).uninstall if was_installed
checks.values.each(&:before)
Installer.new(cask, verbose: true).install
end
overall_success &= step "brew cask uninstall #{cask.token}", "uninstall" do
success = begin
Installer.new(cask, verbose: true).uninstall
true
rescue => e
$stderr.puts e.message
$stderr.puts e.backtrace
false
ensure
cask_dependencies.each do |c|
Installer.new(c, verbose: true).uninstall if c.installed?
end
end
checks.each do |name, check|
check.after
next unless check.changed?
success = false
message = case name
when :installed_pkgs
"Some packages were not uninstalled."
when :loaded_launchjobs
"Some launch jobs were not unloaded."
when :installed_launchjobs
"Some launch jobs were not uninstalled."
when :installed_kexts
"Some kernel extensions were not uninstalled."
when :installed_apps
"Some applications were not uninstalled."
end
$stderr.puts Formatter.error(message, label: "Error")
$stderr.puts check.diff_lines.join("\n")
end
success
end
end
if overall_success
puts Formatter.success("Build finished successfully.", label: "Success")
return
end
raise CaskError, "Build failed."
end
private
def step(name, travis_id)
success = false
output = nil
Travis.fold travis_id do
print "#{Tty.bold}#{Tty.yellow}#{name}#{Tty.reset} "
success, output = capture do
begin
yield != false
rescue => e
$stderr.puts e.message
false
end
end
if success
puts Formatter.success("✔")
puts output
else
puts Formatter.error("✘")
end
end
puts output unless success
success
ensure
$stdout.flush
$stderr.flush
end
def tap
@tap ||= if ENV.key?("TRAVIS_REPO_SLUG")
Tap.fetch(ENV["TRAVIS_REPO_SLUG"])
else
Tap.from_path(Dir.pwd)
end
end
def modified_files
@modified_files ||= system_command!(
"git", args: ["diff", "--name-only", "--diff-filter=AMR", ENV["TRAVIS_COMMIT_RANGE"]]
).stdout.split("\n").map { |path| Pathname(path) }
end
def added_files
@added_files ||= system_command!(
"git", args: ["diff", "--name-only", "--diff-filter=A", ENV["TRAVIS_COMMIT_RANGE"]]
).stdout.split("\n").map { |path| Pathname(path) }
end
def modified_ruby_files
@modified_ruby_files ||= modified_files.select { |path| path.extname == ".rb" }
end
def modified_command_files
@modified_command_files ||= modified_files.select { |path| tap.command_file?(path) || path.ascend.to_a.last.to_s == "cmd" }
end
def modified_cask_files
@modified_cask_files ||= modified_files.select { |path| tap.cask_file?(path) }
end
def added_cask_files
@added_cask_files ||= added_files.select { |path| tap.cask_file?(path) }
end
end
end
end
Don’t use `mdfind`.
# frozen_string_literal: false
require "utils/github"
require "utils/formatter"
require_relative "lib/capture"
require_relative "lib/diffable"
require_relative "lib/travis"
module Hbc
class CLI
class Ci < AbstractCommand
def run
unless ENV.key?("TRAVIS")
raise CaskError, "This command isn’t meant to be run locally."
end
unless tap
raise CaskError, "This command must be run from inside a tap directory."
end
ruby_files_in_wrong_directory = modified_ruby_files - (modified_cask_files + modified_command_files)
unless ruby_files_in_wrong_directory.empty?
raise CaskError, "Casks are in the wrong directory:\n" +
ruby_files_in_wrong_directory.join("\n")
end
if modified_cask_files.count > 1 && tap.name != "homebrew/cask-fonts"
raise CaskError, "More than one cask modified; please submit a pull request for each cask separately."
end
overall_success = true
modified_cask_files.each do |path|
cask = CaskLoader.load(path)
overall_success &= step "brew cask audit #{cask.token}", "audit" do
Auditor.audit(cask, audit_download: true,
check_token_conflicts: added_cask_files.include?(path),
commit_range: ENV["TRAVIS_COMMIT_RANGE"])
end
overall_success &= step "brew cask style #{cask.token}", "style" do
Style.run(path)
end
was_installed = cask.installed?
cask_dependencies = CaskDependencies.new(cask).reject(&:installed?)
checks = {
installed_apps: Diffable.new do
["/Applications", File.expand_path("~/Applications")]
.flat_map { |dir| Dir["#{dir}/**/*.app"] }
end,
installed_kexts: Diffable.new do
system_command!("/usr/sbin/kextstat", args: ["-kl"], print_stderr: false)
.stdout
.lines
.map { |l| l.match(/^.{52}([^\s]+)/)[1] }
.grep_v(/^com\.apple\./)
end,
installed_launchjobs: Diffable.new do
format_launchjob = lambda { |file|
name = file.basename(".plist").to_s
label = Plist.parse_xml(File.read(file))["Label"]
(name == label) ? name : "#{name} (#{label})"
}
[
"~/Library/LaunchAgents",
"~/Library/LaunchDaemons",
"/Library/LaunchAgents",
"/Library/LaunchDaemons",
].map { |p| Pathname(p).expand_path }
.select(&:directory?)
.flat_map(&:children)
.select { |child| child.extname == ".plist" }
.map(&format_launchjob)
end,
loaded_launchjobs: Diffable.new do
launchctl = lambda do |sudo|
system_command!("/bin/launchctl", args: ["list"], print_stderr: false, sudo: sudo)
.stdout
.lines.drop(1)
end
[false, true]
.flat_map(&launchctl)
.map { |l| l.split(/\s+/)[2] }
.grep_v(/^com\.apple\./)
end,
installed_pkgs: Diffable.new do
Pathname("/var/db/receipts")
.children
.grep(/\.plist$/)
.map(&:basename)
end,
}
overall_success &= step "brew cask install #{cask.token}", "install" do
Installer.new(cask, force: true).uninstall if was_installed
checks.values.each(&:before)
Installer.new(cask, verbose: true).install
end
overall_success &= step "brew cask uninstall #{cask.token}", "uninstall" do
success = begin
Installer.new(cask, verbose: true).uninstall
true
rescue => e
$stderr.puts e.message
$stderr.puts e.backtrace
false
ensure
cask_dependencies.each do |c|
Installer.new(c, verbose: true).uninstall if c.installed?
end
end
checks.each do |name, check|
check.after
next unless check.changed?
success = false
message = case name
when :installed_pkgs
"Some packages were not uninstalled."
when :loaded_launchjobs
"Some launch jobs were not unloaded."
when :installed_launchjobs
"Some launch jobs were not uninstalled."
when :installed_kexts
"Some kernel extensions were not uninstalled."
when :installed_apps
"Some applications were not uninstalled."
end
$stderr.puts Formatter.error(message, label: "Error")
$stderr.puts check.diff_lines.join("\n")
end
success
end
end
if overall_success
puts Formatter.success("Build finished successfully.", label: "Success")
return
end
raise CaskError, "Build failed."
end
private
def step(name, travis_id)
success = false
output = nil
Travis.fold travis_id do
print "#{Tty.bold}#{Tty.yellow}#{name}#{Tty.reset} "
success, output = capture do
begin
yield != false
rescue => e
$stderr.puts e.message
false
end
end
if success
puts Formatter.success("✔")
puts output
else
puts Formatter.error("✘")
end
end
puts output unless success
success
ensure
$stdout.flush
$stderr.flush
end
def tap
@tap ||= if ENV.key?("TRAVIS_REPO_SLUG")
Tap.fetch(ENV["TRAVIS_REPO_SLUG"])
else
Tap.from_path(Dir.pwd)
end
end
def modified_files
@modified_files ||= system_command!(
"git", args: ["diff", "--name-only", "--diff-filter=AMR", ENV["TRAVIS_COMMIT_RANGE"]]
).stdout.split("\n").map { |path| Pathname(path) }
end
def added_files
@added_files ||= system_command!(
"git", args: ["diff", "--name-only", "--diff-filter=A", ENV["TRAVIS_COMMIT_RANGE"]]
).stdout.split("\n").map { |path| Pathname(path) }
end
def modified_ruby_files
@modified_ruby_files ||= modified_files.select { |path| path.extname == ".rb" }
end
def modified_command_files
@modified_command_files ||= modified_files.select { |path| tap.command_file?(path) || path.ascend.to_a.last.to_s == "cmd" }
end
def modified_cask_files
@modified_cask_files ||= modified_files.select { |path| tap.cask_file?(path) }
end
def added_cask_files
@added_cask_files ||= added_files.select { |path| tap.cask_file?(path) }
end
end
end
end
|
# Configuration values with defaults
# TODO: Make this return different values depending on the current rails environment
module AlaveteliConfiguration
mattr_accessor :config
if !const_defined?(:DEFAULTS)
DEFAULTS = {
:ADMIN_PASSWORD => '',
:ADMIN_USERNAME => '',
:ALLOW_BATCH_REQUESTS => false,
:AUTHORITY_MUST_RESPOND => true,
:AVAILABLE_LOCALES => '',
:BLACKHOLE_PREFIX => 'do-not-reply-to-this-address',
:BLOG_FEED => '',
:CACHE_FRAGMENTS => true,
:CONTACT_EMAIL => 'contact@localhost',
:CONTACT_NAME => 'Alaveteli',
:COOKIE_STORE_SESSION_SECRET => 'this default is insecure as code is open source, please override for live sites in config/general; this will do for local development',
:DEBUG_RECORD_MEMORY => false,
:DEFAULT_LOCALE => '',
:DISABLE_EMERGENCY_USER => false,
:DOMAIN => 'localhost:3000',
:DONATION_URL => '',
:EXCEPTION_NOTIFICATIONS_FROM => '',
:EXCEPTION_NOTIFICATIONS_TO => '',
:FORCE_REGISTRATION_ON_NEW_REQUEST => false,
:FORCE_SSL => true,
:FORWARD_NONBOUNCE_RESPONSES_TO => 'user-support@localhost',
:FRONTPAGE_PUBLICBODY_EXAMPLES => '',
:GA_CODE => '',
:GAZE_URL => '',
:HTML_TO_PDF_COMMAND => '',
:INCLUDE_DEFAULT_LOCALE_IN_URLS => true,
:INCOMING_EMAIL_DOMAIN => 'localhost',
:INCOMING_EMAIL_PREFIX => 'foi+',
:INCOMING_EMAIL_SECRET => 'dummysecret',
:ISO_COUNTRY_CODE => 'GB',
:MINIMUM_REQUESTS_FOR_STATISTICS => 100,
:MAX_REQUESTS_PER_USER_PER_DAY => 6,
:MTA_LOG_PATH => '/var/log/exim4/exim-mainlog-*',
:MTA_LOG_TYPE => 'exim',
:NEW_RESPONSE_REMINDER_AFTER_DAYS => [3, 10, 24],
:OVERRIDE_ALL_PUBLIC_BODY_REQUEST_EMAILS => '',
:PUBLIC_BODY_STATISTICS_PAGE => false,
:PUBLIC_BODY_LIST_FALLBACK_TO_DEFAULT_LOCALE => false,
:RAW_EMAILS_LOCATION => 'files/raw_emails',
:READ_ONLY => '',
:RECAPTCHA_PRIVATE_KEY => 'x',
:RECAPTCHA_PUBLIC_KEY => 'x',
:REPLY_LATE_AFTER_DAYS => 20,
:REPLY_VERY_LATE_AFTER_DAYS => 40,
:RESPONSIVE_STYLING => true,
:SITE_NAME => 'Alaveteli',
:SKIP_ADMIN_AUTH => false,
:SPECIAL_REPLY_VERY_LATE_AFTER_DAYS => 60,
:THEME_BRANCH => false,
:THEME_URL => "",
:THEME_URLS => [],
:TIME_ZONE => "UTC",
:TRACK_SENDER_EMAIL => 'contact@localhost',
:TRACK_SENDER_NAME => 'Alaveteli',
:TWITTER_USERNAME => '',
:TWITTER_WIDGET_ID => false,
:USE_DEFAULT_BROWSER_LANGUAGE => true,
:USE_GHOSTSCRIPT_COMPRESSION => false,
:USE_MAILCATCHER_IN_DEVELOPMENT => true,
:UTILITY_SEARCH_PATH => ["/usr/bin", "/usr/local/bin"],
:VARNISH_HOST => '',
:WORKING_OR_CALENDAR_DAYS => 'working',
:MAILER_DELIVERY_METHOD => 'sendmail',
:MAILER_ADDRESS => '',
:MAILER_PORT => 587,
:MAILER_DOMAIN => '',
:MAILER_USER_NAME => '',
:MAILER_PASSWORD => '',
:MAILER_AUTHENTICATION => 'plain',
:MAILER_ENABLE_STARTTLS_AUTO => true
}
end
def self.method_missing(name)
self.config ||= YAML.load(ERB.new(File.read(Rails.root.join 'config', 'general.yml')).result)
key = name.to_s.upcase
return super unless DEFAULTS.has_key?(key.to_sym)
config.fetch(key, DEFAULTS[key.to_sym])
end
end
Updated to use PRODUCTION
# Configuration values with defaults
# TODO: Make this return different values depending on the current rails environment
module AlaveteliConfiguration
mattr_accessor :config
if !const_defined?(:DEFAULTS)
DEFAULTS = {
:ADMIN_PASSWORD => '',
:ADMIN_USERNAME => '',
:ALLOW_BATCH_REQUESTS => false,
:AUTHORITY_MUST_RESPOND => true,
:AVAILABLE_LOCALES => '',
:BLACKHOLE_PREFIX => 'do-not-reply-to-this-address',
:BLOG_FEED => '',
:CACHE_FRAGMENTS => true,
:CONTACT_EMAIL => 'contact@localhost',
:CONTACT_NAME => 'Alaveteli',
:COOKIE_STORE_SESSION_SECRET => 'this default is insecure as code is open source, please override for live sites in config/general; this will do for local development',
:DEBUG_RECORD_MEMORY => false,
:DEFAULT_LOCALE => '',
:DISABLE_EMERGENCY_USER => false,
:DOMAIN => 'localhost:3000',
:DONATION_URL => '',
:EXCEPTION_NOTIFICATIONS_FROM => '',
:EXCEPTION_NOTIFICATIONS_TO => '',
:FORCE_REGISTRATION_ON_NEW_REQUEST => false,
:FORCE_SSL => true,
:FORWARD_NONBOUNCE_RESPONSES_TO => 'user-support@localhost',
:FRONTPAGE_PUBLICBODY_EXAMPLES => '',
:GA_CODE => '',
:GAZE_URL => '',
:HTML_TO_PDF_COMMAND => '',
:INCLUDE_DEFAULT_LOCALE_IN_URLS => true,
:INCOMING_EMAIL_DOMAIN => 'localhost',
:INCOMING_EMAIL_PREFIX => 'foi+',
:INCOMING_EMAIL_SECRET => 'dummysecret',
:ISO_COUNTRY_CODE => 'GB',
:MINIMUM_REQUESTS_FOR_STATISTICS => 100,
:MAX_REQUESTS_PER_USER_PER_DAY => 6,
:MTA_LOG_PATH => '/var/log/exim4/exim-mainlog-*',
:MTA_LOG_TYPE => 'exim',
:NEW_RESPONSE_REMINDER_AFTER_DAYS => [3, 10, 24],
:OVERRIDE_ALL_PUBLIC_BODY_REQUEST_EMAILS => '',
:PUBLIC_BODY_STATISTICS_PAGE => false,
:PUBLIC_BODY_LIST_FALLBACK_TO_DEFAULT_LOCALE => false,
:RAW_EMAILS_LOCATION => 'files/raw_emails',
:READ_ONLY => '',
:RECAPTCHA_PRIVATE_KEY => 'x',
:RECAPTCHA_PUBLIC_KEY => 'x',
:REPLY_LATE_AFTER_DAYS => 20,
:REPLY_VERY_LATE_AFTER_DAYS => 40,
:RESPONSIVE_STYLING => true,
:SITE_NAME => 'Alaveteli',
:SKIP_ADMIN_AUTH => false,
:SPECIAL_REPLY_VERY_LATE_AFTER_DAYS => 60,
:THEME_BRANCH => false,
:THEME_URL => "",
:THEME_URLS => [],
:TIME_ZONE => "UTC",
:TRACK_SENDER_EMAIL => 'contact@localhost',
:TRACK_SENDER_NAME => 'Alaveteli',
:TWITTER_USERNAME => '',
:TWITTER_WIDGET_ID => false,
:USE_DEFAULT_BROWSER_LANGUAGE => true,
:USE_GHOSTSCRIPT_COMPRESSION => false,
:USE_MAILCATCHER_IN_DEVELOPMENT => true,
:UTILITY_SEARCH_PATH => ["/usr/bin", "/usr/local/bin"],
:VARNISH_HOST => '',
:WORKING_OR_CALENDAR_DAYS => 'working',
:PRODUCTION_MAILER_DELIVERY_METHOD => 'sendmail',
:MAILER_ADDRESS => '',
:MAILER_PORT => 587,
:MAILER_DOMAIN => '',
:MAILER_USER_NAME => '',
:MAILER_PASSWORD => '',
:MAILER_AUTHENTICATION => 'plain',
:MAILER_ENABLE_STARTTLS_AUTO => true
}
end
def self.method_missing(name)
self.config ||= YAML.load(ERB.new(File.read(Rails.root.join 'config', 'general.yml')).result)
key = name.to_s.upcase
return super unless DEFAULTS.has_key?(key.to_sym)
config.fetch(key, DEFAULTS[key.to_sym])
end
end
|
require 'fileutils'
MetricFu.reporting_require { 'templates/awesome/awesome_template' }
module MetricFu
# The @configuration class variable holds a global type configuration
# object for any parts of the system to use.
# TODO Configuration should probably be a singleton class
def self.configuration
@configuration ||= Configuration.new
end
# = Configuration
#
# The Configuration class, as it sounds, provides methods for
# configuring the behaviour of MetricFu.
#
# == Customization for Rails
#
# The Configuration class checks for the presence of a
# 'config/environment.rb' file. If the file is present, it assumes
# it is running in a Rails project. If it is, it will:
#
# * Add 'app' to the @code_dirs directory to include the
# code in the app directory in the processing
# * Add :stats and :rails_best_practices to the list of metrics to run
#
# == Customization for CruiseControl.rb
#
# The Configuration class checks for the presence of a
# 'CC_BUILD_ARTIFACTS' environment variable. If it's found
# it will change the default output directory from the default
# "tmp/metric_fu to the directory represented by 'CC_BUILD_ARTIFACTS'
#
# == Metric Configuration
#
# Each metric can be configured by e.g. config.churn, config.flog, config.saikuro
class Configuration
def initialize #:nodoc:#
reset
end
def verbose
MfDebugger::Logger.debug_on
end
def verbose=(toggle)
MfDebugger::Logger.debug_on = toggle
end
def reset
set_directories
configure_template
add_promiscuous_instance_variable(:metrics, [])
add_promiscuous_instance_variable(:graphs, [])
add_promiscuous_instance_variable(:graph_engines, [])
add_promiscuous_method(:graph_engine)
# TODO this needs to go
# we should use attr_accessors instead
# TODO review if these code is functionally duplicated in the
# base generator initialize
add_attr_accessors_to_self
add_class_methods_to_metric_fu
end
# This allows us to have a nice syntax like:
#
# MetricFu.run do |config|
# config.base_directory = 'tmp/metric_fu'
# end
#
# See the README for more information on configuration options.
def self.run
yield MetricFu.configuration
end
attr_accessor :metrics
# e.g. :churn
def add_metric(metric)
add_promiscuous_method(metric)
self.metrics = (metrics << metric).uniq
end
# e.g. :reek
def add_graph(metric)
add_promiscuous_method(metric)
self.graphs = (graphs << metric).uniq
end
# e.g. :reek, {}
def configure_metric(metric, metric_configuration)
add_promiscuous_instance_variable(metric, metric_configuration)
end
# e.g. :bluff
def add_graph_engine(graph_engine)
add_promiscuous_method(graph_engine)
self.graph_engines = (graph_engines << graph_engine).uniq
end
# e.g. :bluff
def configure_graph_engine(graph_engine)
add_promiscuous_instance_variable(:graph_engine, graph_engine)
end
# Perform a simple check to try and guess if we're running
# against a rails app.
#
# TODO This should probably be made a bit more robust.
def rails?
add_promiscuous_instance_variable(:rails, File.exist?("config/environment.rb"))
end
def is_cruise_control_rb?
!!ENV['CC_BUILD_ARTIFACTS']
end
def platform #:nodoc:
return RUBY_PLATFORM
end
def self.ruby_strangely_makes_accessors_private?
!!(RUBY_VERSION =~ /1.9.2/)
end
protected unless ruby_strangely_makes_accessors_private?
def add_promiscuous_instance_variable(name,value)
instance_variable_set("@#{name}", value)
add_promiscuous_method(name)
value
end
def add_promiscuous_method(method_name)
add_promiscuous_class_method_to_metric_fu(method_name)
add_accessor_to_config(method_name)
end
def add_promiscuous_class_method_to_metric_fu(method_name)
metric_fu_method = <<-EOF
def self.#{method_name}
configuration.send(:#{method_name})
end
EOF
MetricFu.module_eval(metric_fu_method)
end
def add_accessor_to_config(method_name)
self.class.send(:attr_accessor, method_name)
end
# Searches through the instance variables of the class and
# creates a class method on the MetricFu module to read the value
# of the instance variable from the Configuration class.
def add_class_methods_to_metric_fu
instance_variables.each do |name|
method_name = name[1..-1].to_sym
add_promiscuous_class_method_to_metric_fu(method_name)
end
end
# Searches through the instance variables of the class and creates
# an attribute accessor on this instance of the Configuration
# class for each instance variable.
def add_attr_accessors_to_self
instance_variables.each do |name|
method_name = name[1..-1].to_sym
add_accessor_to_config(method_name)
end
end
private
def configure_template
add_promiscuous_instance_variable(:template_class, AwesomeTemplate)
add_promiscuous_instance_variable(:link_prefix, nil)
add_promiscuous_instance_variable(:darwin_txmt_protocol_no_thanks, true)
# turning off syntax_highlighting may avoid some UTF-8 issues
add_promiscuous_instance_variable(:syntax_highlighting, true)
end
def set_directories
add_promiscuous_instance_variable(:base_directory,MetricFu.artifact_dir)
add_promiscuous_instance_variable(:scratch_directory,MetricFu.scratch_dir)
add_promiscuous_instance_variable(:output_directory,MetricFu.output_dir)
add_promiscuous_instance_variable(:data_directory,MetricFu.data_dir)
# due to behavior differences between ruby 1.8.7 and 1.9.3
# this is good enough for now
create_directories [base_directory, scratch_directory, output_directory]
add_promiscuous_instance_variable(:metric_fu_root_directory,MetricFu.root_dir)
add_promiscuous_instance_variable(:template_directory,
File.join(metric_fu_root_directory,
'lib', 'templates'))
add_promiscuous_instance_variable(:file_globs_to_ignore,[])
set_code_dirs
end
def create_directories(*dirs)
Array(*dirs).each do |dir|
FileUtils.mkdir_p dir
end
end
# Add the 'app' directory if we're running within rails.
def set_code_dirs
if rails?
add_promiscuous_instance_variable(:code_dirs,['app', 'lib'])
else
add_promiscuous_instance_variable(:code_dirs,['lib'])
end
end
end
end
BF we no longer need the global ivar -> method converter
require 'fileutils'
MetricFu.reporting_require { 'templates/awesome/awesome_template' }
module MetricFu
# The @configuration class variable holds a global type configuration
# object for any parts of the system to use.
# TODO Configuration should probably be a singleton class
def self.configuration
@configuration ||= Configuration.new
end
# = Configuration
#
# The Configuration class, as it sounds, provides methods for
# configuring the behaviour of MetricFu.
#
# == Customization for Rails
#
# The Configuration class checks for the presence of a
# 'config/environment.rb' file. If the file is present, it assumes
# it is running in a Rails project. If it is, it will:
#
# * Add 'app' to the @code_dirs directory to include the
# code in the app directory in the processing
# * Add :stats and :rails_best_practices to the list of metrics to run
#
# == Customization for CruiseControl.rb
#
# The Configuration class checks for the presence of a
# 'CC_BUILD_ARTIFACTS' environment variable. If it's found
# it will change the default output directory from the default
# "tmp/metric_fu to the directory represented by 'CC_BUILD_ARTIFACTS'
#
# == Metric Configuration
#
# Each metric can be configured by e.g. config.churn, config.flog, config.saikuro
class Configuration
def initialize #:nodoc:#
reset
end
def verbose
MfDebugger::Logger.debug_on
end
def verbose=(toggle)
MfDebugger::Logger.debug_on = toggle
end
# TODO review if these code is functionally duplicated in the
# base generator initialize
def reset
set_directories
configure_template
add_promiscuous_instance_variable(:metrics, [])
add_promiscuous_instance_variable(:graphs, [])
add_promiscuous_instance_variable(:graph_engines, [])
add_promiscuous_method(:graph_engine)
end
# This allows us to have a nice syntax like:
#
# MetricFu.run do |config|
# config.base_directory = 'tmp/metric_fu'
# end
#
# See the README for more information on configuration options.
def self.run
yield MetricFu.configuration
end
attr_accessor :metrics
# e.g. :churn
def add_metric(metric)
add_promiscuous_method(metric)
self.metrics = (metrics << metric).uniq
end
# e.g. :reek
def add_graph(metric)
add_promiscuous_method(metric)
self.graphs = (graphs << metric).uniq
end
# e.g. :reek, {}
def configure_metric(metric, metric_configuration)
add_promiscuous_instance_variable(metric, metric_configuration)
end
# e.g. :bluff
def add_graph_engine(graph_engine)
add_promiscuous_method(graph_engine)
self.graph_engines = (graph_engines << graph_engine).uniq
end
# e.g. :bluff
def configure_graph_engine(graph_engine)
add_promiscuous_instance_variable(:graph_engine, graph_engine)
end
# Perform a simple check to try and guess if we're running
# against a rails app.
#
# TODO This should probably be made a bit more robust.
def rails?
add_promiscuous_instance_variable(:rails, File.exist?("config/environment.rb"))
end
def is_cruise_control_rb?
!!ENV['CC_BUILD_ARTIFACTS']
end
def platform #:nodoc:
return RUBY_PLATFORM
end
def self.ruby_strangely_makes_accessors_private?
!!(RUBY_VERSION =~ /1.9.2/)
end
protected unless ruby_strangely_makes_accessors_private?
def add_promiscuous_instance_variable(name,value)
instance_variable_set("@#{name}", value)
add_promiscuous_method(name)
value
end
def add_promiscuous_method(method_name)
add_promiscuous_class_method_to_metric_fu(method_name)
add_accessor_to_config(method_name)
end
def add_promiscuous_class_method_to_metric_fu(method_name)
metric_fu_method = <<-EOF
def self.#{method_name}
configuration.send(:#{method_name})
end
EOF
MetricFu.module_eval(metric_fu_method)
end
def add_accessor_to_config(method_name)
self.class.send(:attr_accessor, method_name)
end
private
def configure_template
add_promiscuous_instance_variable(:template_class, AwesomeTemplate)
add_promiscuous_instance_variable(:link_prefix, nil)
add_promiscuous_instance_variable(:darwin_txmt_protocol_no_thanks, true)
# turning off syntax_highlighting may avoid some UTF-8 issues
add_promiscuous_instance_variable(:syntax_highlighting, true)
end
def set_directories
add_promiscuous_instance_variable(:base_directory,MetricFu.artifact_dir)
add_promiscuous_instance_variable(:scratch_directory,MetricFu.scratch_dir)
add_promiscuous_instance_variable(:output_directory,MetricFu.output_dir)
add_promiscuous_instance_variable(:data_directory,MetricFu.data_dir)
# due to behavior differences between ruby 1.8.7 and 1.9.3
# this is good enough for now
create_directories [base_directory, scratch_directory, output_directory]
add_promiscuous_instance_variable(:metric_fu_root_directory,MetricFu.root_dir)
add_promiscuous_instance_variable(:template_directory,
File.join(metric_fu_root_directory,
'lib', 'templates'))
add_promiscuous_instance_variable(:file_globs_to_ignore,[])
set_code_dirs
end
def create_directories(*dirs)
Array(*dirs).each do |dir|
FileUtils.mkdir_p dir
end
end
# Add the 'app' directory if we're running within rails.
def set_code_dirs
if rails?
add_promiscuous_instance_variable(:code_dirs,['app', 'lib'])
else
add_promiscuous_instance_variable(:code_dirs,['lib'])
end
end
end
end
|
class Item# < ActiveRecord::Base
extend ActiveModel::Naming
include ActiveModel::AttributeMethods
require 'rubygems'
require 'rest_client'
OPEN_CALAIS_URI = 'http://www.opencalais.org/Entities#'
WIKI_META_URI = 'http://www.wikimeta.org/Entities#'
INSEE_GEO_URI = 'http://rdf.insee.fr/geo/'
RSS_URI = 'http://purl.org/rss/1.0/'
SVM_PLUGIN_URI = 'http://zone-project.org/model/plugins/Categorization_SVM#result'
TWITTER_MENTIONED_PLUGIN_URI = 'http://zone-project.org/model/plugins/twitter#mentioned'
TWITTER_HASHTAG_PLUGIN_URI = 'http://zone-project.org/model/plugins/twitter#hashtag'
LANG_URI = 'http://zone-project.org/model/plugins#lang'
attr_accessor :uri, :title, :props, :description, :date, :localURI, :similarity, :favorite, :filters
endpoint = Rails.application.config.virtuosoEndpoint
update_uri = Rails.application.config.virtuosoEndpoint+"-auth"
$repo = RDF::Virtuoso::Repository.new(endpoint,
:update_uri => update_uri,
:username => Rails.application.config.virtuosoLogin,
:password => Rails.application.config.virtuosoPassword,
:auth_method => 'digest')
def self.all(search = "",start=0,per_page=10)
sparqlFilter = search.generateSPARQLRequest
filtersIds = search.getOrFilters.map {|elem| "?filter#{elem.id}"}.join(',')
endpoint = Rails.application.config.virtuosoEndpoint
#if start > (10000 - per_page)
# return Array.new
#end
query = "PREFIX RSS: <http://purl.org/rss/1.0/>
SELECT * WHERE{
SELECT DISTINCT(?concept),?pubDateTime, ?title, CONCAT( #{filtersIds} ) AS ?filtersVals
FROM <#{ZoneOntology::GRAPH_ITEMS}>
FROM <#{ZoneOntology::GRAPH_SOURCES}>
WHERE {
?concept RSS:title ?title.
OPTIONAL { ?concept RSS:pubDateTime ?pubDateTime}.
#{sparqlFilter}
}} ORDER BY DESC(?pubDateTime) LIMIT #{per_page} OFFSET #{start}"
store = SPARQL::Client.new(endpoint)
items = Array.new
store.query(query).each do |item|
similarity = item.filtersVals.to_s.scan(/http/).count
items << Item.new(item.concept.to_s, item.title, similarity)
end
return {:result => items, :query => query}
end
def self.find(param,user)
endpoint = Rails.application.config.virtuosoEndpoint
require 'cgi'
require 'uri'
uri = CGI.unescape(URI.escape(CGI.unescape(param)))
uri = uri.gsub("%23","#")
query = "PREFIX RSS: <http://purl.org/rss/1.0/>
SELECT *
FROM <#{ZoneOntology::GRAPH_ITEMS}>
FROM <#{ZoneOntology::GRAPH_TAGS}>
WHERE { <#{uri}> ?prop ?value.
OPTIONAL{?value ?extraProp ?extraValue}";
query +="}"
store = SPARQL::Client.new(endpoint)
result = store.query(query)
if result.size == 0
return nil
end
puts query
params = Hash.new
result.each do |prop|
if params[prop.prop.to_s] == nil
params[prop.prop.to_s] = Hash.new
end
if (!prop.bound?(:extraProp))
if params[prop.prop.to_s][:value] == nil
params[prop.prop.to_s][:value] = Array.new
end
params[prop.prop.to_s][:value] << prop.value.to_s
else
if params[prop.prop.to_s][prop.value.to_s] == nil
params[prop.prop.to_s][prop.value.to_s] = Hash.new
end
params[prop.prop.to_s][prop.value.to_s][prop.extraProp.to_s] = prop.extraValue.to_s
end
end
puts params.to_json
item = Item.new(uri, params["http://purl.org/rss/1.0/title"][:value][0])
item.date = params["http://purl.org/rss/1.0/pubDate"][:value] if params["http://purl.org/rss/1.0/pubDate"] != nil
item.description = params["http://purl.org/rss/1.0/description"][:value] if params["http://purl.org/rss/1.0/description"] != nil
item.props = params
item.filters = Array.new
if params["http://zone-project.org/model/items#favorite"] != nil && user != nil
params["http://zone-project.org/model/items#favorite"].each do |fav|
if fav == "#{ZoneOntology::ZONE_USER}#{user.id}"
item.favorite = true
end
end
end
#add the filters
item.props.each do |key|
if (key[0] == "http://zone-project.org/model/items#favorite") || (key[0].start_with? "http://purl.org/rss") || (key[0].start_with? "http://zone-project.org/model/plugins/ExtractArticlesContent")
next
end
key[1].each do | filterKey, filterVal|
if filterKey.to_s == "value"
filterVal.each do |curVal|
if curVal == "true"
next
end
filter = SearchFilter.new(:value => curVal)
if curVal.start_with?("http")
filter.uri = curVal
filter.type = "http://www.w3.org/2004/02/skos/core#Concept"
end
filter.prop = key[0]
filter.item = item
item.filters << filter
end
else
filter = SearchFilter.new(:value => filterVal[ZoneOntology::RDF_LABEL])
filter.uri = filterKey
filter.prop = key[0]
filter.item = item
filter.type = filterVal[ZoneOntology::RDF_TYPE] if filterVal[ZoneOntology::RDF_TYPE] != nil
filter.abstract = filterVal[ZoneOntology::DBPEDIA_ABSTRACT] if filterVal[ZoneOntology::DBPEDIA_ABSTRACT] != nil
filter.thumb = filterVal[ZoneOntology::DBPEDIA_THUMB] if filterVal[ZoneOntology::DBPEDIA_THUMB] != nil
item.filters << filter
end
end
end
item.filters.sort! { |a,b|
if a.prop == "http://zone-project.org/model/plugins#lang"
-1
elsif b.prop == "http://zone-project.org/model/plugins#lang"
1
elsif a.type == nil
-1
elsif b.type == nil
1
else
a.type.downcase <=> b.type.downcase
end
}
return item
end
def initialize(uri,title, similarity=0)
@uri = uri
@title = title
@filters = Hash.new
@similarity = similarity
end
def to_param
require 'cgi'
CGI.escape(@uri.to_s)
end
def getUriHash
return Digest::SHA1.hexdigest(self.uri)
end
def getTypePicture
if uri.starts_with?('https://twitter.com') || uri.starts_with?('http://twitter.com')
return "/assets/twitter.png"
else
return "/assets/foregroundRSS.png"
end
end
def getTags
result = Array.new
self.props.each do |prop|
prop[1].each do |value|
filter = SearchFilter.new(:value => value)
if value.start_with?("http")
filter.uri = value
end
filter.prop = prop[0]
if(filter.prop.starts_with? WIKI_META_URI)
if(filter.uri == nil)
next
end
result << filter
elsif(filter.prop.starts_with? INSEE_GEO_URI)
result << filter
elsif (filter.prop.starts_with? TWITTER_MENTIONED_PLUGIN_URI)
filter.value = "@#{filter.value}"
result << filter
elsif (filter.prop.starts_with? TWITTER_HASHTAG_PLUGIN_URI)
filter.value = "##{filter.value}"
result << filter
end
end
end
return result
end
def addTag(tag)
graph = RDF::URI.new(ZoneOntology::GRAPH_ITEMS)
subject = RDF::URI.new(@uri)
if tag.start_with? "http"
tagNode = RDF::URI.new(tag)
else
tagNode = tag
end
$repo.insert(RDF::Virtuoso::Query.insert_data([subject,RDF::URI.new(ZoneOntology::PLUGIN_SOCIAL_ANNOTATION),tagNode]).graph(graph))
end
def deleteTag(tag)
graph = RDF::URI.new(ZoneOntology::GRAPH_ITEMS)
subject = RDF::URI.new(@uri)
self.props.each do |prop|
prop[1].each do |value|
if value == tag
if tag.start_with? "http"
tagNode = RDF::URI.new(tag)
else
tagNode = tag
end
$repo.delete(RDF::Virtuoso::Query.delete_data([subject, RDF::URI.new(prop[0]), tagNode]).graph(graph))
end
end
end
end
def getLang()
lang = self.props[LANG_URI]
if lang != nil
lang = lang[0]
if lang == "en"
return "gb"
end
end
return lang
end
end
fix unloadable items bug in watcher
class Item# < ActiveRecord::Base
extend ActiveModel::Naming
include ActiveModel::AttributeMethods
require 'rubygems'
require 'rest_client'
OPEN_CALAIS_URI = 'http://www.opencalais.org/Entities#'
WIKI_META_URI = 'http://www.wikimeta.org/Entities#'
INSEE_GEO_URI = 'http://rdf.insee.fr/geo/'
RSS_URI = 'http://purl.org/rss/1.0/'
SVM_PLUGIN_URI = 'http://zone-project.org/model/plugins/Categorization_SVM#result'
TWITTER_MENTIONED_PLUGIN_URI = 'http://zone-project.org/model/plugins/twitter#mentioned'
TWITTER_HASHTAG_PLUGIN_URI = 'http://zone-project.org/model/plugins/twitter#hashtag'
LANG_URI = 'http://zone-project.org/model/plugins#lang'
attr_accessor :uri, :title, :props, :description, :date, :localURI, :similarity, :favorite, :filters
endpoint = Rails.application.config.virtuosoEndpoint
update_uri = Rails.application.config.virtuosoEndpoint+"-auth"
$repo = RDF::Virtuoso::Repository.new(endpoint,
:update_uri => update_uri,
:username => Rails.application.config.virtuosoLogin,
:password => Rails.application.config.virtuosoPassword,
:auth_method => 'digest')
def self.all(search = "",start=0,per_page=10)
sparqlFilter = search.generateSPARQLRequest
filtersIds = search.getOrFilters.map {|elem| "?filter#{elem.id}"}.join(',')
endpoint = Rails.application.config.virtuosoEndpoint
#if start > (10000 - per_page)
# return Array.new
#end
query = "PREFIX RSS: <http://purl.org/rss/1.0/>
SELECT * WHERE{
SELECT DISTINCT(?concept),?pubDateTime, ?title, CONCAT( #{filtersIds} ) AS ?filtersVals
FROM <#{ZoneOntology::GRAPH_ITEMS}>
FROM <#{ZoneOntology::GRAPH_SOURCES}>
WHERE {
?concept RSS:title ?title.
OPTIONAL { ?concept RSS:pubDateTime ?pubDateTime}.
#{sparqlFilter}
}} ORDER BY DESC(?pubDateTime) LIMIT #{per_page} OFFSET #{start}"
store = SPARQL::Client.new(endpoint)
items = Array.new
store.query(query).each do |item|
similarity = item.filtersVals.to_s.scan(/http/).count
items << Item.new(item.concept.to_s, item.title, similarity)
end
return {:result => items, :query => query}
end
def self.find(param,user)
endpoint = Rails.application.config.virtuosoEndpoint
require 'cgi'
require 'uri'
uri = CGI.unescape(URI.escape(CGI.unescape(param)))
#uri = uri.gsub("%23","#")
query = "PREFIX RSS: <http://purl.org/rss/1.0/>
SELECT *
FROM <#{ZoneOntology::GRAPH_ITEMS}>
FROM <#{ZoneOntology::GRAPH_TAGS}>
WHERE { <#{uri}> ?prop ?value.
OPTIONAL{?value ?extraProp ?extraValue}";
query +="}"
puts query
store = SPARQL::Client.new(endpoint)
result = store.query(query)
if result.size == 0
return nil
end
puts query
params = Hash.new
result.each do |prop|
if params[prop.prop.to_s] == nil
params[prop.prop.to_s] = Hash.new
end
if (!prop.bound?(:extraProp))
if params[prop.prop.to_s][:value] == nil
params[prop.prop.to_s][:value] = Array.new
end
params[prop.prop.to_s][:value] << prop.value.to_s
else
if params[prop.prop.to_s][prop.value.to_s] == nil
params[prop.prop.to_s][prop.value.to_s] = Hash.new
end
params[prop.prop.to_s][prop.value.to_s][prop.extraProp.to_s] = prop.extraValue.to_s
end
end
puts params.to_json
item = Item.new(uri, params["http://purl.org/rss/1.0/title"][:value][0])
item.date = params["http://purl.org/rss/1.0/pubDate"][:value] if params["http://purl.org/rss/1.0/pubDate"] != nil
item.description = params["http://purl.org/rss/1.0/description"][:value] if params["http://purl.org/rss/1.0/description"] != nil
item.props = params
item.filters = Array.new
if params["http://zone-project.org/model/items#favorite"] != nil && user != nil
params["http://zone-project.org/model/items#favorite"].each do |fav|
if fav == "#{ZoneOntology::ZONE_USER}#{user.id}"
item.favorite = true
end
end
end
#add the filters
item.props.each do |key|
if (key[0] == "http://zone-project.org/model/items#favorite") || (key[0].start_with? "http://purl.org/rss") || (key[0].start_with? "http://zone-project.org/model/plugins/ExtractArticlesContent")
next
end
key[1].each do | filterKey, filterVal|
if filterKey.to_s == "value"
filterVal.each do |curVal|
if curVal == "true"
next
end
filter = SearchFilter.new(:value => curVal)
if curVal.start_with?("http")
filter.uri = curVal
filter.type = "http://www.w3.org/2004/02/skos/core#Concept"
end
filter.prop = key[0]
filter.item = item
item.filters << filter
end
else
filter = SearchFilter.new(:value => filterVal[ZoneOntology::RDF_LABEL])
filter.uri = filterKey
filter.prop = key[0]
filter.item = item
filter.type = filterVal[ZoneOntology::RDF_TYPE] if filterVal[ZoneOntology::RDF_TYPE] != nil
filter.abstract = filterVal[ZoneOntology::DBPEDIA_ABSTRACT] if filterVal[ZoneOntology::DBPEDIA_ABSTRACT] != nil
filter.thumb = filterVal[ZoneOntology::DBPEDIA_THUMB] if filterVal[ZoneOntology::DBPEDIA_THUMB] != nil
item.filters << filter
end
end
end
item.filters.sort! { |a,b|
if a.prop == "http://zone-project.org/model/plugins#lang"
-1
elsif b.prop == "http://zone-project.org/model/plugins#lang"
1
elsif a.type == nil
-1
elsif b.type == nil
1
else
a.type.downcase <=> b.type.downcase
end
}
return item
end
def initialize(uri,title, similarity=0)
@uri = uri
@title = title
@filters = Hash.new
@similarity = similarity
end
def to_param
require 'cgi'
CGI.escape(@uri.to_s)
end
def getUriHash
return Digest::SHA1.hexdigest(self.uri)
end
def getTypePicture
if uri.starts_with?('https://twitter.com') || uri.starts_with?('http://twitter.com')
return "/assets/twitter.png"
else
return "/assets/foregroundRSS.png"
end
end
def getTags
result = Array.new
self.props.each do |prop|
prop[1].each do |value|
filter = SearchFilter.new(:value => value)
if value.start_with?("http")
filter.uri = value
end
filter.prop = prop[0]
if(filter.prop.starts_with? WIKI_META_URI)
if(filter.uri == nil)
next
end
result << filter
elsif(filter.prop.starts_with? INSEE_GEO_URI)
result << filter
elsif (filter.prop.starts_with? TWITTER_MENTIONED_PLUGIN_URI)
filter.value = "@#{filter.value}"
result << filter
elsif (filter.prop.starts_with? TWITTER_HASHTAG_PLUGIN_URI)
filter.value = "##{filter.value}"
result << filter
end
end
end
return result
end
def addTag(tag)
graph = RDF::URI.new(ZoneOntology::GRAPH_ITEMS)
subject = RDF::URI.new(@uri)
if tag.start_with? "http"
tagNode = RDF::URI.new(tag)
else
tagNode = tag
end
$repo.insert(RDF::Virtuoso::Query.insert_data([subject,RDF::URI.new(ZoneOntology::PLUGIN_SOCIAL_ANNOTATION),tagNode]).graph(graph))
end
def deleteTag(tag)
graph = RDF::URI.new(ZoneOntology::GRAPH_ITEMS)
subject = RDF::URI.new(@uri)
self.props.each do |prop|
prop[1].each do |value|
if value == tag
if tag.start_with? "http"
tagNode = RDF::URI.new(tag)
else
tagNode = tag
end
$repo.delete(RDF::Virtuoso::Query.delete_data([subject, RDF::URI.new(prop[0]), tagNode]).graph(graph))
end
end
end
end
def getLang()
lang = self.props[LANG_URI]
if lang != nil
lang = lang[0]
if lang == "en"
return "gb"
end
end
return lang
end
end |
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/common', __FILE__)
require File.expand_path('../shared/glob', __FILE__)
describe "Dir.glob" do
before :all do
DirSpecs.create_mock_dirs
end
after :all do
DirSpecs.delete_mock_dirs
end
it_behaves_like :dir_glob, :glob
end
describe "Dir.glob" do
before :all do
DirSpecs.create_mock_dirs
end
after :all do
DirSpecs.delete_mock_dirs
end
it_behaves_like :dir_glob_recursive, :[]
end
describe "Dir.glob" do
before :all do
DirSpecs.create_mock_dirs
@cwd = Dir.pwd
Dir.chdir DirSpecs.mock_dir
end
after :all do
Dir.chdir @cwd
DirSpecs.delete_mock_dirs
end
it "can take an array of patterns" do
Dir.glob(["file_o*", "file_t*"]).should ==
%w!file_one.ext file_two.ext!
end
it "matches both dot and non-dotfiles with '*' and option File::FNM_DOTMATCH" do
Dir.glob('*', File::FNM_DOTMATCH).sort.should == DirSpecs.expected_paths
end
it "matches files with any beginning with '*<non-special characters>' and option File::FNM_DOTMATCH" do
Dir.glob('*file', File::FNM_DOTMATCH).sort.should == %w|.dotfile nondotfile|.sort
end
it "matches any files in the current directory with '**' and option File::FNM_DOTMATCH" do
Dir.glob('**', File::FNM_DOTMATCH).sort.should == DirSpecs.expected_paths
end
it "recursively matches any subdirectories except './' or '../' with '**/' and option File::FNM_DOTMATCH" do
expected = %w[
.dotsubdir/
brace/
deeply/
deeply/nested/
deeply/nested/directory/
deeply/nested/directory/structure/
dir/
special/
subdir_one/
subdir_two/
]
Dir.glob('**/', File::FNM_DOTMATCH).sort.should == expected
end
platform_is_not(:windows) do
it "matches the literal character '\\' with option File::FNM_NOESCAPE" do
Dir.mkdir 'foo?bar'
begin
Dir.glob('foo?bar', File::FNM_NOESCAPE).should == %w|foo?bar|
Dir.glob('foo\?bar', File::FNM_NOESCAPE).should == []
ensure
Dir.rmdir 'foo?bar'
end
Dir.mkdir 'foo\?bar'
begin
Dir.glob('foo\?bar', File::FNM_NOESCAPE).should == %w|foo\\?bar|
ensure
Dir.rmdir 'foo\?bar'
end
end
it "returns nil for directories current user has no permission to read" do
Dir.mkdir('no_permission')
File.chmod(0, 'no_permission')
begin
Dir.glob('no_permission/*').should == []
ensure
Dir.rmdir('no_permission')
end
end
end
end
Add spec for Dir.glob block case
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/common', __FILE__)
require File.expand_path('../shared/glob', __FILE__)
describe "Dir.glob" do
before :all do
DirSpecs.create_mock_dirs
end
after :all do
DirSpecs.delete_mock_dirs
end
it_behaves_like :dir_glob, :glob
end
describe "Dir.glob" do
before :all do
DirSpecs.create_mock_dirs
end
after :all do
DirSpecs.delete_mock_dirs
end
it_behaves_like :dir_glob_recursive, :[]
end
describe "Dir.glob" do
before :all do
DirSpecs.create_mock_dirs
@cwd = Dir.pwd
Dir.chdir DirSpecs.mock_dir
end
after :all do
Dir.chdir @cwd
DirSpecs.delete_mock_dirs
end
it "can take an array of patterns" do
Dir.glob(["file_o*", "file_t*"]).should ==
%w!file_one.ext file_two.ext!
end
it "matches both dot and non-dotfiles with '*' and option File::FNM_DOTMATCH" do
Dir.glob('*', File::FNM_DOTMATCH).sort.should == DirSpecs.expected_paths
end
it "matches files with any beginning with '*<non-special characters>' and option File::FNM_DOTMATCH" do
Dir.glob('*file', File::FNM_DOTMATCH).sort.should == %w|.dotfile nondotfile|.sort
end
it "matches any files in the current directory with '**' and option File::FNM_DOTMATCH" do
Dir.glob('**', File::FNM_DOTMATCH).sort.should == DirSpecs.expected_paths
end
it "recursively matches any subdirectories except './' or '../' with '**/' and option File::FNM_DOTMATCH" do
expected = %w[
.dotsubdir/
brace/
deeply/
deeply/nested/
deeply/nested/directory/
deeply/nested/directory/structure/
dir/
special/
subdir_one/
subdir_two/
]
Dir.glob('**/', File::FNM_DOTMATCH).sort.should == expected
end
it "accepts a block and yields it with each elements" do
ary = []
ret = Dir.glob(["file_o*", "file_t*"]) { |t| ary << t }
ret.should be_nil
ary.should == %w!file_one.ext file_two.ext!
end
platform_is_not(:windows) do
it "matches the literal character '\\' with option File::FNM_NOESCAPE" do
Dir.mkdir 'foo?bar'
begin
Dir.glob('foo?bar', File::FNM_NOESCAPE).should == %w|foo?bar|
Dir.glob('foo\?bar', File::FNM_NOESCAPE).should == []
ensure
Dir.rmdir 'foo?bar'
end
Dir.mkdir 'foo\?bar'
begin
Dir.glob('foo\?bar', File::FNM_NOESCAPE).should == %w|foo\\?bar|
ensure
Dir.rmdir 'foo\?bar'
end
end
it "returns nil for directories current user has no permission to read" do
Dir.mkdir('no_permission')
File.chmod(0, 'no_permission')
begin
Dir.glob('no_permission/*').should == []
ensure
Dir.rmdir('no_permission')
end
end
end
end
|
require "cpf_generator/version"
module CpfGenerator
class Cpf
attr_accessor :numbers
def initialize
@numbers = [*0..9].sample(9)
end
def first_dv
value = 0
down = [10,9,8,7,6,5,4,3,2]
up = [0,1,2,3,4,5,6,7,8]
9.times do |n|
value += @numbers[up[n]].to_i * down[n]
end
remainder = (value % 11)
if remainder < 2
@numbers << 0
0
else
@numbers << (11 - remainder)
(11 - remainder)
end
end
def second_dv
value = 0
down = [11,10,9,8,7,6,5,4,3,2]
up = [0,1,2,3,4,5,6,7,8,9]
10.times do |n|
value += @numbers[up[n]].to_i * down[n]
end
remainder = (value % 11)
if remainder < 2
@numbers << 0
0
else
@numbers << (11 - remainder)
(11 - remainder)
end
end
def formatted
first_dv
second_dv
cpf = @numbers.join("")
"#{cpf[0..2]}.#{cpf[3..5]}.#{cpf[6..8]}-#{cpf[9..11]}"
end
def unformatted
first_dv
second_dv
@numbers.join("")
end
end
end
improving interation code
require "cpf_generator/version"
module CpfGenerator
class Cpf
attr_accessor :numbers
def initialize
@numbers = [*0..9].sample(9)
end
def first_dv
value = 0
multipliers = [10,9,8,7,6,5,4,3,2]
multipliers.each_with_index do |mult, index|
value += @numbers[index] * mult
end
remainder = (value % 11)
if remainder < 2
@numbers << 0
0
else
@numbers << (11 - remainder)
(11 - remainder)
end
end
def second_dv
value = 0
multipliers = [11,10,9,8,7,6,5,4,3,2]
multipliers.each_with_index do |mult, index|
value += @numbers[index] * mult
end
remainder = (value % 11)
if remainder < 2
@numbers << 0
0
else
@numbers << (11 - remainder)
(11 - remainder)
end
end
def formatted
first_dv
second_dv
cpf = @numbers.join("")
"#{cpf[0..2]}.#{cpf[3..5]}.#{cpf[6..8]}-#{cpf[9..11]}"
end
def unformatted
first_dv
second_dv
@numbers.join("")
end
end
end
|
require "test/unit"
require "day"
class DayTest < Test::Unit::TestCase
def setup
@today = Time.mktime(2012, 3, 22)
def parse string
Day::Ru.new(string, @today).parse
end
end
def test_001_next_day
assert_equal parse('завтра'), Time.mktime(2012, 3, 23)
end
end
Tests for date recognition were added
# coding: utf-8
require "test/unit"
require "day"
class DayTest < Test::Unit::TestCase
def setup
@today = Time.mktime(2012, 3, 22, 0, 0)
def parse string
Day::Ru.new(string, @today).parse
end
end
#
# yesterday_today_tomorrow method testing
#
def test_001_tomorrow
assert_equal parse('завтра'), Time.mktime(2012, 3, 23)
end
def test_002_today
assert_equal parse('сегодня'), Time.mktime(2012, 3, 22)
end
def test_003_yesterday
assert_equal parse('вчера'), Time.mktime(2012, 3, 21)
end
def test_004_day_after_tomorrow
assert_equal parse('послезавтра'), Time.mktime(2012, 3, 24)
end
def test_005_day_before_yesterday
assert_equal parse('позавчера'), Time.mktime(2012, 3, 20)
end
#
# future_days method testing
#
def test_006_since_1_day
assert_equal parse('через 1 день'), Time.mktime(2012, 3, 23)
end
def test_007_since_day
assert_equal parse('через день'), Time.mktime(2012, 3, 23)
end
def test_008_since_2_days
assert_equal parse('через 2 дня'), Time.mktime(2012, 3, 24)
end
def test_009_since_10_days
assert_equal parse('через 10 дней'), Time.mktime(2012, 4, 1, 01, 00)
end
end
|
Add plugin.rb
# name: hummingbird-onebox
# about: Embed hummingbird.me media links in discourse posts
# version: 1.0
# authors: Hummingbird Media, Inc.
module Onebox
module Engine
class HummingbirdOnebox
include Engine
# a|m are short links for anime|manga
matches_regexp /https?:\/\/(?:www\.)?hummingbird\.me\/(?<type>anime|manga|a|m)\/(?<slug>.+)/
def to_html
return "<a href=\"#{@url}\">#{@url}</a>" if media.nil?
<<-HTML
<div class="onebox">
<div class="source">
<div class="info">
<a href="#{@url}" class="track-link" target="_blank">
#{media.class.to_s} (#{media_type})
</a>
</div>
</div>
<div class="onebox-body media-embed">
<img src="#{media.poster_image.url(:large)}" class="thumbnail">
<h3><a href="#{@url}" target="_blank">#{media.canonical_title}</a></h3>
<h4>#{media.genres.map {|x| x.name }.sort * ", "}</h4>
#{media.synopsis[0..199]}...
</div>
<div class="clearfix"></div>
</div>
HTML
end
private
def type
return 'anime' if @@matcher.match(@url)["type"] == 'a'
return 'manga' if @@matcher.match(@url)["type"] == 'm'
@@matcher.match(@url)["type"]
end
def slug
@@matcher.match(@url)["slug"]
end
def media
@_media ||= type.classify.constantize.find(slug)
rescue
nil
end
def media_type
if media.is_a?(Anime)
media.show_type
elsif media.is_a?(Manga)
media.manga_type
end
end
def uri
@_uri ||= URI(@url)
end
end
end
end
|
# name: discourse-tagging
# about: Support for tagging topics in Discourse
# version: 0.1
# authors: Robin Ward
# url: https://github.com/discourse/discourse-tagging
enabled_site_setting :tagging_enabled
register_asset 'stylesheets/tagging.scss'
after_initialize do
TAGS_FIELD_NAME = "tags"
TAGS_FILTER_REGEXP = /[<\\\/\>\#\?\&\s]/
module ::DiscourseTagging
class Engine < ::Rails::Engine
engine_name "discourse_tagging"
isolate_namespace DiscourseTagging
end
def self.clean_tag(tag)
tag.downcase.strip[0...SiteSetting.max_tag_length].gsub(TAGS_FILTER_REGEXP, '')
end
def self.tags_for_saving(tags, guardian)
return unless tags
tags.map! {|t| clean_tag(t) }
tags.delete_if {|t| t.blank? }
tags.uniq!
# If the user can't create tags, remove any tags that don't already exist
unless guardian.can_create_tag?
tag_count = TopicCustomField.where(name: TAGS_FIELD_NAME, value: tags).group(:value).count
tags.delete_if {|t| !tag_count.has_key?(t) }
end
return tags[0...SiteSetting.max_tags_per_topic]
end
def self.notification_key(tag_id)
"tags_notification:#{tag_id}"
end
def self.auto_notify_for(tags, topic)
key_names = tags.map {|t| notification_key(t) }
key_names_sql = ActiveRecord::Base.sql_fragment("(#{tags.map { "'%s'" }.join(', ')})", *key_names)
sql = <<-SQL
INSERT INTO topic_users(user_id, topic_id, notification_level, notifications_reason_id)
SELECT ucf.user_id,
#{topic.id.to_i},
CAST(ucf.value AS INTEGER),
#{TopicUser.notification_reasons[:plugin_changed]}
FROM user_custom_fields AS ucf
WHERE ucf.name IN #{key_names_sql}
AND NOT EXISTS(SELECT 1 FROM topic_users WHERE topic_id = #{topic.id.to_i} AND user_id = ucf.user_id)
AND CAST(ucf.value AS INTEGER) <> #{TopicUser.notification_levels[:regular]}
SQL
ActiveRecord::Base.exec_sql(sql)
end
def self.rename_tag(current_user, old_id, new_id)
sql = <<-SQL
UPDATE topic_custom_fields AS tcf
SET value = :new_id
WHERE value = :old_id
AND name = :tags_field_name
AND NOT EXISTS(SELECT 1
FROM topic_custom_fields
WHERE value = :new_id AND name = :tags_field_name AND topic_id = tcf.topic_id)
SQL
user_sql = <<-SQL
UPDATE user_custom_fields
SET name = :new_user_tag_id
WHERE name = :old_user_tag_id
AND NOT EXISTS(SELECT 1
FROM user_custom_fields
WHERE name = :new_user_tag_id)
SQL
ActiveRecord::Base.transaction do
ActiveRecord::Base.exec_sql(sql, new_id: new_id, old_id: old_id, tags_field_name: TAGS_FIELD_NAME)
TopicCustomField.delete_all(name: TAGS_FIELD_NAME, value: old_id)
ActiveRecord::Base.exec_sql(user_sql, new_user_tag_id: notification_key(new_id),
old_user_tag_id: notification_key(old_id))
UserCustomField.delete_all(name: notification_key(old_id))
StaffActionLogger.new(current_user).log_custom('renamed_tag', previous_value: old_id, new_value: new_id)
end
end
end
require_dependency 'application_controller'
require_dependency 'topic_list_responder'
require_dependency 'topics_bulk_action'
class DiscourseTagging::TagsController < ::ApplicationController
include ::TopicListResponder
requires_plugin 'discourse-tagging'
skip_before_filter :check_xhr, only: [:tag_feed, :show]
before_filter :ensure_logged_in, only: [:notifications, :update_notifications, :update]
def index
tag_counts = self.class.tags_by_count(guardian, limit: 300).count
tags = tag_counts.map {|t, c| { id: t, text: t, count: c } }
render json: { tags: tags }
end
def show
tag_id = ::DiscourseTagging.clean_tag(params[:tag_id])
topics_tagged = TopicCustomField.where(name: TAGS_FIELD_NAME, value: tag_id).pluck(:topic_id)
page = params[:page].to_i
query = TopicQuery.new(current_user, page: page)
latest_results = query.latest_results.where(id: topics_tagged)
@list = query.create_list(:by_tag, {}, latest_results)
@list.more_topics_url = list_by_tag_path(tag_id: tag_id, page: page + 1)
@rss = "tag"
respond_with_list(@list)
end
def update
guardian.ensure_can_admin_tags!
new_tag_id = ::DiscourseTagging.clean_tag(params[:tag][:id])
if current_user.staff?
::DiscourseTagging.rename_tag(current_user, params[:tag_id], new_tag_id)
end
render json: { tag: { id: new_tag_id }}
end
def destroy
guardian.ensure_can_admin_tags!
tag_id = params[:tag_id]
TopicCustomField.transaction do
TopicCustomField.where(name: TAGS_FIELD_NAME, value: tag_id).delete_all
UserCustomField.delete_all(name: ::DiscourseTagging.notification_key(tag_id))
StaffActionLogger.new(current_user).log_custom('deleted_tag', subject: tag_id)
end
render json: success_json
end
def tag_feed
discourse_expires_in 1.minute
tag_id = ::DiscourseTagging.clean_tag(params[:tag_id])
@link = "#{Discourse.base_url}/tags/#{tag_id}"
@description = I18n.t("rss_by_tag", tag: tag_id)
@title = "#{SiteSetting.title} - #{@description}"
@atom_link = "#{Discourse.base_url}/tags/#{tag_id}.rss"
query = TopicQuery.new(current_user)
topics_tagged = TopicCustomField.where(name: TAGS_FIELD_NAME, value: tag_id).pluck(:topic_id)
latest_results = query.latest_results.where(id: topics_tagged)
@topic_list = query.create_list(:by_tag, {}, latest_results)
render 'list/list', formats: [:rss]
end
def search
tags = self.class.tags_by_count(guardian)
term = params[:q]
if term.present?
term.gsub!(/[^a-z0-9\.\-]*/, '')
tags = tags.where('value like ?', "%#{term}%")
end
tags = tags.count(:value).map {|t, c| { id: t, text: t, count: c } }
render json: { results: tags }
end
def notifications
level = current_user.custom_fields[::DiscourseTagging.notification_key(params[:tag_id])] || 1
render json: { tag_notification: { id: params[:tag_id], notification_level: level.to_i } }
end
def update_notifications
level = params[:tag_notification][:notification_level].to_i
current_user.custom_fields[::DiscourseTagging.notification_key(params[:tag_id])] = level
current_user.save_custom_fields
render json: {notification_level: level}
end
private
def self.tags_by_count(guardian, opts=nil)
opts = opts || {}
result = TopicCustomField.where(name: TAGS_FIELD_NAME)
.joins(:topic)
.group(:value)
.limit(opts[:limit] || 5)
.order('COUNT(topic_custom_fields.value) DESC')
guardian.filter_allowed_categories(result)
end
end
DiscourseTagging::Engine.routes.draw do
get '/' => 'tags#index'
get '/filter/list' => 'tags#index'
get '/filter/search' => 'tags#search'
constraints(tag_id: /[^\/]+?/, format: /json|rss/) do
get '/:tag_id.rss' => 'tags#tag_feed'
get '/:tag_id' => 'tags#show', as: 'list_by_tag'
get '/:tag_id/notifications' => 'tags#notifications'
put '/:tag_id/notifications' => 'tags#update_notifications'
put '/:tag_id' => 'tags#update'
delete '/:tag_id' => 'tags#destroy'
end
end
Discourse::Application.routes.append do
mount ::DiscourseTagging::Engine, at: "/tags"
end
# Add a `tags` reader to the Topic model for easy reading of tags
class ::Topic
def preload_tags(tags)
@preloaded_tags = tags
end
def tags
return nil unless SiteSetting.tagging_enabled?
if @preloaded_tags
return nil if @preloaded_tags.blank?
return @preloaded_tags
end
result = custom_fields[TAGS_FIELD_NAME]
[result].flatten unless result.blank?
end
end
module ::DiscourseTagging::ExtendTopics
def load_topics
topics = super
if SiteSetting.tagging_enabled? && topics.present?
# super efficient for front page
map_tags = {}
Topic.exec_sql(
"SELECT topic_id, value FROM topic_custom_fields
WHERE topic_id in (:topic_ids) AND
value IS NOT NULL AND
name = 'tags'",
topic_ids: topics.map(&:id)
).values.each do |row|
(map_tags[row[0].to_i] ||= []) << row[1]
end
topics.each do |topic|
topic.preload_tags(map_tags[topic.id] || [])
end
end
topics
end
end
class ::TopicList
prepend ::DiscourseTagging::ExtendTopics
end
# Save the tags when the topic is saved
PostRevisor.track_topic_field(:tags_empty_array) do |tc, val|
if val.present?
tc.record_change(TAGS_FIELD_NAME, tc.topic.custom_fields[TAGS_FIELD_NAME], nil)
tc.topic.custom_fields.delete(TAGS_FIELD_NAME)
end
end
PostRevisor.track_topic_field(:tags) do |tc, tags|
if tags.present?
tags = ::DiscourseTagging.tags_for_saving(tags, tc.guardian)
new_tags = tags - (tc.topic.tags || [])
tc.record_change(TAGS_FIELD_NAME, tc.topic.custom_fields[TAGS_FIELD_NAME], tags)
tc.topic.custom_fields.update(TAGS_FIELD_NAME => tags)
::DiscourseTagging.auto_notify_for(new_tags, tc.topic) if new_tags.present?
end
end
on(:topic_created) do |topic, params, user|
tags = ::DiscourseTagging.tags_for_saving(params[:tags], Guardian.new(user))
if tags.present?
topic.custom_fields.update(TAGS_FIELD_NAME => tags)
topic.save
::DiscourseTagging.auto_notify_for(tags, topic)
end
end
add_to_class(:guardian, :can_create_tag?) do
user && user.has_trust_level?(SiteSetting.min_trust_to_create_tag.to_i)
end
add_to_class(:guardian, :can_admin_tags?) do
user.try(:staff?)
end
TopicsBulkAction.register_operation('change_tags') do
tags = @operation[:tags]
tags = ::DiscourseTagging.tags_for_saving(tags, guardian) if tags.present?
topics.each do |t|
if guardian.can_edit?(t)
if tags.present?
t.custom_fields.update(TAGS_FIELD_NAME => tags)
t.save
::DiscourseTagging.auto_notify_for(tags, t)
else
t.custom_fields.delete(TAGS_FIELD_NAME)
end
end
end
end
# Return tag related stuff in JSON output
TopicViewSerializer.attributes_from_topic(:tags)
add_to_serializer(:site, :can_create_tag) { scope.can_create_tag? }
add_to_serializer(:site, :tags_filter_regexp) { TAGS_FILTER_REGEXP.source }
class ::TopicListItemSerializer
attributes :tags
end
Plugin::Filter.register(:topic_categories_breadcrumb) do |topic, breadcrumbs|
if (tags = topic.tags).present?
tags.each do |tag|
tag_id = ::DiscourseTagging.clean_tag(tag)
url = "#{Discourse.base_url}/tags/#{tag_id}"
breadcrumbs << {url: url, name: tag}
end
end
breadcrumbs
end
end
FIX: Retain backwards compatibility with stable
# name: discourse-tagging
# about: Support for tagging topics in Discourse
# version: 0.1
# authors: Robin Ward
# url: https://github.com/discourse/discourse-tagging
enabled_site_setting :tagging_enabled
register_asset 'stylesheets/tagging.scss'
after_initialize do
TAGS_FIELD_NAME = "tags"
TAGS_FILTER_REGEXP = /[<\\\/\>\#\?\&\s]/
module ::DiscourseTagging
class Engine < ::Rails::Engine
engine_name "discourse_tagging"
isolate_namespace DiscourseTagging
end
def self.clean_tag(tag)
tag.downcase.strip[0...SiteSetting.max_tag_length].gsub(TAGS_FILTER_REGEXP, '')
end
def self.tags_for_saving(tags, guardian)
return unless tags
tags.map! {|t| clean_tag(t) }
tags.delete_if {|t| t.blank? }
tags.uniq!
# If the user can't create tags, remove any tags that don't already exist
unless guardian.can_create_tag?
tag_count = TopicCustomField.where(name: TAGS_FIELD_NAME, value: tags).group(:value).count
tags.delete_if {|t| !tag_count.has_key?(t) }
end
return tags[0...SiteSetting.max_tags_per_topic]
end
def self.notification_key(tag_id)
"tags_notification:#{tag_id}"
end
def self.auto_notify_for(tags, topic)
key_names = tags.map {|t| notification_key(t) }
key_names_sql = ActiveRecord::Base.sql_fragment("(#{tags.map { "'%s'" }.join(', ')})", *key_names)
sql = <<-SQL
INSERT INTO topic_users(user_id, topic_id, notification_level, notifications_reason_id)
SELECT ucf.user_id,
#{topic.id.to_i},
CAST(ucf.value AS INTEGER),
#{TopicUser.notification_reasons[:plugin_changed]}
FROM user_custom_fields AS ucf
WHERE ucf.name IN #{key_names_sql}
AND NOT EXISTS(SELECT 1 FROM topic_users WHERE topic_id = #{topic.id.to_i} AND user_id = ucf.user_id)
AND CAST(ucf.value AS INTEGER) <> #{TopicUser.notification_levels[:regular]}
SQL
ActiveRecord::Base.exec_sql(sql)
end
def self.rename_tag(current_user, old_id, new_id)
sql = <<-SQL
UPDATE topic_custom_fields AS tcf
SET value = :new_id
WHERE value = :old_id
AND name = :tags_field_name
AND NOT EXISTS(SELECT 1
FROM topic_custom_fields
WHERE value = :new_id AND name = :tags_field_name AND topic_id = tcf.topic_id)
SQL
user_sql = <<-SQL
UPDATE user_custom_fields
SET name = :new_user_tag_id
WHERE name = :old_user_tag_id
AND NOT EXISTS(SELECT 1
FROM user_custom_fields
WHERE name = :new_user_tag_id)
SQL
ActiveRecord::Base.transaction do
ActiveRecord::Base.exec_sql(sql, new_id: new_id, old_id: old_id, tags_field_name: TAGS_FIELD_NAME)
TopicCustomField.delete_all(name: TAGS_FIELD_NAME, value: old_id)
ActiveRecord::Base.exec_sql(user_sql, new_user_tag_id: notification_key(new_id),
old_user_tag_id: notification_key(old_id))
UserCustomField.delete_all(name: notification_key(old_id))
StaffActionLogger.new(current_user).log_custom('renamed_tag', previous_value: old_id, new_value: new_id)
end
end
end
require_dependency 'application_controller'
require_dependency 'topic_list_responder'
require_dependency 'topics_bulk_action'
class DiscourseTagging::TagsController < ::ApplicationController
include ::TopicListResponder
requires_plugin 'discourse-tagging'
skip_before_filter :check_xhr, only: [:tag_feed, :show]
before_filter :ensure_logged_in, only: [:notifications, :update_notifications, :update]
def index
tag_counts = self.class.tags_by_count(guardian, limit: 300).count
tags = tag_counts.map {|t, c| { id: t, text: t, count: c } }
render json: { tags: tags }
end
def show
tag_id = ::DiscourseTagging.clean_tag(params[:tag_id])
topics_tagged = TopicCustomField.where(name: TAGS_FIELD_NAME, value: tag_id).pluck(:topic_id)
page = params[:page].to_i
query = TopicQuery.new(current_user, page: page)
latest_results = query.latest_results.where(id: topics_tagged)
@list = query.create_list(:by_tag, {}, latest_results)
@list.more_topics_url = list_by_tag_path(tag_id: tag_id, page: page + 1)
@rss = "tag"
respond_with_list(@list)
end
def update
guardian.ensure_can_admin_tags!
new_tag_id = ::DiscourseTagging.clean_tag(params[:tag][:id])
if current_user.staff?
::DiscourseTagging.rename_tag(current_user, params[:tag_id], new_tag_id)
end
render json: { tag: { id: new_tag_id }}
end
def destroy
guardian.ensure_can_admin_tags!
tag_id = params[:tag_id]
TopicCustomField.transaction do
TopicCustomField.where(name: TAGS_FIELD_NAME, value: tag_id).delete_all
UserCustomField.delete_all(name: ::DiscourseTagging.notification_key(tag_id))
StaffActionLogger.new(current_user).log_custom('deleted_tag', subject: tag_id)
end
render json: success_json
end
def tag_feed
discourse_expires_in 1.minute
tag_id = ::DiscourseTagging.clean_tag(params[:tag_id])
@link = "#{Discourse.base_url}/tags/#{tag_id}"
@description = I18n.t("rss_by_tag", tag: tag_id)
@title = "#{SiteSetting.title} - #{@description}"
@atom_link = "#{Discourse.base_url}/tags/#{tag_id}.rss"
query = TopicQuery.new(current_user)
topics_tagged = TopicCustomField.where(name: TAGS_FIELD_NAME, value: tag_id).pluck(:topic_id)
latest_results = query.latest_results.where(id: topics_tagged)
@topic_list = query.create_list(:by_tag, {}, latest_results)
render 'list/list', formats: [:rss]
end
def search
tags = self.class.tags_by_count(guardian)
term = params[:q]
if term.present?
term.gsub!(/[^a-z0-9\.\-]*/, '')
tags = tags.where('value like ?', "%#{term}%")
end
tags = tags.count(:value).map {|t, c| { id: t, text: t, count: c } }
render json: { results: tags }
end
def notifications
level = current_user.custom_fields[::DiscourseTagging.notification_key(params[:tag_id])] || 1
render json: { tag_notification: { id: params[:tag_id], notification_level: level.to_i } }
end
def update_notifications
level = params[:tag_notification][:notification_level].to_i
current_user.custom_fields[::DiscourseTagging.notification_key(params[:tag_id])] = level
current_user.save_custom_fields
render json: {notification_level: level}
end
private
def self.tags_by_count(guardian, opts=nil)
opts = opts || {}
result = TopicCustomField.where(name: TAGS_FIELD_NAME)
.joins(:topic)
.group(:value)
.limit(opts[:limit] || 5)
.order('COUNT(topic_custom_fields.value) DESC')
guardian.filter_allowed_categories(result)
end
end
DiscourseTagging::Engine.routes.draw do
get '/' => 'tags#index'
get '/filter/list' => 'tags#index'
get '/filter/search' => 'tags#search'
constraints(tag_id: /[^\/]+?/, format: /json|rss/) do
get '/:tag_id.rss' => 'tags#tag_feed'
get '/:tag_id' => 'tags#show', as: 'list_by_tag'
get '/:tag_id/notifications' => 'tags#notifications'
put '/:tag_id/notifications' => 'tags#update_notifications'
put '/:tag_id' => 'tags#update'
delete '/:tag_id' => 'tags#destroy'
end
end
Discourse::Application.routes.append do
mount ::DiscourseTagging::Engine, at: "/tags"
end
# Add a `tags` reader to the Topic model for easy reading of tags
class ::Topic
def preload_tags(tags)
@preloaded_tags = tags
end
def tags
return nil unless SiteSetting.tagging_enabled?
if @preloaded_tags
return nil if @preloaded_tags.blank?
return @preloaded_tags
end
result = custom_fields[TAGS_FIELD_NAME]
[result].flatten unless result.blank?
end
end
module ::DiscourseTagging::ExtendTopics
def load_topics
topics = super
if SiteSetting.tagging_enabled? && topics.present?
# super efficient for front page
map_tags = {}
Topic.exec_sql(
"SELECT topic_id, value FROM topic_custom_fields
WHERE topic_id in (:topic_ids) AND
value IS NOT NULL AND
name = 'tags'",
topic_ids: topics.map(&:id)
).values.each do |row|
(map_tags[row[0].to_i] ||= []) << row[1]
end
topics.each do |topic|
topic.preload_tags(map_tags[topic.id] || [])
end
end
topics
end
end
class ::TopicList
prepend ::DiscourseTagging::ExtendTopics
end
# Save the tags when the topic is saved
PostRevisor.track_topic_field(:tags_empty_array) do |tc, val|
if val.present?
tc.record_change(TAGS_FIELD_NAME, tc.topic.custom_fields[TAGS_FIELD_NAME], nil)
tc.topic.custom_fields.delete(TAGS_FIELD_NAME)
end
end
PostRevisor.track_topic_field(:tags) do |tc, tags|
if tags.present?
tags = ::DiscourseTagging.tags_for_saving(tags, tc.guardian)
new_tags = tags - (tc.topic.tags || [])
tc.record_change(TAGS_FIELD_NAME, tc.topic.custom_fields[TAGS_FIELD_NAME], tags)
tc.topic.custom_fields.update(TAGS_FIELD_NAME => tags)
::DiscourseTagging.auto_notify_for(new_tags, tc.topic) if new_tags.present?
end
end
on(:topic_created) do |topic, params, user|
tags = ::DiscourseTagging.tags_for_saving(params[:tags], Guardian.new(user))
if tags.present?
topic.custom_fields.update(TAGS_FIELD_NAME => tags)
topic.save
::DiscourseTagging.auto_notify_for(tags, topic)
end
end
add_to_class(:guardian, :can_create_tag?) do
user && user.has_trust_level?(SiteSetting.min_trust_to_create_tag.to_i)
end
add_to_class(:guardian, :can_admin_tags?) do
user.try(:staff?)
end
TopicsBulkAction.register_operation('change_tags') do
tags = @operation[:tags]
tags = ::DiscourseTagging.tags_for_saving(tags, guardian) if tags.present?
topics.each do |t|
if guardian.can_edit?(t)
if tags.present?
t.custom_fields.update(TAGS_FIELD_NAME => tags)
t.save
::DiscourseTagging.auto_notify_for(tags, t)
else
t.custom_fields.delete(TAGS_FIELD_NAME)
end
end
end
end
# Return tag related stuff in JSON output
TopicViewSerializer.attributes_from_topic(:tags)
add_to_serializer(:site, :can_create_tag) { scope.can_create_tag? }
add_to_serializer(:site, :tags_filter_regexp) { TAGS_FILTER_REGEXP.source }
add_to_serializer(:topic_list_item, :tags) { object.tags }
Plugin::Filter.register(:topic_categories_breadcrumb) do |topic, breadcrumbs|
if (tags = topic.tags).present?
tags.each do |tag|
tag_id = ::DiscourseTagging.clean_tag(tag)
url = "#{Discourse.base_url}/tags/#{tag_id}"
breadcrumbs << {url: url, name: tag}
end
end
breadcrumbs
end
end
|
# frozen_string_literal: true
# name: discourse-data-explorer
# about: Interface for running analysis SQL queries on the live database
# version: 0.2
# authors: Riking
# url: https://github.com/discourse/discourse-data-explorer
enabled_site_setting :data_explorer_enabled
register_asset 'stylesheets/explorer.scss'
if respond_to?(:register_svg_icon)
register_svg_icon "caret-down"
register_svg_icon "caret-right"
register_svg_icon "chevron-left"
register_svg_icon "exclamation-circle"
register_svg_icon "info"
register_svg_icon "pencil-alt"
register_svg_icon "upload"
end
# route: /admin/plugins/explorer
add_admin_route 'explorer.title', 'explorer'
module ::DataExplorer
QUERY_RESULT_MAX_LIMIT = 1000
def self.plugin_name
'discourse-data-explorer'.freeze
end
def self.pstore_get(key)
PluginStore.get(DataExplorer.plugin_name, key)
end
def self.pstore_set(key, value)
PluginStore.set(DataExplorer.plugin_name, key, value)
end
def self.pstore_delete(key)
PluginStore.remove(DataExplorer.plugin_name, key)
end
end
after_initialize do
add_to_class(:guardian, :user_is_a_member_of_group?) do |group|
return false if !current_user
return true if current_user.admin?
return current_user.group_ids.include?(group.id)
end
add_to_class(:guardian, :user_can_access_query?) do |group, query|
return false if !current_user
return true if current_user.admin?
return user_is_a_member_of_group?(group) &&
query.group_ids.include?(group.id.to_s)
end
module ::DataExplorer
class Engine < ::Rails::Engine
engine_name "data_explorer"
isolate_namespace DataExplorer
end
class ValidationError < StandardError
end
class SmallBadgeSerializer < ApplicationSerializer
attributes :id, :name, :badge_type, :description, :icon
end
class SmallPostWithExcerptSerializer < ApplicationSerializer
attributes :id, :topic_id, :post_number, :excerpt
attributes :username, :avatar_template
def excerpt
Post.excerpt(object.cooked, 70)
end
def username
object.user && object.user.username
end
def avatar_template
object.user && object.user.avatar_template
end
end
# Run a data explorer query on the currently connected database.
#
# @param [DataExplorer::Query] query the Query object to run
# @param [Hash] params the colon-style query parameters to pass to AR
# @param [Hash] opts hash of options
# explain - include a query plan in the result
# @return [Hash]
# error - any exception that was raised in the execution. Check this
# first before looking at any other fields.
# pg_result - the PG::Result object
# duration_nanos - the query duration, in nanoseconds
# explain - the query
def self.run_query(query, req_params = {}, opts = {})
# Safety checks
# see test 'doesn't allow you to modify the database #2'
if query.sql =~ /;/
err = DataExplorer::ValidationError.new(I18n.t('js.errors.explorer.no_semicolons'))
return { error: err, duration_nanos: 0 }
end
query_args = {}
begin
query_args = query.cast_params req_params
rescue DataExplorer::ValidationError => e
return { error: e, duration_nanos: 0 }
end
time_start, time_end, explain, err, result = nil
begin
ActiveRecord::Base.connection.transaction do
# Setting transaction to read only prevents shoot-in-foot actions like SELECT FOR UPDATE
# see test 'doesn't allow you to modify the database #1'
DB.exec "SET TRANSACTION READ ONLY"
# Set a statement timeout so we can't tie up the server
DB.exec "SET LOCAL statement_timeout = 10000"
# SQL comments are for the benefits of the slow queries log
sql = <<-SQL
/*
* DataExplorer Query
* Query: /admin/plugins/explorer?id=#{query.id}
* Started by: #{opts[:current_user]}
*/
WITH query AS (
#{query.sql}
) SELECT * FROM query
LIMIT #{opts[:limit] || DataExplorer::QUERY_RESULT_MAX_LIMIT}
SQL
time_start = Time.now
# we probably want to rewrite this ... but for now reuse the working
# code we have
sql = DB.param_encoder.encode(sql, query_args)
result = ActiveRecord::Base.connection.raw_connection.async_exec(sql)
result.check # make sure it's done
time_end = Time.now
if opts[:explain]
explain = DB.query_hash("EXPLAIN #{query.sql}", query_args)
.map { |row| row["QUERY PLAN"] }.join "\n"
end
# All done. Issue a rollback anyways, just in case
# see test 'doesn't allow you to modify the database #1'
raise ActiveRecord::Rollback
end
rescue Exception => ex
err = ex
time_end = Time.now
end
{
error: err,
pg_result: result,
duration_secs: time_end - time_start,
explain: explain,
params_full: query_args
}
end
def self.extra_data_pluck_fields
@extra_data_pluck_fields ||= {
user: { class: User, fields: [:id, :username, :uploaded_avatar_id], serializer: BasicUserSerializer },
badge: { class: Badge, fields: [:id, :name, :badge_type_id, :description, :icon], include: [:badge_type], serializer: SmallBadgeSerializer },
post: { class: Post, fields: [:id, :topic_id, :post_number, :cooked, :user_id], include: [:user], serializer: SmallPostWithExcerptSerializer },
topic: { class: Topic, fields: [:id, :title, :slug, :posts_count], serializer: BasicTopicSerializer },
group: { class: Group, ignore: true },
category: { class: Category, ignore: true },
reltime: { ignore: true },
html: { ignore: true },
}
end
def self.column_regexes
@column_regexes ||=
extra_data_pluck_fields.map do |key, val|
if val[:class]
/(#{val[:class].to_s.downcase})_id$/
end
end.compact
end
def self.add_extra_data(pg_result)
needed_classes = {}
ret = {}
col_map = {}
pg_result.fields.each_with_index do |col, idx|
rgx = column_regexes.find { |r| r.match col }
if rgx
cls = (rgx.match col)[1].to_sym
needed_classes[cls] ||= []
needed_classes[cls] << idx
elsif col =~ /^(\w+)\$/
cls = $1.to_sym
needed_classes[cls] ||= []
needed_classes[cls] << idx
elsif col =~ /^\w+_url$/
col_map[idx] = "url"
end
end
needed_classes.each do |cls, column_nums|
next unless column_nums.present?
support_info = extra_data_pluck_fields[cls]
next unless support_info
column_nums.each do |col_n|
col_map[col_n] = cls
end
if support_info[:ignore]
ret[cls] = []
next
end
ids = Set.new
column_nums.each do |col_n|
ids.merge(pg_result.column_values(col_n))
end
ids.delete nil
ids.map! &:to_i
object_class = support_info[:class]
all_objs = object_class
all_objs = all_objs.with_deleted if all_objs.respond_to? :with_deleted
all_objs = all_objs
.select(support_info[:fields])
.where(id: ids.to_a.sort)
.includes(support_info[:include])
.order(:id)
ret[cls] = ActiveModel::ArraySerializer.new(all_objs, each_serializer: support_info[:serializer])
end
[ret, col_map]
end
def self.sensitive_column_names
%w(
#_IP_Addresses
topic_views.ip_address
users.ip_address
users.registration_ip_address
incoming_links.ip_address
topic_link_clicks.ip_address
user_histories.ip_address
#_Emails
email_tokens.email
users.email
invites.email
user_histories.email
email_logs.to_address
posts.raw_email
badge_posts.raw_email
#_Secret_Tokens
email_tokens.token
email_logs.reply_key
api_keys.key
site_settings.value
users.auth_token
users.password_hash
users.salt
#_Authentication_Info
user_open_ids.email
oauth2_user_infos.uid
oauth2_user_infos.email
facebook_user_infos.facebook_user_id
facebook_user_infos.email
twitter_user_infos.twitter_user_id
github_user_infos.github_user_id
single_sign_on_records.external_email
single_sign_on_records.external_id
google_user_infos.google_user_id
google_user_infos.email
)
end
def self.schema
# No need to expire this, because the server processes get restarted on upgrade
# refer user to http://www.postgresql.org/docs/9.3/static/datatype.html
@schema ||= begin
results = DB.query_hash <<~SQL
select
c.column_name column_name,
c.data_type data_type,
c.character_maximum_length character_maximum_length,
c.is_nullable is_nullable,
c.column_default column_default,
c.table_name table_name,
pgd.description column_desc
from INFORMATION_SCHEMA.COLUMNS c
inner join pg_catalog.pg_statio_all_tables st on (c.table_schema = st.schemaname and c.table_name = st.relname)
left outer join pg_catalog.pg_description pgd on (pgd.objoid = st.relid and pgd.objsubid = c.ordinal_position)
where c.table_schema = 'public'
ORDER BY c.table_name, c.ordinal_position
SQL
by_table = {}
# Massage the results into a nicer form
results.each do |hash|
full_col_name = "#{hash['table_name']}.#{hash['column_name']}"
if hash['is_nullable'] == "YES"
hash['is_nullable'] = true
else
hash.delete('is_nullable')
end
clen = hash.delete 'character_maximum_length'
dt = hash['data_type']
if hash['column_name'] == 'id'
hash['data_type'] = 'serial'
hash['primary'] = true
elsif dt == 'character varying'
hash['data_type'] = "varchar(#{clen.to_i})"
elsif dt == 'timestamp without time zone'
hash['data_type'] = 'timestamp'
elsif dt == 'double precision'
hash['data_type'] = 'double'
end
default = hash['column_default']
if default.nil? || default =~ /^nextval\(/
hash.delete 'column_default'
elsif default =~ /^'(.*)'::(character varying|text)/
hash['column_default'] = $1
end
hash.delete('column_desc') unless hash['column_desc']
if sensitive_column_names.include? full_col_name
hash['sensitive'] = true
end
if enum_info.include? full_col_name
hash['enum'] = enum_info[full_col_name]
end
if denormalized_columns.include? full_col_name
hash['denormal'] = denormalized_columns[full_col_name]
end
fkey = fkey_info(hash['table_name'], hash['column_name'])
if fkey
hash['fkey_info'] = fkey
end
table_name = hash.delete('table_name')
by_table[table_name] ||= []
by_table[table_name] << hash
end
# this works for now, but no big loss if the tables aren't quite sorted
favored_order = %w(posts topics users categories badges groups notifications post_actions site_settings)
sorted_by_table = {}
favored_order.each do |tbl|
sorted_by_table[tbl] = by_table[tbl]
end
by_table.keys.sort.each do |tbl|
next if favored_order.include? tbl
sorted_by_table[tbl] = by_table[tbl]
end
sorted_by_table
end
end
def self.enums
return @enums if @enums
@enums = {
'application_requests.req_type': ApplicationRequest.req_types,
'badges.badge_type_id': Enum.new(:gold, :silver, :bronze, start: 1),
'category_groups.permission_type': CategoryGroup.permission_types,
'category_users.notification_level': CategoryUser.notification_levels,
'directory_items.period_type': DirectoryItem.period_types,
'groups.id': Group::AUTO_GROUPS,
'groups.mentionable_level': Group::ALIAS_LEVELS,
'groups.messageable_level': Group::ALIAS_LEVELS,
'groups.members_visibility_level': Group.visibility_levels,
'groups.visibility_level': Group.visibility_levels,
'groups.default_notification_level': GroupUser.notification_levels,
'group_users.notification_level': GroupUser.notification_levels,
'notifications.notification_type': Notification.types,
'polls.results': Poll.results,
'polls.status': Poll.statuses,
'polls.type': Poll.types,
'polls.visibility': Poll.visibilities,
'post_action_types.id': PostActionType.types,
'post_actions.post_action_type_id': PostActionType.types,
'posts.cook_method': Post.cook_methods,
'posts.hidden_reason_id': Post.hidden_reasons,
'posts.post_type': Post.types,
'reviewable_histories.reviewable_history_type': ReviewableHistory.types,
'reviewable_scores.status': ReviewableScore.statuses,
'screened_emails.action_type': ScreenedEmail.actions,
'screened_ip_addresses.action_type': ScreenedIpAddress.actions,
'screened_urls.action_type': ScreenedUrl.actions,
'search_logs.search_result_type': SearchLog.search_result_types,
'search_logs.search_type': SearchLog.search_types,
'site_settings.data_type': SiteSetting.types,
'skipped_email_logs.reason_type': SkippedEmailLog.reason_types,
'tag_group_permissions.permission_type': TagGroupPermission.permission_types,
'theme_settings.data_type': ThemeSetting.types,
'topic_timers.status_type': TopicTimer.types,
'topic_users.notification_level': TopicUser.notification_levels,
'topic_users.notifications_reason_id': TopicUser.notification_reasons,
'user_histories.action': UserHistory.actions,
'user_security_keys.factor_type': UserSecurityKey.factor_types,
'users.trust_level': TrustLevel.levels,
'web_hooks.content_type': WebHook.content_types,
'web_hooks.last_delivery_status': WebHook.last_delivery_statuses,
}.with_indifferent_access
# QueuedPost is removed in recent Discourse releases
@enums['queued_posts.state'] = QueuedPost.states if defined?(QueuedPost)
@enums['reviewables.status'] = Reviewable.statuses if defined?(Reviewable)
@enums
end
def self.enum_info
@enum_info ||= begin
enum_info = {}
enums.map do |key, enum|
# https://stackoverflow.com/questions/10874356/reverse-a-hash-in-ruby
enum_info[key] = Hash[enum.to_a.map(&:reverse)]
end
enum_info
end
end
def self.fkey_info(table, column)
full_name = "#{table}.#{column}"
if fkey_defaults[column]
fkey_defaults[column]
elsif column =~ /_by_id$/ || column =~ /_user_id$/
:users
elsif foreign_keys[full_name]
foreign_keys[full_name]
else
nil
end
end
def self.foreign_keys
@fkey_columns ||= {
'posts.last_editor_id': :users,
'posts.version': :'post_revisions.number',
'topics.featured_user1_id': :users,
'topics.featured_user2_id': :users,
'topics.featured_user3_id': :users,
'topics.featured_user4_id': :users,
'topics.featured_user5_id': :users,
'users.seen_notification_id': :notifications,
'users.uploaded_avatar_id': :uploads,
'users.primary_group_id': :groups,
'categories.latest_post_id': :posts,
'categories.latest_topic_id': :topics,
'categories.parent_category_id': :categories,
'badges.badge_grouping_id': :badge_groupings,
'post_actions.related_post_id': :posts,
'color_scheme_colors.color_scheme_id': :color_schemes,
'color_schemes.versioned_id': :color_schemes,
'incoming_links.incoming_referer_id': :incoming_referers,
'incoming_referers.incoming_domain_id': :incoming_domains,
'post_replies.reply_id': :posts,
'quoted_posts.quoted_post_id': :posts,
'topic_link_clicks.topic_link_id': :topic_links,
'topic_link_clicks.link_topic_id': :topics,
'topic_link_clicks.link_post_id': :posts,
'user_actions.target_topic_id': :topics,
'user_actions.target_post_id': :posts,
'user_avatars.custom_upload_id': :uploads,
'user_avatars.gravatar_upload_id': :uploads,
'user_badges.notification_id': :notifications,
'user_profiles.card_image_badge_id': :badges,
}.with_indifferent_access
end
def self.fkey_defaults
@fkey_defaults ||= {
user_id: :users,
# :*_by_id => :users,
# :*_user_id => :users,
category_id: :categories,
group_id: :groups,
post_id: :posts,
post_action_id: :post_actions,
topic_id: :topics,
upload_id: :uploads,
}.with_indifferent_access
end
def self.denormalized_columns
{
'posts.reply_count': :post_replies,
'posts.quote_count': :quoted_posts,
'posts.incoming_link_count': :topic_links,
'posts.word_count': :posts,
'posts.avg_time': :post_timings,
'posts.reads': :post_timings,
'posts.like_score': :post_actions,
'posts.like_count': :post_actions,
'posts.bookmark_count': :post_actions,
'posts.vote_count': :post_actions,
'posts.off_topic_count': :post_actions,
'posts.notify_moderators_count': :post_actions,
'posts.spam_count': :post_actions,
'posts.illegal_count': :post_actions,
'posts.inappropriate_count': :post_actions,
'posts.notify_user_count': :post_actions,
'topics.views': :topic_views,
'topics.posts_count': :posts,
'topics.reply_count': :posts,
'topics.incoming_link_count': :topic_links,
'topics.moderator_posts_count': :posts,
'topics.participant_count': :posts,
'topics.word_count': :posts,
'topics.last_posted_at': :posts,
'topics.last_post_user_idt': :posts,
'topics.avg_time': :post_timings,
'topics.highest_post_number': :posts,
'topics.image_url': :posts,
'topics.excerpt': :posts,
'topics.like_count': :post_actions,
'topics.bookmark_count': :post_actions,
'topics.vote_count': :post_actions,
'topics.off_topic_count': :post_actions,
'topics.notify_moderators_count': :post_actions,
'topics.spam_count': :post_actions,
'topics.illegal_count': :post_actions,
'topics.inappropriate_count': :post_actions,
'topics.notify_user_count': :post_actions,
'categories.topic_count': :topics,
'categories.post_count': :posts,
'categories.latest_post_id': :posts,
'categories.latest_topic_id': :topics,
'categories.description': :posts,
'categories.read_restricted': :category_groups,
'categories.topics_year': :topics,
'categories.topics_month': :topics,
'categories.topics_week': :topics,
'categories.topics_day': :topics,
'categories.posts_year': :posts,
'categories.posts_month': :posts,
'categories.posts_week': :posts,
'categories.posts_day': :posts,
'badges.grant_count': :user_badges,
'groups.user_count': :group_users,
'directory_items.likes_received': :post_actions,
'directory_items.likes_given': :post_actions,
'directory_items.topics_entered': :user_stats,
'directory_items.days_visited': :user_stats,
'directory_items.posts_read': :user_stats,
'directory_items.topic_count': :topics,
'directory_items.post_count': :posts,
'post_search_data.search_data': :posts,
'top_topics.yearly_posts_count': :posts,
'top_topics.monthly_posts_count': :posts,
'top_topics.weekly_posts_count': :posts,
'top_topics.daily_posts_count': :posts,
'top_topics.yearly_views_count': :topic_views,
'top_topics.monthly_views_count': :topic_views,
'top_topics.weekly_views_count': :topic_views,
'top_topics.daily_views_count': :topic_views,
'top_topics.yearly_likes_count': :post_actions,
'top_topics.monthly_likes_count': :post_actions,
'top_topics.weekly_likes_count': :post_actions,
'top_topics.daily_likes_count': :post_actions,
'top_topics.yearly_op_likes_count': :post_actions,
'top_topics.monthly_op_likes_count': :post_actions,
'top_topics.weekly_op_likes_count': :post_actions,
'top_topics.daily_op_likes_count': :post_actions,
'top_topics.all_score': :posts,
'top_topics.yearly_score': :posts,
'top_topics.monthly_score': :posts,
'top_topics.weekly_score': :posts,
'top_topics.daily_score': :posts,
'topic_links.clicks': :topic_link_clicks,
'topic_search_data.search_data': :topics,
'topic_users.liked': :post_actions,
'topic_users.bookmarked': :post_actions,
'user_stats.posts_read_count': :post_timings,
'user_stats.topic_reply_count': :posts,
'user_stats.first_post_created_at': :posts,
'user_stats.post_count': :posts,
'user_stats.topic_count': :topics,
'user_stats.likes_given': :post_actions,
'user_stats.likes_received': :post_actions,
'user_search_data.search_data': :user_profiles,
'users.last_posted_at': :posts,
'users.previous_visit_at': :user_visits,
}.with_indifferent_access
end
end
# Reimplement a couple ActiveRecord methods, but use PluginStore for storage instead
require_dependency File.expand_path('../lib/queries.rb', __FILE__)
class DataExplorer::Query
attr_accessor :id, :name, :description, :sql, :created_by, :created_at, :group_ids, :last_run_at
def initialize
@name = 'Unnamed Query'
@description = ''
@sql = 'SELECT 1'
@group_ids = []
end
def slug
Slug.for(name).presence || "query-#{id}"
end
def params
@params ||= DataExplorer::Parameter.create_from_sql(sql)
end
def check_params!
DataExplorer::Parameter.create_from_sql(sql, strict: true)
nil
end
def cast_params(input_params)
result = {}.with_indifferent_access
self.params.each do |pobj|
result[pobj.identifier] = pobj.cast_to_ruby input_params[pobj.identifier]
end
result
end
def can_be_run_by(group)
@group_ids.include?(group.id.to_s)
end
# saving/loading functions
# May want to extract this into a library or something for plugins to use?
def self.alloc_id
DistributedMutex.synchronize('data-explorer_query-id') do
max_id = DataExplorer.pstore_get("q:_id")
max_id = 1 unless max_id
DataExplorer.pstore_set("q:_id", max_id + 1)
max_id
end
end
def self.from_hash(h)
query = DataExplorer::Query.new
[:name, :description, :sql, :created_by, :created_at, :last_run_at].each do |sym|
query.send("#{sym}=", h[sym].strip) if h[sym]
end
group_ids = (h[:group_ids] == "" || !h[:group_ids]) ? [] : h[:group_ids]
query.group_ids = group_ids
query.id = h[:id].to_i if h[:id]
query
end
def to_hash
{
id: @id,
name: @name,
description: @description,
sql: @sql,
created_by: @created_by,
created_at: @created_at,
group_ids: @group_ids,
last_run_at: @last_run_at
}
end
def self.find(id, opts = {})
if DataExplorer.pstore_get("q:#{id}").nil? && id < 0
hash = Queries.default[id.to_s]
hash[:id] = id
from_hash hash
else
unless hash = DataExplorer.pstore_get("q:#{id}")
return DataExplorer::Query.new if opts[:ignore_deleted]
raise Discourse::NotFound
end
from_hash hash
end
end
def save
check_params!
return save_default_query if @id && @id < 0
@id = @id || self.class.alloc_id
DataExplorer.pstore_set "q:#{id}", to_hash
end
def save_default_query
check_params!
# Read from queries.rb again to pick up any changes and save them
query = Queries.default[id.to_s]
@id = query["id"]
@sql = query["sql"]
@group_ids = @group_ids || []
@name = query["name"]
@description = query["description"]
DataExplorer.pstore_set "q:#{id}", to_hash
end
def destroy
DataExplorer.pstore_delete "q:#{id}"
end
def read_attribute_for_serialization(attr)
self.send(attr)
end
def self.all
PluginStoreRow.where(plugin_name: DataExplorer.plugin_name)
.where("key LIKE 'q:%'")
.where("key != 'q:_id'")
.map do |psr|
DataExplorer::Query.from_hash PluginStore.cast_value(psr.type_name, psr.value)
end.sort_by { |query| query.name }
end
def self.destroy_all
PluginStoreRow.where(plugin_name: DataExplorer.plugin_name)
.where("key LIKE 'q:%'")
.destroy_all
end
end
class DataExplorer::Parameter
attr_accessor :identifier, :type, :default, :nullable
def initialize(identifier, type, default, nullable)
raise DataExplorer::ValidationError.new('Parameter declaration error - identifier is missing') unless identifier
raise DataExplorer::ValidationError.new('Parameter declaration error - type is missing') unless type
# process aliases
type = type.to_sym
if DataExplorer::Parameter.type_aliases[type]
type = DataExplorer::Parameter.type_aliases[type]
end
raise DataExplorer::ValidationError.new("Parameter declaration error - unknown type #{type}") unless DataExplorer::Parameter.types[type]
@identifier = identifier
@type = type
@default = default
@nullable = nullable
begin
cast_to_ruby default unless default.blank?
rescue DataExplorer::ValidationError
raise DataExplorer::ValidationError.new("Parameter declaration error - the default value is not a valid #{type}")
end
end
def to_hash
{
identifier: @identifier,
type: @type,
default: @default,
nullable: @nullable,
}
end
def self.types
@types ||= Enum.new(
# Normal types
:int, :bigint, :boolean, :string, :date, :time, :datetime, :double,
# Selection help
:user_id, :post_id, :topic_id, :category_id, :group_id, :badge_id,
# Arrays
:int_list, :string_list, :user_list
)
end
def self.type_aliases
@type_aliases ||= {
integer: :int,
text: :string,
timestamp: :datetime,
}
end
def cast_to_ruby(string)
string = @default unless string
if string.blank?
if @nullable
return nil
else
raise DataExplorer::ValidationError.new("Missing parameter #{identifier} of type #{type}")
end
end
if string.downcase == '#null'
return nil
end
def invalid_format(string, msg = nil)
if msg
raise DataExplorer::ValidationError.new("'#{string}' is an invalid #{type} - #{msg}")
else
raise DataExplorer::ValidationError.new("'#{string}' is an invalid value for #{type}")
end
end
value = nil
case @type
when :int
invalid_format string, 'Not an integer' unless string =~ /^-?\d+$/
value = string.to_i
invalid_format string, 'Too large' unless Integer === value
when :bigint
invalid_format string, 'Not an integer' unless string =~ /^-?\d+$/
value = string.to_i
when :boolean
value = !!(string =~ /t|true|y|yes|1/i)
when :string
value = string
when :time
begin
value = Time.parse string
rescue ArgumentError => e
invalid_format string, e.message
end
when :date
begin
value = Date.parse string
rescue ArgumentError => e
invalid_format string, e.message
end
when :datetime
begin
value = DateTime.parse string
rescue ArgumentError => e
invalid_format string, e.message
end
when :double
if string =~ /-?\d*(\.\d+)/
value = Float(string)
elsif string =~ /^(-?)Inf(inity)?$/i
if $1
value = -Float::INFINITY
else
value = Float::INFINITY
end
elsif string =~ /^(-?)NaN$/i
if $1
value = -Float::NAN
else
value = Float::NAN
end
else
invalid_format string
end
when :category_id
if string =~ /(.*)\/(.*)/
parent_name = $1
child_name = $2
parent = Category.query_parent_category(parent_name)
invalid_format string, "Could not find category named #{parent_name}" unless parent
object = Category.query_category(child_name, parent)
invalid_format string, "Could not find subcategory of #{parent_name} named #{child_name}" unless object
else
object = Category.where(id: string.to_i).first || Category.where(slug: string).first || Category.where(name: string).first
invalid_format string, "Could not find category named #{string}" unless object
end
value = object.id
when :user_id, :post_id, :topic_id, :group_id, :badge_id
if string.gsub(/[ _]/, '') =~ /^-?\d+$/
clazz_name = (/^(.*)_id$/.match(type.to_s)[1].classify.to_sym)
begin
object = Object.const_get(clazz_name).with_deleted.find(string.gsub(/[ _]/, '').to_i)
value = object.id
rescue ActiveRecord::RecordNotFound
invalid_format string, "The specified #{clazz_name} was not found"
end
elsif type == :user_id
begin
object = User.find_by_username_or_email(string)
value = object.id
rescue ActiveRecord::RecordNotFound
invalid_format string, "The user named #{string} was not found"
end
elsif type == :post_id
if string =~ /(\d+)\/(\d+)(\?u=.*)?$/
object = Post.with_deleted.find_by(topic_id: $1, post_number: $2)
invalid_format string, "The post at topic:#{$1} post_number:#{$2} was not found" unless object
value = object.id
end
elsif type == :topic_id
if string =~ /\/t\/[^\/]+\/(\d+)/
begin
object = Topic.with_deleted.find($1)
value = object.id
rescue ActiveRecord::RecordNotFound
invalid_format string, "The topic with id #{$1} was not found"
end
end
elsif type == :group_id
object = Group.where(name: string).first
invalid_format string, "The group named #{string} was not found" unless object
value = object.id
else
invalid_format string
end
when :int_list
value = string.split(',').map { |s| s.downcase == '#null' ? nil : s.to_i }
invalid_format string, "can't be empty" if value.length == 0
when :string_list
value = string.split(',').map { |s| s.downcase == '#null' ? nil : s }
invalid_format string, "can't be empty" if value.length == 0
when :user_list
value = string.split(',').map { |s| User.find_by_username_or_email(s) }
invalid_format string, "can't be empty" if value.length == 0
else
raise TypeError.new('unknown parameter type??? should not get here')
end
value
end
def self.create_from_sql(sql, opts = {})
in_params = false
ret_params = []
sql.lines.find do |line|
line.chomp!
if in_params
# -- (ident) :(ident) (= (ident))?
if line =~ /^\s*--\s*([a-zA-Z_ ]+)\s*:([a-z_]+)\s*(?:=\s+(.*)\s*)?$/
type = $1
ident = $2
default = $3
nullable = false
if type =~ /^(null)?(.*?)(null)?$/i
if $1 || $3
nullable = true
end
type = $2
end
type = type.strip
begin
ret_params << DataExplorer::Parameter.new(ident, type, default, nullable)
rescue
if opts[:strict]
raise
end
end
false
elsif line =~ /^\s+$/
false
else
true
end
else
if line =~ /^\s*--\s*\[params\]\s*$/
in_params = true
end
false
end
end
ret_params
end
end
require_dependency 'application_controller'
require_dependency File.expand_path('../lib/queries.rb', __FILE__)
class DataExplorer::QueryController < ::ApplicationController
requires_plugin DataExplorer.plugin_name
before_action :check_enabled
before_action :set_group, only: [:group_reports_index, :group_reports_show, :group_reports_run]
before_action :set_query, only: [:group_reports_show, :group_reports_run]
attr_reader :group, :query
def check_enabled
raise Discourse::NotFound unless SiteSetting.data_explorer_enabled?
end
def set_group
@group = Group.find_by(name: params["group_name"])
end
def set_query
@query = DataExplorer::Query.find(params[:id].to_i)
end
def index
# guardian.ensure_can_use_data_explorer!
queries = DataExplorer::Query.all
Queries.default.each do |params|
query = DataExplorer::Query.new
query.id = params.second["id"]
query.sql = params.second["sql"]
query.name = params.second["name"]
query.description = params.second["description"]
query.created_by = Discourse::SYSTEM_USER_ID.to_s
# don't render this query if query with the same id already exists in pstore
queries.push(query) unless DataExplorer.pstore_get("q:#{query.id}").present?
end
render_serialized queries, DataExplorer::QuerySerializer, root: 'queries'
end
skip_before_action :check_xhr, only: [:show]
def show
check_xhr unless params[:export]
query = DataExplorer::Query.find(params[:id].to_i)
if params[:export]
response.headers['Content-Disposition'] = "attachment; filename=#{query.slug}.dcquery.json"
response.sending_file = true
end
# guardian.ensure_can_see! query
render_serialized query, DataExplorer::QuerySerializer, root: 'query'
end
def groups
render_serialized(Group.all, BasicGroupSerializer)
end
def group_reports_index
return raise Discourse::NotFound unless guardian.user_is_a_member_of_group?(group)
respond_to do |format|
format.html { render 'groups/show' }
format.json do
queries = DataExplorer::Query.all
queries.select! { |query| query.group_ids&.include?(group.id.to_s) }
render_serialized queries, DataExplorer::QuerySerializer, root: 'queries'
end
end
end
def group_reports_show
return raise Discourse::NotFound unless guardian.user_can_access_query?(group, query)
respond_to do |format|
format.html { render 'groups/show' }
format.json do
render_serialized query, DataExplorer::QuerySerializer, root: 'query'
end
end
end
skip_before_action :check_xhr, only: [:group_reports_run]
def group_reports_run
return raise Discourse::NotFound unless guardian.user_can_access_query?(group, query)
run
end
def create
# guardian.ensure_can_create_explorer_query!
query = DataExplorer::Query.from_hash params.require(:query)
query.created_at = Time.now
query.created_by = current_user.id.to_s
query.last_run_at = Time.now
query.id = nil # json import will assign an id, which is wrong
query.save
render_serialized query, DataExplorer::QuerySerializer, root: 'query'
end
def update
query = DataExplorer::Query.find(params[:id].to_i, ignore_deleted: true)
hash = params.require(:query)
hash[:group_ids] ||= []
# Undeleting
unless query.id
if hash[:id]
query.id = hash[:id].to_i
else
raise Discourse::NotFound
end
end
[:name, :sql, :description, :created_by, :created_at, :group_ids, :last_run_at].each do |sym|
query.send("#{sym}=", hash[sym]) if hash[sym]
end
query.check_params!
query.save
render_serialized query, DataExplorer::QuerySerializer, root: 'query'
rescue DataExplorer::ValidationError => e
render_json_error e.message
end
def destroy
query = DataExplorer::Query.find(params[:id].to_i)
query.destroy
render json: { success: true, errors: [] }
end
def schema
schema_version = DB.query_single("SELECT max(version) AS tag FROM schema_migrations").first
if stale?(public: true, etag: schema_version, template: false)
render json: DataExplorer.schema
end
end
skip_before_action :check_xhr, only: [:run]
# Return value:
# success - true/false. if false, inspect the errors value.
# errors - array of strings.
# params - hash. Echo of the query parameters as executed.
# duration - float. Time to execute the query, in milliseconds, to 1 decimal place.
# columns - array of strings. Titles of the returned columns, in order.
# explain - string. (Optional - pass explain=true in the request) Postgres query plan, UNIX newlines.
# rows - array of array of strings. Results of the query. In the same order as 'columns'.
def run
check_xhr unless params[:download]
query = DataExplorer::Query.find(params[:id].to_i)
query.last_run_at = Time.now
if params[:id].to_i < 0
query.created_by = Discourse::SYSTEM_USER_ID.to_s
query.save_default_query
else
query.save
end
if params[:download]
response.sending_file = true
end
params[:params] = params[:_params] if params[:_params] # testing workaround
query_params = {}
query_params = MultiJson.load(params[:params]) if params[:params]
opts = { current_user: current_user.username }
opts[:explain] = true if params[:explain] == "true"
opts[:limit] =
if params[:limit] == "ALL" || params[:format] == "csv"
"ALL"
elsif params[:limit]
params[:limit].to_i
end
result = DataExplorer.run_query(query, query_params, opts)
if result[:error]
err = result[:error]
# Pretty printing logic
err_class = err.class
err_msg = err.message
if err.is_a? ActiveRecord::StatementInvalid
err_class = err.original_exception.class
err_msg.gsub!("#{err_class}:", '')
else
err_msg = "#{err_class}: #{err_msg}"
end
render json: {
success: false,
errors: [err_msg]
}, status: 422
else
pg_result = result[:pg_result]
cols = pg_result.fields
respond_to do |format|
format.json do
if params[:download]
response.headers['Content-Disposition'] =
"attachment; filename=#{query.slug}@#{Slug.for(Discourse.current_hostname, 'discourse')}-#{Date.today}.dcqresult.json"
end
json = {
success: true,
errors: [],
duration: (result[:duration_secs].to_f * 1000).round(1),
result_count: pg_result.values.length || 0,
params: query_params,
columns: cols,
default_limit: DataExplorer::QUERY_RESULT_MAX_LIMIT
}
json[:explain] = result[:explain] if opts[:explain]
if !params[:download]
relations, colrender = DataExplorer.add_extra_data(pg_result)
json[:relations] = relations
json[:colrender] = colrender
end
json[:rows] = pg_result.values
render json: json
end
format.csv do
response.headers['Content-Disposition'] =
"attachment; filename=#{query.slug}@#{Slug.for(Discourse.current_hostname, 'discourse')}-#{Date.today}.dcqresult.csv"
require 'csv'
text = CSV.generate do |csv|
csv << cols
pg_result.values.each do |row|
csv << row
end
end
render plain: text
end
end
end
end
end
class DataExplorer::QuerySerializer < ActiveModel::Serializer
attributes :id, :sql, :name, :description, :param_info, :created_by, :created_at, :username, :group_ids, :last_run_at
def param_info
object.params.map(&:to_hash) rescue nil
end
def username
User.find(created_by).username rescue nil
end
end
DataExplorer::Engine.routes.draw do
root to: "query#index"
get 'schema' => "query#schema"
get 'queries' => "query#index"
get 'groups' => "query#groups"
post 'queries' => "query#create"
get 'queries/:id' => "query#show"
put 'queries/:id' => "query#update"
delete 'queries/:id' => "query#destroy"
post 'queries/:id/run' => "query#run"
end
Discourse::Application.routes.append do
get '/g/:group_name/reports' => 'data_explorer/query#group_reports_index'
get '/g/:group_name/reports/:id' => 'data_explorer/query#group_reports_show'
post '/g/:group_name/reports/:id/run' => 'data_explorer/query#group_reports_run'
mount ::DataExplorer::Engine, at: '/admin/plugins/explorer', constraints: AdminConstraint.new
end
end
DEV: set limit for maximum no of rows in CSV exports.
# frozen_string_literal: true
# name: discourse-data-explorer
# about: Interface for running analysis SQL queries on the live database
# version: 0.2
# authors: Riking
# url: https://github.com/discourse/discourse-data-explorer
enabled_site_setting :data_explorer_enabled
register_asset 'stylesheets/explorer.scss'
if respond_to?(:register_svg_icon)
register_svg_icon "caret-down"
register_svg_icon "caret-right"
register_svg_icon "chevron-left"
register_svg_icon "exclamation-circle"
register_svg_icon "info"
register_svg_icon "pencil-alt"
register_svg_icon "upload"
end
# route: /admin/plugins/explorer
add_admin_route 'explorer.title', 'explorer'
module ::DataExplorer
QUERY_RESULT_DEFAULT_LIMIT = 1000
QUERY_RESULT_MAX_LIMIT = 10000
def self.plugin_name
'discourse-data-explorer'.freeze
end
def self.pstore_get(key)
PluginStore.get(DataExplorer.plugin_name, key)
end
def self.pstore_set(key, value)
PluginStore.set(DataExplorer.plugin_name, key, value)
end
def self.pstore_delete(key)
PluginStore.remove(DataExplorer.plugin_name, key)
end
end
after_initialize do
add_to_class(:guardian, :user_is_a_member_of_group?) do |group|
return false if !current_user
return true if current_user.admin?
return current_user.group_ids.include?(group.id)
end
add_to_class(:guardian, :user_can_access_query?) do |group, query|
return false if !current_user
return true if current_user.admin?
return user_is_a_member_of_group?(group) &&
query.group_ids.include?(group.id.to_s)
end
module ::DataExplorer
class Engine < ::Rails::Engine
engine_name "data_explorer"
isolate_namespace DataExplorer
end
class ValidationError < StandardError
end
class SmallBadgeSerializer < ApplicationSerializer
attributes :id, :name, :badge_type, :description, :icon
end
class SmallPostWithExcerptSerializer < ApplicationSerializer
attributes :id, :topic_id, :post_number, :excerpt
attributes :username, :avatar_template
def excerpt
Post.excerpt(object.cooked, 70)
end
def username
object.user && object.user.username
end
def avatar_template
object.user && object.user.avatar_template
end
end
# Run a data explorer query on the currently connected database.
#
# @param [DataExplorer::Query] query the Query object to run
# @param [Hash] params the colon-style query parameters to pass to AR
# @param [Hash] opts hash of options
# explain - include a query plan in the result
# @return [Hash]
# error - any exception that was raised in the execution. Check this
# first before looking at any other fields.
# pg_result - the PG::Result object
# duration_nanos - the query duration, in nanoseconds
# explain - the query
def self.run_query(query, req_params = {}, opts = {})
# Safety checks
# see test 'doesn't allow you to modify the database #2'
if query.sql =~ /;/
err = DataExplorer::ValidationError.new(I18n.t('js.errors.explorer.no_semicolons'))
return { error: err, duration_nanos: 0 }
end
query_args = {}
begin
query_args = query.cast_params req_params
rescue DataExplorer::ValidationError => e
return { error: e, duration_nanos: 0 }
end
time_start, time_end, explain, err, result = nil
begin
ActiveRecord::Base.connection.transaction do
# Setting transaction to read only prevents shoot-in-foot actions like SELECT FOR UPDATE
# see test 'doesn't allow you to modify the database #1'
DB.exec "SET TRANSACTION READ ONLY"
# Set a statement timeout so we can't tie up the server
DB.exec "SET LOCAL statement_timeout = 10000"
# SQL comments are for the benefits of the slow queries log
sql = <<-SQL
/*
* DataExplorer Query
* Query: /admin/plugins/explorer?id=#{query.id}
* Started by: #{opts[:current_user]}
*/
WITH query AS (
#{query.sql}
) SELECT * FROM query
LIMIT #{opts[:limit] || DataExplorer::QUERY_RESULT_DEFAULT_LIMIT}
SQL
time_start = Time.now
# we probably want to rewrite this ... but for now reuse the working
# code we have
sql = DB.param_encoder.encode(sql, query_args)
result = ActiveRecord::Base.connection.raw_connection.async_exec(sql)
result.check # make sure it's done
time_end = Time.now
if opts[:explain]
explain = DB.query_hash("EXPLAIN #{query.sql}", query_args)
.map { |row| row["QUERY PLAN"] }.join "\n"
end
# All done. Issue a rollback anyways, just in case
# see test 'doesn't allow you to modify the database #1'
raise ActiveRecord::Rollback
end
rescue Exception => ex
err = ex
time_end = Time.now
end
{
error: err,
pg_result: result,
duration_secs: time_end - time_start,
explain: explain,
params_full: query_args
}
end
def self.extra_data_pluck_fields
@extra_data_pluck_fields ||= {
user: { class: User, fields: [:id, :username, :uploaded_avatar_id], serializer: BasicUserSerializer },
badge: { class: Badge, fields: [:id, :name, :badge_type_id, :description, :icon], include: [:badge_type], serializer: SmallBadgeSerializer },
post: { class: Post, fields: [:id, :topic_id, :post_number, :cooked, :user_id], include: [:user], serializer: SmallPostWithExcerptSerializer },
topic: { class: Topic, fields: [:id, :title, :slug, :posts_count], serializer: BasicTopicSerializer },
group: { class: Group, ignore: true },
category: { class: Category, ignore: true },
reltime: { ignore: true },
html: { ignore: true },
}
end
def self.column_regexes
@column_regexes ||=
extra_data_pluck_fields.map do |key, val|
if val[:class]
/(#{val[:class].to_s.downcase})_id$/
end
end.compact
end
def self.add_extra_data(pg_result)
needed_classes = {}
ret = {}
col_map = {}
pg_result.fields.each_with_index do |col, idx|
rgx = column_regexes.find { |r| r.match col }
if rgx
cls = (rgx.match col)[1].to_sym
needed_classes[cls] ||= []
needed_classes[cls] << idx
elsif col =~ /^(\w+)\$/
cls = $1.to_sym
needed_classes[cls] ||= []
needed_classes[cls] << idx
elsif col =~ /^\w+_url$/
col_map[idx] = "url"
end
end
needed_classes.each do |cls, column_nums|
next unless column_nums.present?
support_info = extra_data_pluck_fields[cls]
next unless support_info
column_nums.each do |col_n|
col_map[col_n] = cls
end
if support_info[:ignore]
ret[cls] = []
next
end
ids = Set.new
column_nums.each do |col_n|
ids.merge(pg_result.column_values(col_n))
end
ids.delete nil
ids.map! &:to_i
object_class = support_info[:class]
all_objs = object_class
all_objs = all_objs.with_deleted if all_objs.respond_to? :with_deleted
all_objs = all_objs
.select(support_info[:fields])
.where(id: ids.to_a.sort)
.includes(support_info[:include])
.order(:id)
ret[cls] = ActiveModel::ArraySerializer.new(all_objs, each_serializer: support_info[:serializer])
end
[ret, col_map]
end
def self.sensitive_column_names
%w(
#_IP_Addresses
topic_views.ip_address
users.ip_address
users.registration_ip_address
incoming_links.ip_address
topic_link_clicks.ip_address
user_histories.ip_address
#_Emails
email_tokens.email
users.email
invites.email
user_histories.email
email_logs.to_address
posts.raw_email
badge_posts.raw_email
#_Secret_Tokens
email_tokens.token
email_logs.reply_key
api_keys.key
site_settings.value
users.auth_token
users.password_hash
users.salt
#_Authentication_Info
user_open_ids.email
oauth2_user_infos.uid
oauth2_user_infos.email
facebook_user_infos.facebook_user_id
facebook_user_infos.email
twitter_user_infos.twitter_user_id
github_user_infos.github_user_id
single_sign_on_records.external_email
single_sign_on_records.external_id
google_user_infos.google_user_id
google_user_infos.email
)
end
def self.schema
# No need to expire this, because the server processes get restarted on upgrade
# refer user to http://www.postgresql.org/docs/9.3/static/datatype.html
@schema ||= begin
results = DB.query_hash <<~SQL
select
c.column_name column_name,
c.data_type data_type,
c.character_maximum_length character_maximum_length,
c.is_nullable is_nullable,
c.column_default column_default,
c.table_name table_name,
pgd.description column_desc
from INFORMATION_SCHEMA.COLUMNS c
inner join pg_catalog.pg_statio_all_tables st on (c.table_schema = st.schemaname and c.table_name = st.relname)
left outer join pg_catalog.pg_description pgd on (pgd.objoid = st.relid and pgd.objsubid = c.ordinal_position)
where c.table_schema = 'public'
ORDER BY c.table_name, c.ordinal_position
SQL
by_table = {}
# Massage the results into a nicer form
results.each do |hash|
full_col_name = "#{hash['table_name']}.#{hash['column_name']}"
if hash['is_nullable'] == "YES"
hash['is_nullable'] = true
else
hash.delete('is_nullable')
end
clen = hash.delete 'character_maximum_length'
dt = hash['data_type']
if hash['column_name'] == 'id'
hash['data_type'] = 'serial'
hash['primary'] = true
elsif dt == 'character varying'
hash['data_type'] = "varchar(#{clen.to_i})"
elsif dt == 'timestamp without time zone'
hash['data_type'] = 'timestamp'
elsif dt == 'double precision'
hash['data_type'] = 'double'
end
default = hash['column_default']
if default.nil? || default =~ /^nextval\(/
hash.delete 'column_default'
elsif default =~ /^'(.*)'::(character varying|text)/
hash['column_default'] = $1
end
hash.delete('column_desc') unless hash['column_desc']
if sensitive_column_names.include? full_col_name
hash['sensitive'] = true
end
if enum_info.include? full_col_name
hash['enum'] = enum_info[full_col_name]
end
if denormalized_columns.include? full_col_name
hash['denormal'] = denormalized_columns[full_col_name]
end
fkey = fkey_info(hash['table_name'], hash['column_name'])
if fkey
hash['fkey_info'] = fkey
end
table_name = hash.delete('table_name')
by_table[table_name] ||= []
by_table[table_name] << hash
end
# this works for now, but no big loss if the tables aren't quite sorted
favored_order = %w(posts topics users categories badges groups notifications post_actions site_settings)
sorted_by_table = {}
favored_order.each do |tbl|
sorted_by_table[tbl] = by_table[tbl]
end
by_table.keys.sort.each do |tbl|
next if favored_order.include? tbl
sorted_by_table[tbl] = by_table[tbl]
end
sorted_by_table
end
end
def self.enums
return @enums if @enums
@enums = {
'application_requests.req_type': ApplicationRequest.req_types,
'badges.badge_type_id': Enum.new(:gold, :silver, :bronze, start: 1),
'category_groups.permission_type': CategoryGroup.permission_types,
'category_users.notification_level': CategoryUser.notification_levels,
'directory_items.period_type': DirectoryItem.period_types,
'groups.id': Group::AUTO_GROUPS,
'groups.mentionable_level': Group::ALIAS_LEVELS,
'groups.messageable_level': Group::ALIAS_LEVELS,
'groups.members_visibility_level': Group.visibility_levels,
'groups.visibility_level': Group.visibility_levels,
'groups.default_notification_level': GroupUser.notification_levels,
'group_users.notification_level': GroupUser.notification_levels,
'notifications.notification_type': Notification.types,
'polls.results': Poll.results,
'polls.status': Poll.statuses,
'polls.type': Poll.types,
'polls.visibility': Poll.visibilities,
'post_action_types.id': PostActionType.types,
'post_actions.post_action_type_id': PostActionType.types,
'posts.cook_method': Post.cook_methods,
'posts.hidden_reason_id': Post.hidden_reasons,
'posts.post_type': Post.types,
'reviewable_histories.reviewable_history_type': ReviewableHistory.types,
'reviewable_scores.status': ReviewableScore.statuses,
'screened_emails.action_type': ScreenedEmail.actions,
'screened_ip_addresses.action_type': ScreenedIpAddress.actions,
'screened_urls.action_type': ScreenedUrl.actions,
'search_logs.search_result_type': SearchLog.search_result_types,
'search_logs.search_type': SearchLog.search_types,
'site_settings.data_type': SiteSetting.types,
'skipped_email_logs.reason_type': SkippedEmailLog.reason_types,
'tag_group_permissions.permission_type': TagGroupPermission.permission_types,
'theme_settings.data_type': ThemeSetting.types,
'topic_timers.status_type': TopicTimer.types,
'topic_users.notification_level': TopicUser.notification_levels,
'topic_users.notifications_reason_id': TopicUser.notification_reasons,
'user_histories.action': UserHistory.actions,
'user_security_keys.factor_type': UserSecurityKey.factor_types,
'users.trust_level': TrustLevel.levels,
'web_hooks.content_type': WebHook.content_types,
'web_hooks.last_delivery_status': WebHook.last_delivery_statuses,
}.with_indifferent_access
# QueuedPost is removed in recent Discourse releases
@enums['queued_posts.state'] = QueuedPost.states if defined?(QueuedPost)
@enums['reviewables.status'] = Reviewable.statuses if defined?(Reviewable)
@enums
end
def self.enum_info
@enum_info ||= begin
enum_info = {}
enums.map do |key, enum|
# https://stackoverflow.com/questions/10874356/reverse-a-hash-in-ruby
enum_info[key] = Hash[enum.to_a.map(&:reverse)]
end
enum_info
end
end
def self.fkey_info(table, column)
full_name = "#{table}.#{column}"
if fkey_defaults[column]
fkey_defaults[column]
elsif column =~ /_by_id$/ || column =~ /_user_id$/
:users
elsif foreign_keys[full_name]
foreign_keys[full_name]
else
nil
end
end
def self.foreign_keys
@fkey_columns ||= {
'posts.last_editor_id': :users,
'posts.version': :'post_revisions.number',
'topics.featured_user1_id': :users,
'topics.featured_user2_id': :users,
'topics.featured_user3_id': :users,
'topics.featured_user4_id': :users,
'topics.featured_user5_id': :users,
'users.seen_notification_id': :notifications,
'users.uploaded_avatar_id': :uploads,
'users.primary_group_id': :groups,
'categories.latest_post_id': :posts,
'categories.latest_topic_id': :topics,
'categories.parent_category_id': :categories,
'badges.badge_grouping_id': :badge_groupings,
'post_actions.related_post_id': :posts,
'color_scheme_colors.color_scheme_id': :color_schemes,
'color_schemes.versioned_id': :color_schemes,
'incoming_links.incoming_referer_id': :incoming_referers,
'incoming_referers.incoming_domain_id': :incoming_domains,
'post_replies.reply_id': :posts,
'quoted_posts.quoted_post_id': :posts,
'topic_link_clicks.topic_link_id': :topic_links,
'topic_link_clicks.link_topic_id': :topics,
'topic_link_clicks.link_post_id': :posts,
'user_actions.target_topic_id': :topics,
'user_actions.target_post_id': :posts,
'user_avatars.custom_upload_id': :uploads,
'user_avatars.gravatar_upload_id': :uploads,
'user_badges.notification_id': :notifications,
'user_profiles.card_image_badge_id': :badges,
}.with_indifferent_access
end
def self.fkey_defaults
@fkey_defaults ||= {
user_id: :users,
# :*_by_id => :users,
# :*_user_id => :users,
category_id: :categories,
group_id: :groups,
post_id: :posts,
post_action_id: :post_actions,
topic_id: :topics,
upload_id: :uploads,
}.with_indifferent_access
end
def self.denormalized_columns
{
'posts.reply_count': :post_replies,
'posts.quote_count': :quoted_posts,
'posts.incoming_link_count': :topic_links,
'posts.word_count': :posts,
'posts.avg_time': :post_timings,
'posts.reads': :post_timings,
'posts.like_score': :post_actions,
'posts.like_count': :post_actions,
'posts.bookmark_count': :post_actions,
'posts.vote_count': :post_actions,
'posts.off_topic_count': :post_actions,
'posts.notify_moderators_count': :post_actions,
'posts.spam_count': :post_actions,
'posts.illegal_count': :post_actions,
'posts.inappropriate_count': :post_actions,
'posts.notify_user_count': :post_actions,
'topics.views': :topic_views,
'topics.posts_count': :posts,
'topics.reply_count': :posts,
'topics.incoming_link_count': :topic_links,
'topics.moderator_posts_count': :posts,
'topics.participant_count': :posts,
'topics.word_count': :posts,
'topics.last_posted_at': :posts,
'topics.last_post_user_idt': :posts,
'topics.avg_time': :post_timings,
'topics.highest_post_number': :posts,
'topics.image_url': :posts,
'topics.excerpt': :posts,
'topics.like_count': :post_actions,
'topics.bookmark_count': :post_actions,
'topics.vote_count': :post_actions,
'topics.off_topic_count': :post_actions,
'topics.notify_moderators_count': :post_actions,
'topics.spam_count': :post_actions,
'topics.illegal_count': :post_actions,
'topics.inappropriate_count': :post_actions,
'topics.notify_user_count': :post_actions,
'categories.topic_count': :topics,
'categories.post_count': :posts,
'categories.latest_post_id': :posts,
'categories.latest_topic_id': :topics,
'categories.description': :posts,
'categories.read_restricted': :category_groups,
'categories.topics_year': :topics,
'categories.topics_month': :topics,
'categories.topics_week': :topics,
'categories.topics_day': :topics,
'categories.posts_year': :posts,
'categories.posts_month': :posts,
'categories.posts_week': :posts,
'categories.posts_day': :posts,
'badges.grant_count': :user_badges,
'groups.user_count': :group_users,
'directory_items.likes_received': :post_actions,
'directory_items.likes_given': :post_actions,
'directory_items.topics_entered': :user_stats,
'directory_items.days_visited': :user_stats,
'directory_items.posts_read': :user_stats,
'directory_items.topic_count': :topics,
'directory_items.post_count': :posts,
'post_search_data.search_data': :posts,
'top_topics.yearly_posts_count': :posts,
'top_topics.monthly_posts_count': :posts,
'top_topics.weekly_posts_count': :posts,
'top_topics.daily_posts_count': :posts,
'top_topics.yearly_views_count': :topic_views,
'top_topics.monthly_views_count': :topic_views,
'top_topics.weekly_views_count': :topic_views,
'top_topics.daily_views_count': :topic_views,
'top_topics.yearly_likes_count': :post_actions,
'top_topics.monthly_likes_count': :post_actions,
'top_topics.weekly_likes_count': :post_actions,
'top_topics.daily_likes_count': :post_actions,
'top_topics.yearly_op_likes_count': :post_actions,
'top_topics.monthly_op_likes_count': :post_actions,
'top_topics.weekly_op_likes_count': :post_actions,
'top_topics.daily_op_likes_count': :post_actions,
'top_topics.all_score': :posts,
'top_topics.yearly_score': :posts,
'top_topics.monthly_score': :posts,
'top_topics.weekly_score': :posts,
'top_topics.daily_score': :posts,
'topic_links.clicks': :topic_link_clicks,
'topic_search_data.search_data': :topics,
'topic_users.liked': :post_actions,
'topic_users.bookmarked': :post_actions,
'user_stats.posts_read_count': :post_timings,
'user_stats.topic_reply_count': :posts,
'user_stats.first_post_created_at': :posts,
'user_stats.post_count': :posts,
'user_stats.topic_count': :topics,
'user_stats.likes_given': :post_actions,
'user_stats.likes_received': :post_actions,
'user_search_data.search_data': :user_profiles,
'users.last_posted_at': :posts,
'users.previous_visit_at': :user_visits,
}.with_indifferent_access
end
end
# Reimplement a couple ActiveRecord methods, but use PluginStore for storage instead
require_dependency File.expand_path('../lib/queries.rb', __FILE__)
class DataExplorer::Query
attr_accessor :id, :name, :description, :sql, :created_by, :created_at, :group_ids, :last_run_at
def initialize
@name = 'Unnamed Query'
@description = ''
@sql = 'SELECT 1'
@group_ids = []
end
def slug
Slug.for(name).presence || "query-#{id}"
end
def params
@params ||= DataExplorer::Parameter.create_from_sql(sql)
end
def check_params!
DataExplorer::Parameter.create_from_sql(sql, strict: true)
nil
end
def cast_params(input_params)
result = {}.with_indifferent_access
self.params.each do |pobj|
result[pobj.identifier] = pobj.cast_to_ruby input_params[pobj.identifier]
end
result
end
def can_be_run_by(group)
@group_ids.include?(group.id.to_s)
end
# saving/loading functions
# May want to extract this into a library or something for plugins to use?
def self.alloc_id
DistributedMutex.synchronize('data-explorer_query-id') do
max_id = DataExplorer.pstore_get("q:_id")
max_id = 1 unless max_id
DataExplorer.pstore_set("q:_id", max_id + 1)
max_id
end
end
def self.from_hash(h)
query = DataExplorer::Query.new
[:name, :description, :sql, :created_by, :created_at, :last_run_at].each do |sym|
query.send("#{sym}=", h[sym].strip) if h[sym]
end
group_ids = (h[:group_ids] == "" || !h[:group_ids]) ? [] : h[:group_ids]
query.group_ids = group_ids
query.id = h[:id].to_i if h[:id]
query
end
def to_hash
{
id: @id,
name: @name,
description: @description,
sql: @sql,
created_by: @created_by,
created_at: @created_at,
group_ids: @group_ids,
last_run_at: @last_run_at
}
end
def self.find(id, opts = {})
if DataExplorer.pstore_get("q:#{id}").nil? && id < 0
hash = Queries.default[id.to_s]
hash[:id] = id
from_hash hash
else
unless hash = DataExplorer.pstore_get("q:#{id}")
return DataExplorer::Query.new if opts[:ignore_deleted]
raise Discourse::NotFound
end
from_hash hash
end
end
def save
check_params!
return save_default_query if @id && @id < 0
@id = @id || self.class.alloc_id
DataExplorer.pstore_set "q:#{id}", to_hash
end
def save_default_query
check_params!
# Read from queries.rb again to pick up any changes and save them
query = Queries.default[id.to_s]
@id = query["id"]
@sql = query["sql"]
@group_ids = @group_ids || []
@name = query["name"]
@description = query["description"]
DataExplorer.pstore_set "q:#{id}", to_hash
end
def destroy
DataExplorer.pstore_delete "q:#{id}"
end
def read_attribute_for_serialization(attr)
self.send(attr)
end
def self.all
PluginStoreRow.where(plugin_name: DataExplorer.plugin_name)
.where("key LIKE 'q:%'")
.where("key != 'q:_id'")
.map do |psr|
DataExplorer::Query.from_hash PluginStore.cast_value(psr.type_name, psr.value)
end.sort_by { |query| query.name }
end
def self.destroy_all
PluginStoreRow.where(plugin_name: DataExplorer.plugin_name)
.where("key LIKE 'q:%'")
.destroy_all
end
end
class DataExplorer::Parameter
attr_accessor :identifier, :type, :default, :nullable
def initialize(identifier, type, default, nullable)
raise DataExplorer::ValidationError.new('Parameter declaration error - identifier is missing') unless identifier
raise DataExplorer::ValidationError.new('Parameter declaration error - type is missing') unless type
# process aliases
type = type.to_sym
if DataExplorer::Parameter.type_aliases[type]
type = DataExplorer::Parameter.type_aliases[type]
end
raise DataExplorer::ValidationError.new("Parameter declaration error - unknown type #{type}") unless DataExplorer::Parameter.types[type]
@identifier = identifier
@type = type
@default = default
@nullable = nullable
begin
cast_to_ruby default unless default.blank?
rescue DataExplorer::ValidationError
raise DataExplorer::ValidationError.new("Parameter declaration error - the default value is not a valid #{type}")
end
end
def to_hash
{
identifier: @identifier,
type: @type,
default: @default,
nullable: @nullable,
}
end
def self.types
@types ||= Enum.new(
# Normal types
:int, :bigint, :boolean, :string, :date, :time, :datetime, :double,
# Selection help
:user_id, :post_id, :topic_id, :category_id, :group_id, :badge_id,
# Arrays
:int_list, :string_list, :user_list
)
end
def self.type_aliases
@type_aliases ||= {
integer: :int,
text: :string,
timestamp: :datetime,
}
end
def cast_to_ruby(string)
string = @default unless string
if string.blank?
if @nullable
return nil
else
raise DataExplorer::ValidationError.new("Missing parameter #{identifier} of type #{type}")
end
end
if string.downcase == '#null'
return nil
end
def invalid_format(string, msg = nil)
if msg
raise DataExplorer::ValidationError.new("'#{string}' is an invalid #{type} - #{msg}")
else
raise DataExplorer::ValidationError.new("'#{string}' is an invalid value for #{type}")
end
end
value = nil
case @type
when :int
invalid_format string, 'Not an integer' unless string =~ /^-?\d+$/
value = string.to_i
invalid_format string, 'Too large' unless Integer === value
when :bigint
invalid_format string, 'Not an integer' unless string =~ /^-?\d+$/
value = string.to_i
when :boolean
value = !!(string =~ /t|true|y|yes|1/i)
when :string
value = string
when :time
begin
value = Time.parse string
rescue ArgumentError => e
invalid_format string, e.message
end
when :date
begin
value = Date.parse string
rescue ArgumentError => e
invalid_format string, e.message
end
when :datetime
begin
value = DateTime.parse string
rescue ArgumentError => e
invalid_format string, e.message
end
when :double
if string =~ /-?\d*(\.\d+)/
value = Float(string)
elsif string =~ /^(-?)Inf(inity)?$/i
if $1
value = -Float::INFINITY
else
value = Float::INFINITY
end
elsif string =~ /^(-?)NaN$/i
if $1
value = -Float::NAN
else
value = Float::NAN
end
else
invalid_format string
end
when :category_id
if string =~ /(.*)\/(.*)/
parent_name = $1
child_name = $2
parent = Category.query_parent_category(parent_name)
invalid_format string, "Could not find category named #{parent_name}" unless parent
object = Category.query_category(child_name, parent)
invalid_format string, "Could not find subcategory of #{parent_name} named #{child_name}" unless object
else
object = Category.where(id: string.to_i).first || Category.where(slug: string).first || Category.where(name: string).first
invalid_format string, "Could not find category named #{string}" unless object
end
value = object.id
when :user_id, :post_id, :topic_id, :group_id, :badge_id
if string.gsub(/[ _]/, '') =~ /^-?\d+$/
clazz_name = (/^(.*)_id$/.match(type.to_s)[1].classify.to_sym)
begin
object = Object.const_get(clazz_name).with_deleted.find(string.gsub(/[ _]/, '').to_i)
value = object.id
rescue ActiveRecord::RecordNotFound
invalid_format string, "The specified #{clazz_name} was not found"
end
elsif type == :user_id
begin
object = User.find_by_username_or_email(string)
value = object.id
rescue ActiveRecord::RecordNotFound
invalid_format string, "The user named #{string} was not found"
end
elsif type == :post_id
if string =~ /(\d+)\/(\d+)(\?u=.*)?$/
object = Post.with_deleted.find_by(topic_id: $1, post_number: $2)
invalid_format string, "The post at topic:#{$1} post_number:#{$2} was not found" unless object
value = object.id
end
elsif type == :topic_id
if string =~ /\/t\/[^\/]+\/(\d+)/
begin
object = Topic.with_deleted.find($1)
value = object.id
rescue ActiveRecord::RecordNotFound
invalid_format string, "The topic with id #{$1} was not found"
end
end
elsif type == :group_id
object = Group.where(name: string).first
invalid_format string, "The group named #{string} was not found" unless object
value = object.id
else
invalid_format string
end
when :int_list
value = string.split(',').map { |s| s.downcase == '#null' ? nil : s.to_i }
invalid_format string, "can't be empty" if value.length == 0
when :string_list
value = string.split(',').map { |s| s.downcase == '#null' ? nil : s }
invalid_format string, "can't be empty" if value.length == 0
when :user_list
value = string.split(',').map { |s| User.find_by_username_or_email(s) }
invalid_format string, "can't be empty" if value.length == 0
else
raise TypeError.new('unknown parameter type??? should not get here')
end
value
end
def self.create_from_sql(sql, opts = {})
in_params = false
ret_params = []
sql.lines.find do |line|
line.chomp!
if in_params
# -- (ident) :(ident) (= (ident))?
if line =~ /^\s*--\s*([a-zA-Z_ ]+)\s*:([a-z_]+)\s*(?:=\s+(.*)\s*)?$/
type = $1
ident = $2
default = $3
nullable = false
if type =~ /^(null)?(.*?)(null)?$/i
if $1 || $3
nullable = true
end
type = $2
end
type = type.strip
begin
ret_params << DataExplorer::Parameter.new(ident, type, default, nullable)
rescue
if opts[:strict]
raise
end
end
false
elsif line =~ /^\s+$/
false
else
true
end
else
if line =~ /^\s*--\s*\[params\]\s*$/
in_params = true
end
false
end
end
ret_params
end
end
require_dependency 'application_controller'
require_dependency File.expand_path('../lib/queries.rb', __FILE__)
class DataExplorer::QueryController < ::ApplicationController
requires_plugin DataExplorer.plugin_name
before_action :check_enabled
before_action :set_group, only: [:group_reports_index, :group_reports_show, :group_reports_run]
before_action :set_query, only: [:group_reports_show, :group_reports_run]
attr_reader :group, :query
def check_enabled
raise Discourse::NotFound unless SiteSetting.data_explorer_enabled?
end
def set_group
@group = Group.find_by(name: params["group_name"])
end
def set_query
@query = DataExplorer::Query.find(params[:id].to_i)
end
def index
# guardian.ensure_can_use_data_explorer!
queries = DataExplorer::Query.all
Queries.default.each do |params|
query = DataExplorer::Query.new
query.id = params.second["id"]
query.sql = params.second["sql"]
query.name = params.second["name"]
query.description = params.second["description"]
query.created_by = Discourse::SYSTEM_USER_ID.to_s
# don't render this query if query with the same id already exists in pstore
queries.push(query) unless DataExplorer.pstore_get("q:#{query.id}").present?
end
render_serialized queries, DataExplorer::QuerySerializer, root: 'queries'
end
skip_before_action :check_xhr, only: [:show]
def show
check_xhr unless params[:export]
query = DataExplorer::Query.find(params[:id].to_i)
if params[:export]
response.headers['Content-Disposition'] = "attachment; filename=#{query.slug}.dcquery.json"
response.sending_file = true
end
# guardian.ensure_can_see! query
render_serialized query, DataExplorer::QuerySerializer, root: 'query'
end
def groups
render_serialized(Group.all, BasicGroupSerializer)
end
def group_reports_index
return raise Discourse::NotFound unless guardian.user_is_a_member_of_group?(group)
respond_to do |format|
format.html { render 'groups/show' }
format.json do
queries = DataExplorer::Query.all
queries.select! { |query| query.group_ids&.include?(group.id.to_s) }
render_serialized queries, DataExplorer::QuerySerializer, root: 'queries'
end
end
end
def group_reports_show
return raise Discourse::NotFound unless guardian.user_can_access_query?(group, query)
respond_to do |format|
format.html { render 'groups/show' }
format.json do
render_serialized query, DataExplorer::QuerySerializer, root: 'query'
end
end
end
skip_before_action :check_xhr, only: [:group_reports_run]
def group_reports_run
return raise Discourse::NotFound unless guardian.user_can_access_query?(group, query)
run
end
def create
# guardian.ensure_can_create_explorer_query!
query = DataExplorer::Query.from_hash params.require(:query)
query.created_at = Time.now
query.created_by = current_user.id.to_s
query.last_run_at = Time.now
query.id = nil # json import will assign an id, which is wrong
query.save
render_serialized query, DataExplorer::QuerySerializer, root: 'query'
end
def update
query = DataExplorer::Query.find(params[:id].to_i, ignore_deleted: true)
hash = params.require(:query)
hash[:group_ids] ||= []
# Undeleting
unless query.id
if hash[:id]
query.id = hash[:id].to_i
else
raise Discourse::NotFound
end
end
[:name, :sql, :description, :created_by, :created_at, :group_ids, :last_run_at].each do |sym|
query.send("#{sym}=", hash[sym]) if hash[sym]
end
query.check_params!
query.save
render_serialized query, DataExplorer::QuerySerializer, root: 'query'
rescue DataExplorer::ValidationError => e
render_json_error e.message
end
def destroy
query = DataExplorer::Query.find(params[:id].to_i)
query.destroy
render json: { success: true, errors: [] }
end
def schema
schema_version = DB.query_single("SELECT max(version) AS tag FROM schema_migrations").first
if stale?(public: true, etag: schema_version, template: false)
render json: DataExplorer.schema
end
end
skip_before_action :check_xhr, only: [:run]
# Return value:
# success - true/false. if false, inspect the errors value.
# errors - array of strings.
# params - hash. Echo of the query parameters as executed.
# duration - float. Time to execute the query, in milliseconds, to 1 decimal place.
# columns - array of strings. Titles of the returned columns, in order.
# explain - string. (Optional - pass explain=true in the request) Postgres query plan, UNIX newlines.
# rows - array of array of strings. Results of the query. In the same order as 'columns'.
def run
check_xhr unless params[:download]
query = DataExplorer::Query.find(params[:id].to_i)
query.last_run_at = Time.now
if params[:id].to_i < 0
query.created_by = Discourse::SYSTEM_USER_ID.to_s
query.save_default_query
else
query.save
end
if params[:download]
response.sending_file = true
end
params[:params] = params[:_params] if params[:_params] # testing workaround
query_params = {}
query_params = MultiJson.load(params[:params]) if params[:params]
opts = { current_user: current_user.username }
opts[:explain] = true if params[:explain] == "true"
opts[:limit] =
if params[:limit]
params[:limit].to_i
elsif params[:format] == "csv"
DataExplorer::QUERY_RESULT_MAX_LIMIT
elsif params[:limit] == "ALL"
"ALL"
end
result = DataExplorer.run_query(query, query_params, opts)
if result[:error]
err = result[:error]
# Pretty printing logic
err_class = err.class
err_msg = err.message
if err.is_a? ActiveRecord::StatementInvalid
err_class = err.original_exception.class
err_msg.gsub!("#{err_class}:", '')
else
err_msg = "#{err_class}: #{err_msg}"
end
render json: {
success: false,
errors: [err_msg]
}, status: 422
else
pg_result = result[:pg_result]
cols = pg_result.fields
respond_to do |format|
format.json do
if params[:download]
response.headers['Content-Disposition'] =
"attachment; filename=#{query.slug}@#{Slug.for(Discourse.current_hostname, 'discourse')}-#{Date.today}.dcqresult.json"
end
json = {
success: true,
errors: [],
duration: (result[:duration_secs].to_f * 1000).round(1),
result_count: pg_result.values.length || 0,
params: query_params,
columns: cols,
default_limit: DataExplorer::QUERY_RESULT_DEFAULT_LIMIT
}
json[:explain] = result[:explain] if opts[:explain]
if !params[:download]
relations, colrender = DataExplorer.add_extra_data(pg_result)
json[:relations] = relations
json[:colrender] = colrender
end
json[:rows] = pg_result.values
render json: json
end
format.csv do
response.headers['Content-Disposition'] =
"attachment; filename=#{query.slug}@#{Slug.for(Discourse.current_hostname, 'discourse')}-#{Date.today}.dcqresult.csv"
require 'csv'
text = CSV.generate do |csv|
csv << cols
pg_result.values.each do |row|
csv << row
end
end
render plain: text
end
end
end
end
end
class DataExplorer::QuerySerializer < ActiveModel::Serializer
attributes :id, :sql, :name, :description, :param_info, :created_by, :created_at, :username, :group_ids, :last_run_at
def param_info
object.params.map(&:to_hash) rescue nil
end
def username
User.find(created_by).username rescue nil
end
end
DataExplorer::Engine.routes.draw do
root to: "query#index"
get 'schema' => "query#schema"
get 'queries' => "query#index"
get 'groups' => "query#groups"
post 'queries' => "query#create"
get 'queries/:id' => "query#show"
put 'queries/:id' => "query#update"
delete 'queries/:id' => "query#destroy"
post 'queries/:id/run' => "query#run"
end
Discourse::Application.routes.append do
get '/g/:group_name/reports' => 'data_explorer/query#group_reports_index'
get '/g/:group_name/reports/:id' => 'data_explorer/query#group_reports_show'
post '/g/:group_name/reports/:id/run' => 'data_explorer/query#group_reports_run'
mount ::DataExplorer::Engine, at: '/admin/plugins/explorer', constraints: AdminConstraint.new
end
end
|
$:.push File.expand_path("../lib", __FILE__)
require "onix/version"
Gem::Specification.new do |s|
s.name = "milkfarm-onix"
s.version = ONIX::VERSION
s.summary = "A convient mapping between ruby objects and the ONIX XML specification"
s.description = "A fork of the original onix gem by James Healy. Differs from original mainly in it's adjustments for the US school/library market as applied in the product wrapper SLProduct."
s.authors = ["James Healy", "milkfarm productions"]
s.email = ["jimmy@deefa.com", "stuff@milkfarmproductions.com"]
s.has_rdoc = true
s.homepage = "http://github.com/milkfarm/onix"
s.rdoc_options << "--title" << "ONIX - Working with the ONIX XML spec" <<
"--line-numbers"
s.test_files = Dir.glob("spec/**/*.rb")
s.files = Dir.glob("{lib,support,dtd}/**/**/*") + ["README.markdown", "TODO", "CHANGELOG"]
s.add_dependency('roxml', '~>3.1.6')
s.add_dependency('i18n')
s.add_dependency('andand')
s.add_dependency('nokogiri', '>=1.4')
s.add_development_dependency("rake")
s.add_development_dependency("rspec", "~>2.1")
end
add dependency on activesupport 3
* the onix gem itself doesn't requite AS 3
* the roxml gem declares a dependency on AS 2.3 or higher, but actually
requires AS 3 or higher
* until a fixed version of roxml is release, let's compensate for them
$:.push File.expand_path("../lib", __FILE__)
require "onix/version"
Gem::Specification.new do |s|
s.name = "milkfarm-onix"
s.version = ONIX::VERSION
s.summary = "A convient mapping between ruby objects and the ONIX XML specification"
s.description = "A fork of the original onix gem by James Healy. Differs from original mainly in it's adjustments for the US school/library market as applied in the product wrapper SLProduct."
s.authors = ["James Healy", "milkfarm productions"]
s.email = ["jimmy@deefa.com", "stuff@milkfarmproductions.com"]
s.has_rdoc = true
s.homepage = "http://github.com/milkfarm/onix"
s.rdoc_options << "--title" << "ONIX - Working with the ONIX XML spec" <<
"--line-numbers"
s.test_files = Dir.glob("spec/**/*.rb")
s.files = Dir.glob("{lib,support,dtd}/**/**/*") + ["README.markdown", "TODO", "CHANGELOG"]
s.add_dependency('roxml', '~>3.1.6')
s.add_dependency('activesupport', '~> 3.0.5')
s.add_dependency('i18n')
s.add_dependency('andand')
s.add_dependency('nokogiri', '>=1.4')
s.add_development_dependency("rake")
s.add_development_dependency("rspec", "~>2.1")
end
|
# name: discourse_sso_redirect
# about: allows a whitelist for SSO login redirects
# version: 0.1
# authors: Gregory Avery-Weir
after_initialize do
SessionController.class_eval do
skip_before_filter :check_xhr, only: ['sso', 'sso_login', 'become', 'sso_provider', 'sso_redirect']
def sso_redirect
logger.info "Entering sso_redirect with query string #{request.query_string}"
redirect = Rack::Utils.parse_query(request.query_string).return_path
domains = SiteSetting.sso_redirect_domain_whitelist
# If it's not a relative URL check the host
if redirect !~ /^\/[^\/]/
begin
uri = URI(redirect)
redirect = "/" unless domains.split('|').include?(uri.host)
rescue
redirect = "/"
end
end
logger.info "About to redirect to #{redirect}"
redirect_to redirect
end
end
Rails.application.routes.draw do
get "session/sso_redirect" => "session#sso_redirect"
end
end
Try pointing route at known working action
# name: discourse_sso_redirect
# about: allows a whitelist for SSO login redirects
# version: 0.1
# authors: Gregory Avery-Weir
after_initialize do
SessionController.class_eval do
skip_before_filter :check_xhr, only: ['sso', 'sso_login', 'become', 'sso_provider', 'sso_redirect']
def sso_redirect
logger.info "Entering sso_redirect with query string #{request.query_string}"
redirect = Rack::Utils.parse_query(request.query_string).return_path
domains = SiteSetting.sso_redirect_domain_whitelist
# If it's not a relative URL check the host
if redirect !~ /^\/[^\/]/
begin
uri = URI(redirect)
redirect = "/" unless domains.split('|').include?(uri.host)
rescue
redirect = "/"
end
end
logger.info "About to redirect to #{redirect}"
redirect_to redirect
end
end
Rails.application.routes.draw do
get "session/sso_redirect" => "session#sso"
end
end
|
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "minitest-line"
s.version = "0.6.0"
s.date = "2014-03-25"
s.summary = "Focused tests for Minitest"
s.email = "judofyr@gmail.com"
s.homepage = "https://github.com/judofyr/minitest-line"
s.authors = ['Magnus Holm']
s.description = s.summary
s.files = Dir['{test,lib}/**/*']
s.test_files = Dir['test/**/*']
s.add_runtime_dependency('minitest', '~> 5.0')
end
Release v0.6.1
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "minitest-line"
s.version = "0.6.1"
s.date = "2014-03-25"
s.summary = "Focused tests for Minitest"
s.email = "judofyr@gmail.com"
s.homepage = "https://github.com/judofyr/minitest-line"
s.authors = ['Magnus Holm']
s.description = s.summary
s.files = Dir['{test,lib}/**/*']
s.test_files = Dir['test/**/*']
s.add_runtime_dependency('minitest', '~> 5.0')
end
|
#!/usr/bin/env ruby
#
require 'rubygems'
require 'bundler/setup'
require 'yaml'
require 'twitter'
require 'ostruct'
require 'optparse'
require 'json/pure'
require 'open-uri'
class PosterOptions
def self.parse(args)
options = OpenStruct.new
opts = OptionParser.new do |opts|
opts.banner = "Usage: poster <options>"
opts.on('-o', '--diff-only', "compare, but don't post") do
options.diff_only = true
end
opts.on('-d', '--directory DIR', 'directory for YAML') do |dir|
options.directory = dir
end
opts.on('-c', '--config FILE', 'config filename') do |file|
options.config_filename = file
end
opts.on('-v', '--verbose', 'increase verbosity') do
options.verbose = true
end
end
begin
opts.parse!(args)
rescue => e
puts e.message.capitalize + "\n\n"
puts opts
exit 1
end
# set a default config filename, and verify its existance
options.config_filename ||= File.join(File.dirname(__FILE__), 'config.yaml')
unless File.exists?(options.config_filename)
puts "You need to setup a config file."
puts "Please read the README."
exit 1
end
# set a default data directory location
options.directory ||= File.join(File.dirname(__FILE__), 'data')
options
end
end
class Poster
def initialize(opts={})
@diff_only = opts[:diff_only]
@data_directory = opts[:data_directory]
@config_filename = opts[:config_filename]
@verbose = opts[:verbose]
end
def load_data
@config = YAML::load(File.read(@config_filename))
@yamls = Dir.glob(File.expand_path(File.join(@data_directory, '*.yaml'))).sort
unless @yamls[-1] && @yamls[-2]
puts "Please run the fetcher again - need another dataset to compare against."
exit 1
end
@second_last = YAML::load(File.read(@yamls[-2]))
@last = YAML::load(File.read(@yamls[-1]))
end
def unprocessed?
@last[:meta][:processed?] != true
end
def changed?
if @verbose
puts "Second Latest: #{@yamls[-2]}"
puts "Latest: #{@yamls[-1]}"
end
# Filter out attrs that change frequently.
attr_whitelist = [:type, :status, :size, :council_name, :location, :incident_name]
last = @last[:incidents].map {|i| i.reject {|k,v| !attr_whitelist.include?(k) } }
second_last = @second_last[:incidents].map {|i| i.reject {|k,v| !attr_whitelist.include?(k) } }
# Get the list of new incidents. Remove MVAs.
@diff = (last - second_last).reject {|i| i[:type] =~ /motor\s*vehicle\s*accident/i }
if @verbose
puts "\nAttributes that are different:" if @diff.size > 0
@diff.each do |incident|
old_incident = second_last.find {|i| i[:incident_name] == incident[:incident_name] }
if old_incident
puts incident[:incident_name]
print "Before: "
p incident.reject {|k, v| v == old_incident[k]}
print "After: "
p old_incident.reject {|k, v| v == incident[k]}
else
puts incident[:incident_name]
puts "**New incident**"
end
puts
end
puts
end
updated = @diff.size == 0
modified = @last[:meta][:modified] != @second_last[:meta][:modified]
updated || modified
end
def authenticate
consumer_token = @config[:consumer_token]
consumer_secret = @config[:consumer_secret]
access_token = @config[:access_token]
access_secret = @config[:access_secret]
@oauth = Twitter::OAuth.new(consumer_token, consumer_secret)
begin
@oauth.authorize_from_access(access_token, access_secret)
rescue OAuth::Unauthorized => e
puts "Couldn't authenticate:"
p e
puts "Exiting."
exit
end
@twitter = Twitter::Base.new(@oauth)
end
def post_updates
@diff.each do |i|
if i[:status] =~ /patrol/i
puts "Updated #{i[:incident_name]}, but status is patrol."
next
end
i[:gmaps] = shorten_gmaps_url(:lat => i[:lat], :long => i[:long])
puts "Update to #{i[:incident_name]}"
msg = build_message(i)
if @diff_only
puts " - This would be posted to Twitter:"
puts " - \"#{msg}\""
else
puts " - posting to Twitter"
begin
@twitter.update(msg, :lat => i[:lat], :long => i[:long])
rescue SocketError
puts "Problem with networking: #{e.message}"
rescue Twitter::Unavailable, Twitter::InformTwitter => e
puts "Problem with Twitter: #{e.message}"
rescue Twitter::General => e
puts "Problem with tweet: #{e.message}"
end
end
puts
end
end
def shorten_gmaps_url(opts={})
if opts[:lat] && opts[:long]
api_key = "R_3215bce34570d671032a02d1075a0d94"
api_login = "nswbushfires"
gmaps_url = "http://maps.google.com.au/maps?q=#{opts[:lat]},#{opts[:long]}&z=9"
escaped_gmaps_url = URI.escape(gmaps_url, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
bitly_api_url = "http://api.bit.ly/shorten?apiKey=#{api_key}&login=#{api_login}&version=2.0.1&longUrl=#{escaped_gmaps_url}"
response = open(bitly_api_url).read
json = JSON.parse(response)
if json["errorCode"] == 0 && json["statusCode"] == "OK"
url = json["results"].keys.first
json["results"][url]["shortUrl"]
else
nil
end
end
end
def build_message(i)
msg = []
if i[:incident_name] =~ /unmapped/i
msg << "Council: #{i[:council_name]}"
else
msg << "Location: #{i[:location]}"
end
msg << "Type: #{i[:type]}"
msg << "Status: #{i[:status]}"
msg << "Size: #{i[:size]}"
msg << "Map: #{i[:gmaps]}" if i[:gmaps]
message = msg.join(', ')
if message.size > 140
(msg - [msg[3]]).join(', ')
else
message
end
#message = (msg - msg[3]).join(', ') if message.size > 140
end
def mark_as_processed
return if @diff_only
@last[:meta][:processed?] = true
File.open(@yamls[-1], 'w') do |f|
f << @last.to_yaml
end
end
def validate_config
%w(consumer_token consumer_secret access_token access_secret).each do |attr|
attr = attr.to_sym
@missing ||= []
@missing << attr unless @config[attr]
end
if @missing.size > 0
pretty_missing = @missing.map {|m| ":#{m}" }.join(', ')
puts "You need to specify #{pretty_missing} in #{@config_filename}"
exit 2
end
end
# entry point - you should only ever have to call this
def post
load_data
validate_config
if unprocessed? && changed?
authenticate
post_updates
mark_as_processed
end
end
end
options = PosterOptions.parse(ARGV)
poster = Poster.new(:data_directory => options.directory,
:config_filename => options.config_filename,
:verbose => options.verbose,
:diff_only => options.diff_only)
poster.post
exit
Reject any incidents that have the word 'vehicle' in them
#!/usr/bin/env ruby
#
require 'rubygems'
require 'bundler/setup'
require 'yaml'
require 'twitter'
require 'ostruct'
require 'optparse'
require 'json/pure'
require 'open-uri'
class PosterOptions
def self.parse(args)
options = OpenStruct.new
opts = OptionParser.new do |opts|
opts.banner = "Usage: poster <options>"
opts.on('-o', '--diff-only', "compare, but don't post") do
options.diff_only = true
end
opts.on('-d', '--directory DIR', 'directory for YAML') do |dir|
options.directory = dir
end
opts.on('-c', '--config FILE', 'config filename') do |file|
options.config_filename = file
end
opts.on('-v', '--verbose', 'increase verbosity') do
options.verbose = true
end
end
begin
opts.parse!(args)
rescue => e
puts e.message.capitalize + "\n\n"
puts opts
exit 1
end
# set a default config filename, and verify its existance
options.config_filename ||= File.join(File.dirname(__FILE__), 'config.yaml')
unless File.exists?(options.config_filename)
puts "You need to setup a config file."
puts "Please read the README."
exit 1
end
# set a default data directory location
options.directory ||= File.join(File.dirname(__FILE__), 'data')
options
end
end
class Poster
def initialize(opts={})
@diff_only = opts[:diff_only]
@data_directory = opts[:data_directory]
@config_filename = opts[:config_filename]
@verbose = opts[:verbose]
end
def load_data
@config = YAML::load(File.read(@config_filename))
@yamls = Dir.glob(File.expand_path(File.join(@data_directory, '*.yaml'))).sort
unless @yamls[-1] && @yamls[-2]
puts "Please run the fetcher again - need another dataset to compare against."
exit 1
end
@second_last = YAML::load(File.read(@yamls[-2]))
@last = YAML::load(File.read(@yamls[-1]))
end
def unprocessed?
@last[:meta][:processed?] != true
end
def changed?
if @verbose
puts "Second Latest: #{@yamls[-2]}"
puts "Latest: #{@yamls[-1]}"
end
# Filter out attrs that change frequently.
attr_whitelist = [:type, :status, :size, :council_name, :location, :incident_name]
last = @last[:incidents].map {|i| i.reject {|k,v| !attr_whitelist.include?(k) } }
second_last = @second_last[:incidents].map {|i| i.reject {|k,v| !attr_whitelist.include?(k) } }
# Get the list of new incidents. Remove MVAs.
@diff = (last - second_last).reject {|i| i[:type] =~ /vehicle/i }
if @verbose
puts "\nAttributes that are different:" if @diff.size > 0
@diff.each do |incident|
old_incident = second_last.find {|i| i[:incident_name] == incident[:incident_name] }
if old_incident
puts incident[:incident_name]
print "Before: "
p incident.reject {|k, v| v == old_incident[k]}
print "After: "
p old_incident.reject {|k, v| v == incident[k]}
else
puts incident[:incident_name]
puts "**New incident**"
end
puts
end
puts
end
updated = @diff.size == 0
modified = @last[:meta][:modified] != @second_last[:meta][:modified]
updated || modified
end
def authenticate
consumer_token = @config[:consumer_token]
consumer_secret = @config[:consumer_secret]
access_token = @config[:access_token]
access_secret = @config[:access_secret]
@oauth = Twitter::OAuth.new(consumer_token, consumer_secret)
begin
@oauth.authorize_from_access(access_token, access_secret)
rescue OAuth::Unauthorized => e
puts "Couldn't authenticate:"
p e
puts "Exiting."
exit
end
@twitter = Twitter::Base.new(@oauth)
end
def post_updates
@diff.each do |i|
if i[:status] =~ /patrol/i
puts "Updated #{i[:incident_name]}, but status is patrol."
next
end
i[:gmaps] = shorten_gmaps_url(:lat => i[:lat], :long => i[:long])
puts "Update to #{i[:incident_name]}"
msg = build_message(i)
if @diff_only
puts " - This would be posted to Twitter:"
puts " - \"#{msg}\""
else
puts " - posting to Twitter"
begin
@twitter.update(msg, :lat => i[:lat], :long => i[:long])
rescue SocketError
puts "Problem with networking: #{e.message}"
rescue Twitter::Unavailable, Twitter::InformTwitter => e
puts "Problem with Twitter: #{e.message}"
rescue Twitter::General => e
puts "Problem with tweet: #{e.message}"
end
end
puts
end
end
def shorten_gmaps_url(opts={})
if opts[:lat] && opts[:long]
api_key = "R_3215bce34570d671032a02d1075a0d94"
api_login = "nswbushfires"
gmaps_url = "http://maps.google.com.au/maps?q=#{opts[:lat]},#{opts[:long]}&z=9"
escaped_gmaps_url = URI.escape(gmaps_url, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
bitly_api_url = "http://api.bit.ly/shorten?apiKey=#{api_key}&login=#{api_login}&version=2.0.1&longUrl=#{escaped_gmaps_url}"
response = open(bitly_api_url).read
json = JSON.parse(response)
if json["errorCode"] == 0 && json["statusCode"] == "OK"
url = json["results"].keys.first
json["results"][url]["shortUrl"]
else
nil
end
end
end
def build_message(i)
msg = []
if i[:incident_name] =~ /unmapped/i
msg << "Council: #{i[:council_name]}"
else
msg << "Location: #{i[:location]}"
end
msg << "Type: #{i[:type]}"
msg << "Status: #{i[:status]}"
msg << "Size: #{i[:size]}"
msg << "Map: #{i[:gmaps]}" if i[:gmaps]
message = msg.join(', ')
if message.size > 140
(msg - [msg[3]]).join(', ')
else
message
end
#message = (msg - msg[3]).join(', ') if message.size > 140
end
def mark_as_processed
return if @diff_only
@last[:meta][:processed?] = true
File.open(@yamls[-1], 'w') do |f|
f << @last.to_yaml
end
end
def validate_config
%w(consumer_token consumer_secret access_token access_secret).each do |attr|
attr = attr.to_sym
@missing ||= []
@missing << attr unless @config[attr]
end
if @missing.size > 0
pretty_missing = @missing.map {|m| ":#{m}" }.join(', ')
puts "You need to specify #{pretty_missing} in #{@config_filename}"
exit 2
end
end
# entry point - you should only ever have to call this
def post
load_data
validate_config
if unprocessed? && changed?
authenticate
post_updates
mark_as_processed
end
end
end
options = PosterOptions.parse(ARGV)
poster = Poster.new(:data_directory => options.directory,
:config_filename => options.config_filename,
:verbose => options.verbose,
:diff_only => options.diff_only)
poster.post
exit
|
module CZTop
VERSION = "0.5.0"
end
prepare for 0.6.0
module CZTop
VERSION = "0.6.0"
end
|
module Daddy
VERSION = [
VERSION_MAJOR = '0',
VERSION_MINOR = '9',
VERSION_REVISION = '0'
].join('.')
end
bump up version
module Daddy
VERSION = [
VERSION_MAJOR = '0',
VERSION_MINOR = '9',
VERSION_REVISION = '1'
].join('.')
end
|
module Danger
# Checks the presence of Xcode file headers.
# This is done using the [clorox](https://pypi.python.org/pypi/clorox) python egg.
# Results are passed out as a list in markdown.
#
# @example Running clorox from current directory
#
# # clorox.check_files
#
# @example Running clorox from specific directories
#
# clorox.directories = ["MyApp", "MyAppTests", "MyAppExtension"]
# clorox.check_files
#
# @tags xcode, clorox, comments
#
class DangerClorox < Plugin
ROOT_DIR = "/tmp/danger_clorox"
EXECUTABLE = "#{ROOT_DIR}/clorox/clorox.py"
# Checks presence of file header comments. Will fail if `clorox` cannot be installed correctly.
# Generates a `markdown` list of dirty Objective-C and Swift files
#
# @param directories [Array<String>] Directories from where clorox will be run. Defaults to current dir.
# @return [void]
#
def check(directories=["."])
# Installs clorox if needed
system "pip install --target #{ROOT_DIR} clorox" unless clorox_installed?
# Check that this is in the user's PATH after installing
unless clorox_installed?
fail "clorox is not in the user's PATH, or it failed to install"
return
end
clorox_command = "python #{EXECUTABLE} "
clorox_command += "--path #{directories ? directories.join(' ') : '.'} "
clorox_command += "--inspection "
clorox_command += "--report json"
require 'json'
result = JSON.parse(`#{clorox_command}`)
result['files'].each { |file| warn("#{file} contains file header", sticky: false) } unless result['status'] == 'clean'
end
# Determine if clorox is currently installed in the system paths.
# @return [Bool]
#
def clorox_installed?
File.exists? EXECUTABLE
end
end
end
add log level
related to #10
module Danger
# Checks the presence of Xcode file headers.
# This is done using the [clorox](https://pypi.python.org/pypi/clorox) python egg.
# Results are passed out as a list in markdown.
#
# @example Running clorox from current directory
#
# # clorox.check_files
#
# @example Running clorox from specific directories
#
# clorox.directories = ["MyApp", "MyAppTests", "MyAppExtension"]
# clorox.check_files
#
# @tags xcode, clorox, comments
#
class DangerClorox < Plugin
ROOT_DIR = "/tmp/danger_clorox"
EXECUTABLE = "#{ROOT_DIR}/clorox/clorox.py"
LEVEL_WARNING = "warning"
LEVEL_FAILURE = "failure"
attr_accessor :level
# Checks presence of file header comments. Will fail if `clorox` cannot be installed correctly.
# Generates a `markdown` list of dirty Objective-C and Swift files
#
# @param directories [Array<String>] Directories from where clorox will be run. Defaults to current dir.
# @return [void]
#
def check(directories=["."])
# Installs clorox if needed
system "pip install --target #{ROOT_DIR} clorox" unless clorox_installed?
# Check that this is in the user's PATH after installing
unless clorox_installed?
fail "clorox is not in the user's PATH, or it failed to install"
return
end
clorox_command = "python #{EXECUTABLE} "
clorox_command += "--path #{directories ? directories.join(' ') : '.'} "
clorox_command += "--inspection "
clorox_command += "--report json"
require 'json'
result = JSON.parse(`#{clorox_command}`)
if result['status'] == 'dirty'
result['files'].each do |file|
message = "#{file} contains file header"
level == LEVEL_FAILURE ? fail(message) : warn(message)
end
end
end
# Determine if clorox is currently installed in the system paths.
# @return [Bool]
#
def clorox_installed?
File.exists? EXECUTABLE
end
end
end
|
module Dcgen
VERSION = "0.3.0"
end
bump version to 0.4.0
module Dcgen
VERSION = "0.4.0"
end
|
module Decco
VERSION = "0.0.1"
end
bump version, so I can push over the yanked version
module Decco
VERSION = "0.0.2"
end
|
require 'rest-client'
require 'faye/websocket'
require 'eventmachine'
require 'discordrb/events/message'
require 'discordrb/events/typing'
require 'discordrb/events/lifetime'
require 'discordrb/events/presence'
require 'discordrb/events/voice_state_update'
require 'discordrb/events/channel_create'
require 'discordrb/events/channel_update'
require 'discordrb/events/channel_delete'
require 'discordrb/events/members'
require 'discordrb/events/guild_role_create'
require 'discordrb/events/guild_role_delete'
require 'discordrb/events/guild_role_update'
require 'discordrb/events/guilds'
require 'discordrb/events/await'
require 'discordrb/events/bans'
require 'discordrb/api'
require 'discordrb/exceptions'
require 'discordrb/data'
require 'discordrb/await'
require 'discordrb/token_cache'
require 'discordrb/container'
require 'discordrb/voice/voice_bot'
module Discordrb
# Represents a Discord bot, including servers, users, etc.
class Bot
# The user that represents the bot itself. This version will always be identical to
# the user determined by {#user} called with the bot's ID.
# @return [User] The bot user.
attr_reader :bot_user
# The list of users the bot shares a server with.
# @return [Array<User>] The users.
attr_reader :users
# The list of servers the bot is currently in.
# @return [Array<Server>] The servers.
attr_reader :servers
# The list of currently running threads used to parse and call events.
# The threads will have a local variable `:discordrb_name` in the format of `et-1234`, where
# "et" stands for "event thread" and the number is a continually incrementing number representing
# how many events were executed before.
# @return [Array<Thread>] The threads.
attr_reader :event_threads
# The bot's user profile. This special user object can be used
# to edit user data like the current username (see {Profile#username=}).
# @return [Profile] The bot's profile that can be used to edit data.
attr_reader :profile
# Whether or not the bot should parse its own messages. Off by default.
attr_accessor :should_parse_self
# The bot's name which discordrb sends to Discord when making any request, so Discord can identify bots with the
# same codebase. Not required but I recommend setting it anyway.
attr_accessor :name
include EventContainer
# Makes a new bot with the given email and password. It will be ready to be added event handlers to and can eventually be run with {#run}.
# @param email [String] The email for your (or the bot's) Discord account.
# @param password [String] The valid password that should be used to log in to the account.
# @param debug [Boolean] Whether or not the bug should run in debug mode, which gives increased console output.
def initialize(email, password, debug = false)
# Make sure people replace the login details in the example files...
if email.end_with? 'example.com'
puts 'You have to replace the login details in the example files with your own!'
exit
end
LOGGER.debug = debug
@should_parse_self = false
@email = email
@password = password
@name = ''
debug('Creating token cache')
@token_cache = Discordrb::TokenCache.new
debug('Token cache created successfully')
@token = login
@channels = {}
@users = {}
@event_threads = []
@current_thread = 0
end
# The Discord API token received when logging in. Useful to explicitly call
# {API} methods.
# @return [String] The API token.
def token
API.bot_name = @name
@token
end
# Runs the bot, which logs into Discord and connects the WebSocket. This prevents all further execution unless it is executed with `async` = `:async`.
# @param async [Symbol] If it is `:async`, then the bot will allow further execution.
# It doesn't necessarily have to be that, anything truthy will work,
# however it is recommended to use `:async` for code readability reasons.
# If the bot is run in async mode, make sure to eventually run {#sync} so
# the script doesn't stop prematurely.
def run(async = false)
run_async
return if async
debug('Oh wait! Not exiting yet as run was run synchronously.')
sync
end
# Runs the bot asynchronously. Equivalent to #run with the :async parameter.
# @see #run
def run_async
# Handle heartbeats
@heartbeat_interval = 1
@heartbeat_active = false
@heartbeat_thread = Thread.new do
Thread.current[:discordrb_name] = 'heartbeat'
loop do
sleep @heartbeat_interval
send_heartbeat if @heartbeat_active
end
end
@ws_thread = Thread.new do
Thread.current[:discordrb_name] = 'websocket'
loop do
websocket_connect
debug('Disconnected! Attempting to reconnect in 5 seconds.')
sleep 5
@token = login
end
end
debug('WS thread created! Now waiting for confirmation that everything worked')
@ws_success = false
sleep(0.5) until @ws_success
debug('Confirmation received! Exiting run.')
end
# Prevents all further execution until the websocket thread stops (e. g. through a closed connection).
def sync
@ws_thread.join
end
# Kills the websocket thread, stopping all connections to Discord.
def stop
@ws_thread.kill
end
# Gets a channel given its ID. This queries the internal channel cache, and if the channel doesn't
# exist in there, it will get the data from Discord.
# @param id [Integer] The channel ID for which to search for.
# @return [Channel] The channel identified by the ID.
def channel(id)
id = id.resolve_id
debug("Obtaining data for channel with id #{id}")
return @channels[id] if @channels[id]
response = API.channel(token, id)
channel = Channel.new(JSON.parse(response), self)
@channels[id] = channel
end
# Creates a private channel for the given user ID, or if one exists already, returns that one.
# It is recommended that you use {User#pm} instead, as this is mainly for internal use. However,
# usage of this method may be unavoidable if only the user ID is known.
# @param id [Integer] The user ID to generate a private channel for.
# @return [Channel] A private channel for that user.
def private_channel(id)
id = id.resolve_id
debug("Creating private channel with user id #{id}")
return @private_channels[id] if @private_channels[id]
response = API.create_private(token, @bot_user.id, id)
channel = Channel.new(JSON.parse(response), self)
@private_channels[id] = channel
end
# Gets the code for an invite.
# @param invite [String, Invite] The invite to get the code for. Possible formats are:
#
# * An {Invite} object
# * The code for an invite
# * A fully qualified invite URL (e. g. `https://discordapp.com/invite/0A37aN7fasF7n83q`)
# * A short invite URL with protocol (e. g. `https://discord.gg/0A37aN7fasF7n83q`)
# * A short invite URL without protocol (e. g. `discord.gg/0A37aN7fasF7n83q`)
# @return [String] Only the code for the invite.
def resolve_invite_code(invite)
invite = invite.code if invite.is_a? Discordrb::Invite
invite = invite[invite.rindex('/') + 1..-1] if invite.start_with?('http', 'discord.gg')
invite
end
# Gets information about an invite.
# @param invite [String, Invite] The invite to join. For possible formats see {#resolve_invite_code}.
# @return [Invite] The invite with information about the given invite URL.
def invite(invite)
code = resolve_invite_code(invite)
Invite.new(JSON.parse(API.resolve_invite(token, code)), self)
end
# Makes the bot join an invite to a server.
# @param invite [String, Invite] The invite to join. For possible formats see {#resolve_invite_code}.
def join(invite)
resolved = invite(invite).code
API.join_server(token, resolved)
end
attr_reader :voice
# Connects to a voice channel, initializes network connections and returns the {Voice::VoiceBot} over which audio
# data can then be sent. After connecting, the bot can also be accessed using {#voice}.
# @param chan [Channel] The voice channel to connect to.
# @param encrypted [true, false] Whether voice communication should be encrypted using RbNaCl's SecretBox
# (uses an XSalsa20 stream cipher for encryption and Poly1305 for authentication)
# @return [Voice::VoiceBot] the initialized bot over which audio data can then be sent.
def voice_connect(chan, encrypted = true)
if @voice
debug('Voice bot exists already! Destroying it')
@voice.destroy
@voice = nil
end
chan = channel(chan.resolve_id)
@voice_channel = chan
@should_encrypt_voice = encrypted
debug("Got voice channel: #{@voice_channel}")
data = {
op: 4,
d: {
guild_id: @voice_channel.server.id.to_s,
channel_id: @voice_channel.id.to_s,
self_mute: false,
self_deaf: false
}
}
debug("Voice channel init packet is: #{data.to_json}")
@should_connect_to_voice = true
@ws.send(data.to_json)
debug('Voice channel init packet sent! Now waiting.')
sleep(0.05) until @voice
debug('Voice connect succeeded!')
@voice
end
# Revokes an invite to a server. Will fail unless you have the *Manage Server* permission.
# It is recommended that you use {Invite#delete} instead.
# @param code [String, Invite] The invite to revoke. For possible formats see {#resolve_invite_code}.
def delete_invite(code)
invite = resolve_invite_code(code)
API.delete_invite(token, invite)
end
# Gets a user by its ID.
# @note This can only resolve users known by the bot (i.e. that share a server with the bot).
# @param id [Integer] The user ID that should be resolved.
# @return [User, nil] The user identified by the ID, or `nil` if it couldn't be found.
def user(id)
id = id.resolve_id
@users[id]
end
# Gets a server by its ID.
# @note This can only resolve servers the bot is currently in.
# @param id [Integer] The server ID that should be resolved.
# @return [Server, nil] The server identified by the ID, or `nil` if it couldn't be found.
def server(id)
id = id.resolve_id
@servers[id]
end
# Finds a channel given its name and optionally the name of the server it is in. If the threshold
# is not 0, it will use a Levenshtein distance function to find the channel in a fuzzy way, which
# allows slight misspellings.
# @param channel_name [String] The channel to search for.
# @param server_name [String] The server to search for, or `nil` if only the channel should be searched for.
# @param threshold [Integer] The threshold for the Levenshtein algorithm. The larger
# the threshold is, the more misspellings will be allowed.
# @return [Array<Channel>] The array of channels that were found. May be empty if none were found.
def find(channel_name, server_name = nil, threshold = 0)
begin
require 'levenshtein' if threshold > 0
levenshtein_available = true
rescue LoadError; levenshtein_available = false; end
results = []
@servers.values.each do |server|
server.channels.each do |channel|
if threshold > 0
fail LoadError, 'Levenshtein distance unavailable! Either set threshold to 0 or install the `levenshtein-ffi` gem' unless levenshtein_available
distance = Levenshtein.distance(channel.name, channel_name)
distance += Levenshtein.distance(server_name || server.name, server.name)
next if distance > threshold
else
distance = 0
next if channel.name != channel_name || (server_name || server.name) != server.name
end
# Make a singleton accessor "distance"
channel.instance_variable_set(:@distance, distance)
class << channel
attr_reader :distance
end
results << channel
end
end
results
end
# Finds a user given its username. This allows fuzzy finding using Levenshtein
# distances, see {#find}
# @param username [String] The username to look for.
# @param threshold [Integer] The threshold for the Levenshtein algorithm. The larger
# the threshold is, the more misspellings will be allowed.
# @return [Array<User>] The array of users that were found. May be empty if none were found.
def find_user(username, threshold = 0)
begin
require 'levenshtein' if threshold > 0
levenshtein_available = true
rescue LoadError; levenshtein_available = false; end
results = []
@users.values.each do |user|
if threshold > 0
fail LoadError, 'Levenshtein distance unavailable! Either set threshold to 0 or install the `levenshtein-ffi` gem' unless levenshtein_available
distance = Levenshtein.distance(user.username, username)
next if distance > threshold
else
distance = 0
next if user.username != username
end
# Make a singleton accessor "distance"
user.instance_variable_set(:@distance, distance)
class << user
attr_reader :distance
end
results << user
end
results
end
# Sends a text message to a channel given its ID and the message's content.
# @param channel_id [Integer] The ID that identifies the channel to send something to.
# @param content [String] The text that should be sent as a message. It is limited to 2000 characters (Discord imposed).
# @return [Message] The message that was sent.
def send_message(channel_id, content)
debug("Sending message to #{channel_id} with content '#{content}'")
response = API.send_message(token, channel_id, content)
Message.new(JSON.parse(response), self)
end
# Sends a file to a channel. If it is an image, it will automatically be embedded.
# @note This executes in a blocking way, so if you're sending long files, be wary of delays.
# @param channel_id [Integer] The ID that identifies the channel to send something to.
# @param file [File] The file that should be sent.
def send_file(channel_id, file)
response = API.send_file(token, channel_id, file)
Message.new(JSON.parse(response), self)
end
# Creates a server on Discord with a specified name and a region.
# @note Discord's API doesn't directly return the server when creating it, so this method
# waits until the data has been received via the websocket. This may make the execution take a while.
# @param name [String] The name the new server should have. Doesn't have to be alphanumeric.
# @param region [Symbol] The region where the server should be created. Possible regions are:
#
# * `:london`
# * `:amsterdam`
# * `:frankfurt`
# * `:us-east`
# * `:us-west`
# * `:singapore`
# * `:sydney`
# @return [Server] The server that was created.
def create_server(name, region = :london)
response = API.create_server(token, name, region)
id = JSON.parse(response)['id'].to_i
sleep 0.1 until @servers[id]
server = @servers[id]
debug "Successfully created server #{server.id} with name #{server.name}"
server
end
# Gets the user from a mention of the user.
# @param mention [String] The mention, which should look like <@12314873129>.
# @return [User] The user identified by the mention, or `nil` if none exists.
def parse_mention(mention)
# Mention format: <@id>
return nil unless /<@(?<id>\d+)>?/ =~ mention
user(id.to_i)
end
# Sets the currently playing game to the specified game.
# @param name [String] The name of the game to be played.
# @return [String] The game that is being played now.
def game=(name)
@game = name
data = {
op: 3,
d: {
idle_since: nil,
game: name ? { name: name } : nil
}
}
@ws.send(data.to_json)
name
end
# Sets debug mode. If debug mode is on, many things will be outputted to STDOUT.
def debug=(new_debug)
LOGGER.debug = new_debug
end
# Prevents the READY packet from being printed regardless of debug mode.
def suppress_ready_debug
@prevent_ready = true
end
# Add an await the bot should listen to. For information on awaits, see {Await}.
# @param key [Symbol] The key that uniquely identifies the await for {AwaitEvent}s to listen to (see {#await}).
# @param type [Class] The event class that should be listened for.
# @param attributes [Hash] The attributes the event should check for. The block will only be executed if all attributes match.
# @yield Is executed when the await is triggered.
# @yieldparam event [Event] The event object that was triggered.
# @return [Await] The await that was created.
def add_await(key, type, attributes = {}, &block)
fail "You can't await an AwaitEvent!" if type == Discordrb::Events::AwaitEvent
await = Await.new(self, key, type, attributes, block)
@awaits ||= {}
@awaits[key] = await
end
# @see Logger#debug
def debug(message, important = false)
LOGGER.debug(message, important)
end
# @see Logger#log_exception
def log_exception(e)
LOGGER.log_exception(e)
end
private
####### ### ###### ## ## ########
## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ##
## ## ## ## ######### ######
## ######### ## ## ## ##
## ## ## ## ## ## ## ## ##
####### ## ## ###### ## ## ########
def add_server(data)
server = Server.new(data, self)
@servers[server.id] = server
# Initialize users
server.members.each do |member|
if @users[member.id]
# If the user is already cached, just add the new roles
@users[member.id].merge_roles(server, member.roles[server.id])
else
@users[member.id] = member
end
end
server
end
### ## ## ######## ######## ######## ## ## ### ## ######
## ### ## ## ## ## ## ### ## ## ## ## ## ##
## #### ## ## ## ## ## #### ## ## ## ## ##
## ## ## ## ## ###### ######## ## ## ## ## ## ## ######
## ## #### ## ## ## ## ## #### ######### ## ##
## ## ### ## ## ## ## ## ### ## ## ## ## ##
### ## ## ## ######## ## ## ## ## ## ## ######## ######
# Internal handler for PRESENCE_UPDATE
def update_presence(data)
user_id = data['user']['id'].to_i
server_id = data['guild_id'].to_i
server = @servers[server_id]
return unless server
user = @users[user_id]
unless user
user = User.new(data['user'], self)
@users[user_id] = user
end
status = data['status'].to_sym
if status != :offline
unless server.members.find { |u| u.id == user.id }
server.members << user
end
end
user.status = status
user.game = data['game'] ? data['game']['name'] : nil
user
end
# Internal handler for VOICE_STATUS_UPDATE
def update_voice_state(data)
user_id = data['user_id'].to_i
server_id = data['guild_id'].to_i
server = @servers[server_id]
return unless server
user = @users[user_id]
user.server_mute = data['mute']
user.server_deaf = data['deaf']
user.self_mute = data['self_mute']
user.self_deaf = data['self_deaf']
channel_id = data['channel_id']
channel = nil
channel = @channels[channel_id.to_i] if channel_id
user.move(channel)
@session_id = data['session_id']
end
# Internal handler for VOICE_SERVER_UPDATE
def update_voice_server(data)
debug("Voice server update received! should connect: #{@should_connect_to_voice}")
return unless @should_connect_to_voice
@should_connect_to_voice = false
debug('Updating voice server!')
token = data['token']
endpoint = data['endpoint']
channel = @voice_channel
debug('Got data, now creating the bot.')
@voice = Discordrb::Voice::VoiceBot.new(channel, self, token, @session_id, endpoint, @should_encrypt_voice)
end
# Internal handler for CHANNEL_CREATE
def create_channel(data)
channel = Channel.new(data, self)
server = channel.server
server.channels << channel
@channels[channel.id] = channel
end
# Internal handler for CHANNEL_UPDATE
def update_channel(data)
channel = Channel.new(data, self)
old_channel = @channels[channel.id]
return unless old_channel
old_channel.update_from(channel)
end
# Internal handler for CHANNEL_DELETE
def delete_channel(data)
channel = Channel.new(data, self)
server = channel.server
@channels[channel.id] = nil
server.channels.reject! { |c| c.id == channel.id }
end
# Internal handler for GUILD_MEMBER_ADD
def add_guild_member(data)
user = User.new(data['user'], self)
server_id = data['guild_id'].to_i
server = @servers[server_id]
roles = []
data['roles'].each do |element|
role_id = element.to_i
roles << server.roles.find { |r| r.id == role_id }
end
user.update_roles(server, roles)
if @users[user.id]
# If the user is already cached, just add the new roles
@users[user.id].merge_roles(server, user.roles[server.id])
else
@users[user.id] = user
end
server.add_user(user)
end
# Internal handler for GUILD_MEMBER_UPDATE
def update_guild_member(data)
user_id = data['user']['id'].to_i
user = @users[user_id]
server_id = data['guild_id'].to_i
server = @servers[server_id]
roles = []
data['roles'].each do |element|
role_id = element.to_i
roles << server.roles.find { |r| r.id == role_id }
end
user.update_roles(server, roles)
end
# Internal handler for GUILD_MEMBER_DELETE
def delete_guild_member(data)
user_id = data['user']['id'].to_i
user = @users[user_id]
server_id = data['guild_id'].to_i
server = @servers[server_id]
user.delete_roles(server_id)
server.delete_user(user_id)
end
# Internal handler for GUILD_CREATE
def create_guild(data)
add_server(data)
end
# Internal handler for GUILD_UPDATE
def update_guild(data)
@servers[data['id'].to_i].update_data(data)
end
# Internal handler for GUILD_DELETE
def delete_guild(data)
id = data['id'].to_i
@users.each do |_, user|
user.delete_roles(id)
end
@servers.delete(id)
end
# Internal handler for GUILD_ROLE_UPDATE
def update_guild_role(data)
role_data = data['role']
server_id = data['guild_id'].to_i
server = @servers[server_id]
new_role = Role.new(role_data, self, server)
role_id = role_data['id'].to_i
old_role = server.roles.find { |r| r.id == role_id }
old_role.update_from(new_role)
end
# Internal handler for GUILD_ROLE_CREATE
def create_guild_role(data)
role_data = data['role']
server_id = data['guild_id'].to_i
server = @servers[server_id]
new_role = Role.new(role_data, self, server)
server.add_role(new_role)
end
# Internal handler for GUILD_ROLE_DELETE
def delete_guild_role(data)
role_id = data['role_id'].to_i
server_id = data['guild_id'].to_i
server = @servers[server_id]
server.delete_role(role_id)
end
# Internal handler for MESSAGE_CREATE
def create_message(data); end
# Internal handler for TYPING_START
def start_typing(data); end
# Internal handler for MESSAGE_UPDATE
def update_message(data); end
# Internal handler for MESSAGE_DELETE
def delete_message(data); end
# Internal handler for GUILD_BAN_ADD
def add_user_ban(data); end
# Internal handler for GUILD_BAN_REMOVE
def remove_user_ban(data); end
## ####### ###### #### ## ##
## ## ## ## ## ## ### ##
## ## ## ## ## #### ##
## ## ## ## #### ## ## ## ##
## ## ## ## ## ## ## ####
## ## ## ## ## ## ## ###
######## ####### ###### #### ## ##
def login
debug('Logging in')
login_attempts ||= 0
# First, attempt to get the token from the cache
token = @token_cache.token(@email, @password)
if token
debug('Token successfully obtained from cache!')
return token
end
# Login
login_response = API.login(@email, @password)
fail HTTPStatusException, login_response.code if login_response.code >= 400
# Parse response
login_response_object = JSON.parse(login_response)
fail InvalidAuthenticationException unless login_response_object['token']
debug('Received token from Discord!')
# Cache the token
@token_cache.store_token(@email, @password, login_response_object['token'])
login_response_object['token']
rescue Exception => e
response_code = login_response.nil? ? 0 : login_response.code ######## mackmm145
if login_attempts < 100 && (e.inspect.include?('No such host is known.') || response_code == 523)
debug("Login failed! Reattempting in 5 seconds. #{100 - login_attempts} attempts remaining.")
debug("Error was: #{e.inspect}")
sleep 5
login_attempts += 1
retry
else
debug("Login failed permanently after #{login_attempts + 1} attempts")
# Apparently we get a 400 if the password or username is incorrect. In that case, tell the user
debug("Are you sure you're using the correct username and password?") if e.class == RestClient::BadRequest
log_exception(e)
raise $ERROR_INFO
end
end
def find_gateway
# Get updated websocket_hub
response = API.gateway(token)
JSON.parse(response)['url']
end
## ## ###### ######## ## ## ######## ## ## ######## ######
## ## ## ## ## ## ## ## ## ### ## ## ## ##
## ## ## ## ## ## ## ## #### ## ## ##
## ## ## ###### ###### ## ## ###### ## ## ## ## ######
## ## ## ## ## ## ## ## ## #### ## ##
## ## ## ## ## ## ## ## ## ## ### ## ## ##
#### ### ###### ######## ### ######## ## ## ## ######
def websocket_connect
debug('Attempting to get gateway URL...')
websocket_hub = find_gateway
debug("Success! Gateway URL is #{websocket_hub}.")
debug('Now running bot')
EM.run do
@ws = Faye::WebSocket::Client.new(websocket_hub)
@ws.on(:open) { |event| websocket_open(event) }
@ws.on(:message) { |event| websocket_message(event) }
@ws.on(:error) { |event| debug(event.message) }
@ws.on :close do |event|
websocket_close(event)
@ws = nil
end
end
end
def websocket_message(event)
# Parse packet
packet = JSON.parse(event.data)
if @prevent_ready && packet['t'] == 'READY'
debug('READY packet was received and suppressed')
elsif @prevent_ready && packet['t'] == 'GUILD_MEMBERS_CHUNK'
# Ignore chunks as they will be handled later anyway
else
debug("Received packet #{event.data}")
end
fail 'Invalid Packet' unless packet['op'] == 0 # TODO
data = packet['d']
case packet['t']
when 'READY'
# Activate the heartbeats
@heartbeat_interval = data['heartbeat_interval'].to_f / 1000.0
@heartbeat_active = true
debug("Desired heartbeat_interval: #{@heartbeat_interval}")
bot_user_id = data['user']['id'].to_i
@profile = Profile.new(data['user'], self, @email, @password)
# Initialize servers
@servers = {}
data['guilds'].each do |element|
add_server(element)
# Save the bot user
@bot_user = @users[bot_user_id]
end
# Add private channels
@private_channels = {}
data['private_channels'].each do |element|
channel = Channel.new(element, self)
@channels[channel.id] = channel
@private_channels[channel.recipient.id] = channel
end
# Make sure to raise the event
raise_event(ReadyEvent.new)
# Afterwards, send out a members request to get the chunk data
chunk_packet = {
op: 8,
d: {
guild_id: @servers.keys,
query: '',
limit: 0
}
}.to_json
@ws.send(chunk_packet)
# Tell the run method that everything was successful
@ws_success = true
when 'GUILD_MEMBERS_CHUNK'
id = data['guild_id'].to_i
members = data['members']
start_time = Time.now
members.each do |member|
# Add the guild_id to the member so we can reuse add_guild_member
member['guild_id'] = id
add_guild_member(member)
end
duration = Time.now - start_time
if members.length < 1000
debug "Got final chunk for server #{id}, parsing took #{duration} seconds"
else
debug "Got one chunk for server #{id}, parsing took #{duration} seconds"
end
when 'MESSAGE_CREATE'
create_message(data)
message = Message.new(data, self)
return if message.from_bot? && !should_parse_self
event = MessageEvent.new(message, self)
raise_event(event)
if message.mentions.any? { |user| user.id == @bot_user.id }
event = MentionEvent.new(message, self)
raise_event(event)
end
if message.channel.private?
event = PrivateMessageEvent.new(message, self)
raise_event(event)
end
when 'MESSAGE_UPDATE'
update_message(data)
event = MessageEditEvent.new(data, self)
raise_event(event)
when 'MESSAGE_DELETE'
delete_message(data)
event = MessageDeleteEvent.new(data, self)
raise_event(event)
when 'TYPING_START'
start_typing(data)
event = TypingEvent.new(data, self)
raise_event(event)
when 'PRESENCE_UPDATE'
now_playing = data['game']
played_before = user(data['user']['id'].to_i).game
update_presence(data)
event = if now_playing != played_before
PlayingEvent.new(data, self)
else
PresenceEvent.new(data, self)
end
raise_event(event)
when 'VOICE_STATE_UPDATE'
update_voice_state(data)
event = VoiceStateUpdateEvent.new(data, self)
raise_event(event)
when 'VOICE_SERVER_UPDATE'
update_voice_server(data)
# no event as this is irrelevant to users
when 'CHANNEL_CREATE'
create_channel(data)
event = ChannelCreateEvent.new(data, self)
raise_event(event)
when 'CHANNEL_UPDATE'
update_channel(data)
event = ChannelUpdateEvent.new(data, self)
raise_event(event)
when 'CHANNEL_DELETE'
delete_channel(data)
event = ChannelDeleteEvent.new(data, self)
raise_event(event)
when 'GUILD_MEMBER_ADD'
add_guild_member(data)
event = GuildMemberAddEvent.new(data, self)
raise_event(event)
when 'GUILD_MEMBER_UPDATE'
update_guild_member(data)
event = GuildMemberUpdateEvent.new(data, self)
raise_event(event)
when 'GUILD_MEMBER_REMOVE'
delete_guild_member(data)
event = GuildMemberDeleteEvent.new(data, self)
raise_event(event)
when 'GUILD_BAN_ADD'
add_user_ban(data)
event = UserBanEvent.new(data, self)
raise_event(event)
when 'GUILD_BAN_REMOVE'
remove_user_ban(data)
event = UserUnbanEvent.new(data, self)
raise_event(event)
when 'GUILD_ROLE_UPDATE'
update_guild_role(data)
event = GuildRoleUpdateEvent.new(data, self)
raise_event(event)
when 'GUILD_ROLE_CREATE'
create_guild_role(data)
event = GuildRoleCreateEvent.new(data, self)
raise_event(event)
when 'GUILD_ROLE_DELETE'
delete_guild_role(data)
event = GuildRoleDeleteEvent.new(data, self)
raise_event(event)
when 'GUILD_CREATE'
create_guild(data)
event = GuildCreateEvent.new(data, self)
raise_event(event)
when 'GUILD_UPDATE'
update_guild(data)
event = GuildUpdateEvent.new(data, self)
raise_event(event)
when 'GUILD_DELETE'
delete_guild(data)
event = GuildDeleteEvent.new(data, self)
raise_event(event)
else
# another event that we don't support yet
debug "Event #{packet['t']} has been received but is unsupported, ignoring"
end
rescue Exception => e
log_exception(e)
end
def websocket_close(event)
debug('Disconnected from WebSocket!')
debug(" (Reason: #{event.reason})")
debug(" (Code: #{event.code})")
raise_event(DisconnectEvent.new)
EM.stop
end
def websocket_open(_)
# Send the initial packet
packet = {
op: 2, # Packet identifier
d: { # Packet data
v: 2, # Another identifier
token: @token,
properties: { # I'm unsure what these values are for exactly, but they don't appear to impact bot functionality in any way.
:'$os' => RUBY_PLATFORM.to_s,
:'$browser' => 'discordrb',
:'$device' => 'discordrb',
:'$referrer' => '',
:'$referring_domain' => ''
},
large_threshold: 100
}
}
@ws.send(packet.to_json)
end
def send_heartbeat
millis = Time.now.strftime('%s%L').to_i
debug("Sending heartbeat at #{millis}")
data = {
op: 1,
d: millis
}
@ws.send(data.to_json)
end
def raise_event(event)
debug("Raised a #{event.class}")
handle_awaits(event)
@event_handlers ||= {}
handlers = @event_handlers[event.class]
(handlers || []).each do |handler|
call_event(handler, event) if handler.matches?(event)
end
end
def call_event(handler, event)
t = Thread.new do
@event_threads ||= []
@current_thread ||= 0
@event_threads << t
Thread.current[:discordrb_name] = "et-#{@current_thread += 1}"
begin
handler.call(event)
handler.after_call(event)
rescue => e
log_exception(e)
ensure
@event_threads.delete(t)
end
end
end
def handle_awaits(event)
@awaits ||= {}
@awaits.each do |_, await|
key, should_delete = await.match(event)
next unless key
debug("should_delete: #{should_delete}")
@awaits.delete(await.key) if should_delete
await_event = Discordrb::Events::AwaitEvent.new(await, event, self)
raise_event(await_event)
end
end
end
end
Use WS protocol version 3, fixes #53
require 'rest-client'
require 'faye/websocket'
require 'eventmachine'
require 'discordrb/events/message'
require 'discordrb/events/typing'
require 'discordrb/events/lifetime'
require 'discordrb/events/presence'
require 'discordrb/events/voice_state_update'
require 'discordrb/events/channel_create'
require 'discordrb/events/channel_update'
require 'discordrb/events/channel_delete'
require 'discordrb/events/members'
require 'discordrb/events/guild_role_create'
require 'discordrb/events/guild_role_delete'
require 'discordrb/events/guild_role_update'
require 'discordrb/events/guilds'
require 'discordrb/events/await'
require 'discordrb/events/bans'
require 'discordrb/api'
require 'discordrb/exceptions'
require 'discordrb/data'
require 'discordrb/await'
require 'discordrb/token_cache'
require 'discordrb/container'
require 'discordrb/voice/voice_bot'
module Discordrb
# Represents a Discord bot, including servers, users, etc.
class Bot
# The user that represents the bot itself. This version will always be identical to
# the user determined by {#user} called with the bot's ID.
# @return [User] The bot user.
attr_reader :bot_user
# The list of users the bot shares a server with.
# @return [Array<User>] The users.
attr_reader :users
# The list of servers the bot is currently in.
# @return [Array<Server>] The servers.
attr_reader :servers
# The list of currently running threads used to parse and call events.
# The threads will have a local variable `:discordrb_name` in the format of `et-1234`, where
# "et" stands for "event thread" and the number is a continually incrementing number representing
# how many events were executed before.
# @return [Array<Thread>] The threads.
attr_reader :event_threads
# The bot's user profile. This special user object can be used
# to edit user data like the current username (see {Profile#username=}).
# @return [Profile] The bot's profile that can be used to edit data.
attr_reader :profile
# Whether or not the bot should parse its own messages. Off by default.
attr_accessor :should_parse_self
# The bot's name which discordrb sends to Discord when making any request, so Discord can identify bots with the
# same codebase. Not required but I recommend setting it anyway.
attr_accessor :name
include EventContainer
# Makes a new bot with the given email and password. It will be ready to be added event handlers to and can eventually be run with {#run}.
# @param email [String] The email for your (or the bot's) Discord account.
# @param password [String] The valid password that should be used to log in to the account.
# @param debug [Boolean] Whether or not the bug should run in debug mode, which gives increased console output.
def initialize(email, password, debug = false)
# Make sure people replace the login details in the example files...
if email.end_with? 'example.com'
puts 'You have to replace the login details in the example files with your own!'
exit
end
LOGGER.debug = debug
@should_parse_self = false
@email = email
@password = password
@name = ''
debug('Creating token cache')
@token_cache = Discordrb::TokenCache.new
debug('Token cache created successfully')
@token = login
@channels = {}
@users = {}
@event_threads = []
@current_thread = 0
end
# The Discord API token received when logging in. Useful to explicitly call
# {API} methods.
# @return [String] The API token.
def token
API.bot_name = @name
@token
end
# Runs the bot, which logs into Discord and connects the WebSocket. This prevents all further execution unless it is executed with `async` = `:async`.
# @param async [Symbol] If it is `:async`, then the bot will allow further execution.
# It doesn't necessarily have to be that, anything truthy will work,
# however it is recommended to use `:async` for code readability reasons.
# If the bot is run in async mode, make sure to eventually run {#sync} so
# the script doesn't stop prematurely.
def run(async = false)
run_async
return if async
debug('Oh wait! Not exiting yet as run was run synchronously.')
sync
end
# Runs the bot asynchronously. Equivalent to #run with the :async parameter.
# @see #run
def run_async
# Handle heartbeats
@heartbeat_interval = 1
@heartbeat_active = false
@heartbeat_thread = Thread.new do
Thread.current[:discordrb_name] = 'heartbeat'
loop do
sleep @heartbeat_interval
send_heartbeat if @heartbeat_active
end
end
@ws_thread = Thread.new do
Thread.current[:discordrb_name] = 'websocket'
loop do
websocket_connect
debug('Disconnected! Attempting to reconnect in 5 seconds.')
sleep 5
@token = login
end
end
debug('WS thread created! Now waiting for confirmation that everything worked')
@ws_success = false
sleep(0.5) until @ws_success
debug('Confirmation received! Exiting run.')
end
# Prevents all further execution until the websocket thread stops (e. g. through a closed connection).
def sync
@ws_thread.join
end
# Kills the websocket thread, stopping all connections to Discord.
def stop
@ws_thread.kill
end
# Gets a channel given its ID. This queries the internal channel cache, and if the channel doesn't
# exist in there, it will get the data from Discord.
# @param id [Integer] The channel ID for which to search for.
# @return [Channel] The channel identified by the ID.
def channel(id)
id = id.resolve_id
debug("Obtaining data for channel with id #{id}")
return @channels[id] if @channels[id]
response = API.channel(token, id)
channel = Channel.new(JSON.parse(response), self)
@channels[id] = channel
end
# Creates a private channel for the given user ID, or if one exists already, returns that one.
# It is recommended that you use {User#pm} instead, as this is mainly for internal use. However,
# usage of this method may be unavoidable if only the user ID is known.
# @param id [Integer] The user ID to generate a private channel for.
# @return [Channel] A private channel for that user.
def private_channel(id)
id = id.resolve_id
debug("Creating private channel with user id #{id}")
return @private_channels[id] if @private_channels[id]
response = API.create_private(token, @bot_user.id, id)
channel = Channel.new(JSON.parse(response), self)
@private_channels[id] = channel
end
# Gets the code for an invite.
# @param invite [String, Invite] The invite to get the code for. Possible formats are:
#
# * An {Invite} object
# * The code for an invite
# * A fully qualified invite URL (e. g. `https://discordapp.com/invite/0A37aN7fasF7n83q`)
# * A short invite URL with protocol (e. g. `https://discord.gg/0A37aN7fasF7n83q`)
# * A short invite URL without protocol (e. g. `discord.gg/0A37aN7fasF7n83q`)
# @return [String] Only the code for the invite.
def resolve_invite_code(invite)
invite = invite.code if invite.is_a? Discordrb::Invite
invite = invite[invite.rindex('/') + 1..-1] if invite.start_with?('http', 'discord.gg')
invite
end
# Gets information about an invite.
# @param invite [String, Invite] The invite to join. For possible formats see {#resolve_invite_code}.
# @return [Invite] The invite with information about the given invite URL.
def invite(invite)
code = resolve_invite_code(invite)
Invite.new(JSON.parse(API.resolve_invite(token, code)), self)
end
# Makes the bot join an invite to a server.
# @param invite [String, Invite] The invite to join. For possible formats see {#resolve_invite_code}.
def join(invite)
resolved = invite(invite).code
API.join_server(token, resolved)
end
attr_reader :voice
# Connects to a voice channel, initializes network connections and returns the {Voice::VoiceBot} over which audio
# data can then be sent. After connecting, the bot can also be accessed using {#voice}.
# @param chan [Channel] The voice channel to connect to.
# @param encrypted [true, false] Whether voice communication should be encrypted using RbNaCl's SecretBox
# (uses an XSalsa20 stream cipher for encryption and Poly1305 for authentication)
# @return [Voice::VoiceBot] the initialized bot over which audio data can then be sent.
def voice_connect(chan, encrypted = true)
if @voice
debug('Voice bot exists already! Destroying it')
@voice.destroy
@voice = nil
end
chan = channel(chan.resolve_id)
@voice_channel = chan
@should_encrypt_voice = encrypted
debug("Got voice channel: #{@voice_channel}")
data = {
op: 4,
d: {
guild_id: @voice_channel.server.id.to_s,
channel_id: @voice_channel.id.to_s,
self_mute: false,
self_deaf: false
}
}
debug("Voice channel init packet is: #{data.to_json}")
@should_connect_to_voice = true
@ws.send(data.to_json)
debug('Voice channel init packet sent! Now waiting.')
sleep(0.05) until @voice
debug('Voice connect succeeded!')
@voice
end
# Revokes an invite to a server. Will fail unless you have the *Manage Server* permission.
# It is recommended that you use {Invite#delete} instead.
# @param code [String, Invite] The invite to revoke. For possible formats see {#resolve_invite_code}.
def delete_invite(code)
invite = resolve_invite_code(code)
API.delete_invite(token, invite)
end
# Gets a user by its ID.
# @note This can only resolve users known by the bot (i.e. that share a server with the bot).
# @param id [Integer] The user ID that should be resolved.
# @return [User, nil] The user identified by the ID, or `nil` if it couldn't be found.
def user(id)
id = id.resolve_id
@users[id]
end
# Gets a server by its ID.
# @note This can only resolve servers the bot is currently in.
# @param id [Integer] The server ID that should be resolved.
# @return [Server, nil] The server identified by the ID, or `nil` if it couldn't be found.
def server(id)
id = id.resolve_id
@servers[id]
end
# Finds a channel given its name and optionally the name of the server it is in. If the threshold
# is not 0, it will use a Levenshtein distance function to find the channel in a fuzzy way, which
# allows slight misspellings.
# @param channel_name [String] The channel to search for.
# @param server_name [String] The server to search for, or `nil` if only the channel should be searched for.
# @param threshold [Integer] The threshold for the Levenshtein algorithm. The larger
# the threshold is, the more misspellings will be allowed.
# @return [Array<Channel>] The array of channels that were found. May be empty if none were found.
def find(channel_name, server_name = nil, threshold = 0)
begin
require 'levenshtein' if threshold > 0
levenshtein_available = true
rescue LoadError; levenshtein_available = false; end
results = []
@servers.values.each do |server|
server.channels.each do |channel|
if threshold > 0
fail LoadError, 'Levenshtein distance unavailable! Either set threshold to 0 or install the `levenshtein-ffi` gem' unless levenshtein_available
distance = Levenshtein.distance(channel.name, channel_name)
distance += Levenshtein.distance(server_name || server.name, server.name)
next if distance > threshold
else
distance = 0
next if channel.name != channel_name || (server_name || server.name) != server.name
end
# Make a singleton accessor "distance"
channel.instance_variable_set(:@distance, distance)
class << channel
attr_reader :distance
end
results << channel
end
end
results
end
# Finds a user given its username. This allows fuzzy finding using Levenshtein
# distances, see {#find}
# @param username [String] The username to look for.
# @param threshold [Integer] The threshold for the Levenshtein algorithm. The larger
# the threshold is, the more misspellings will be allowed.
# @return [Array<User>] The array of users that were found. May be empty if none were found.
def find_user(username, threshold = 0)
begin
require 'levenshtein' if threshold > 0
levenshtein_available = true
rescue LoadError; levenshtein_available = false; end
results = []
@users.values.each do |user|
if threshold > 0
fail LoadError, 'Levenshtein distance unavailable! Either set threshold to 0 or install the `levenshtein-ffi` gem' unless levenshtein_available
distance = Levenshtein.distance(user.username, username)
next if distance > threshold
else
distance = 0
next if user.username != username
end
# Make a singleton accessor "distance"
user.instance_variable_set(:@distance, distance)
class << user
attr_reader :distance
end
results << user
end
results
end
# Sends a text message to a channel given its ID and the message's content.
# @param channel_id [Integer] The ID that identifies the channel to send something to.
# @param content [String] The text that should be sent as a message. It is limited to 2000 characters (Discord imposed).
# @return [Message] The message that was sent.
def send_message(channel_id, content)
debug("Sending message to #{channel_id} with content '#{content}'")
response = API.send_message(token, channel_id, content)
Message.new(JSON.parse(response), self)
end
# Sends a file to a channel. If it is an image, it will automatically be embedded.
# @note This executes in a blocking way, so if you're sending long files, be wary of delays.
# @param channel_id [Integer] The ID that identifies the channel to send something to.
# @param file [File] The file that should be sent.
def send_file(channel_id, file)
response = API.send_file(token, channel_id, file)
Message.new(JSON.parse(response), self)
end
# Creates a server on Discord with a specified name and a region.
# @note Discord's API doesn't directly return the server when creating it, so this method
# waits until the data has been received via the websocket. This may make the execution take a while.
# @param name [String] The name the new server should have. Doesn't have to be alphanumeric.
# @param region [Symbol] The region where the server should be created. Possible regions are:
#
# * `:london`
# * `:amsterdam`
# * `:frankfurt`
# * `:us-east`
# * `:us-west`
# * `:singapore`
# * `:sydney`
# @return [Server] The server that was created.
def create_server(name, region = :london)
response = API.create_server(token, name, region)
id = JSON.parse(response)['id'].to_i
sleep 0.1 until @servers[id]
server = @servers[id]
debug "Successfully created server #{server.id} with name #{server.name}"
server
end
# Gets the user from a mention of the user.
# @param mention [String] The mention, which should look like <@12314873129>.
# @return [User] The user identified by the mention, or `nil` if none exists.
def parse_mention(mention)
# Mention format: <@id>
return nil unless /<@(?<id>\d+)>?/ =~ mention
user(id.to_i)
end
# Sets the currently playing game to the specified game.
# @param name [String] The name of the game to be played.
# @return [String] The game that is being played now.
def game=(name)
@game = name
data = {
op: 3,
d: {
idle_since: nil,
game: name ? { name: name } : nil
}
}
@ws.send(data.to_json)
name
end
# Sets debug mode. If debug mode is on, many things will be outputted to STDOUT.
def debug=(new_debug)
LOGGER.debug = new_debug
end
# Prevents the READY packet from being printed regardless of debug mode.
def suppress_ready_debug
@prevent_ready = true
end
# Add an await the bot should listen to. For information on awaits, see {Await}.
# @param key [Symbol] The key that uniquely identifies the await for {AwaitEvent}s to listen to (see {#await}).
# @param type [Class] The event class that should be listened for.
# @param attributes [Hash] The attributes the event should check for. The block will only be executed if all attributes match.
# @yield Is executed when the await is triggered.
# @yieldparam event [Event] The event object that was triggered.
# @return [Await] The await that was created.
def add_await(key, type, attributes = {}, &block)
fail "You can't await an AwaitEvent!" if type == Discordrb::Events::AwaitEvent
await = Await.new(self, key, type, attributes, block)
@awaits ||= {}
@awaits[key] = await
end
# @see Logger#debug
def debug(message, important = false)
LOGGER.debug(message, important)
end
# @see Logger#log_exception
def log_exception(e)
LOGGER.log_exception(e)
end
private
####### ### ###### ## ## ########
## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ##
## ## ## ## ######### ######
## ######### ## ## ## ##
## ## ## ## ## ## ## ## ##
####### ## ## ###### ## ## ########
def add_server(data)
server = Server.new(data, self)
@servers[server.id] = server
# Initialize users
server.members.each do |member|
if @users[member.id]
# If the user is already cached, just add the new roles
@users[member.id].merge_roles(server, member.roles[server.id])
else
@users[member.id] = member
end
end
server
end
### ## ## ######## ######## ######## ## ## ### ## ######
## ### ## ## ## ## ## ### ## ## ## ## ## ##
## #### ## ## ## ## ## #### ## ## ## ## ##
## ## ## ## ## ###### ######## ## ## ## ## ## ## ######
## ## #### ## ## ## ## ## #### ######### ## ##
## ## ### ## ## ## ## ## ### ## ## ## ## ##
### ## ## ## ######## ## ## ## ## ## ## ######## ######
# Internal handler for PRESENCE_UPDATE
def update_presence(data)
user_id = data['user']['id'].to_i
server_id = data['guild_id'].to_i
server = @servers[server_id]
return unless server
user = @users[user_id]
unless user
user = User.new(data['user'], self)
@users[user_id] = user
end
status = data['status'].to_sym
if status != :offline
unless server.members.find { |u| u.id == user.id }
server.members << user
end
end
user.status = status
user.game = data['game'] ? data['game']['name'] : nil
user
end
# Internal handler for VOICE_STATUS_UPDATE
def update_voice_state(data)
user_id = data['user_id'].to_i
server_id = data['guild_id'].to_i
server = @servers[server_id]
return unless server
user = @users[user_id]
user.server_mute = data['mute']
user.server_deaf = data['deaf']
user.self_mute = data['self_mute']
user.self_deaf = data['self_deaf']
channel_id = data['channel_id']
channel = nil
channel = @channels[channel_id.to_i] if channel_id
user.move(channel)
@session_id = data['session_id']
end
# Internal handler for VOICE_SERVER_UPDATE
def update_voice_server(data)
debug("Voice server update received! should connect: #{@should_connect_to_voice}")
return unless @should_connect_to_voice
@should_connect_to_voice = false
debug('Updating voice server!')
token = data['token']
endpoint = data['endpoint']
channel = @voice_channel
debug('Got data, now creating the bot.')
@voice = Discordrb::Voice::VoiceBot.new(channel, self, token, @session_id, endpoint, @should_encrypt_voice)
end
# Internal handler for CHANNEL_CREATE
def create_channel(data)
channel = Channel.new(data, self)
server = channel.server
server.channels << channel
@channels[channel.id] = channel
end
# Internal handler for CHANNEL_UPDATE
def update_channel(data)
channel = Channel.new(data, self)
old_channel = @channels[channel.id]
return unless old_channel
old_channel.update_from(channel)
end
# Internal handler for CHANNEL_DELETE
def delete_channel(data)
channel = Channel.new(data, self)
server = channel.server
@channels[channel.id] = nil
server.channels.reject! { |c| c.id == channel.id }
end
# Internal handler for GUILD_MEMBER_ADD
def add_guild_member(data)
user = User.new(data['user'], self)
server_id = data['guild_id'].to_i
server = @servers[server_id]
roles = []
data['roles'].each do |element|
role_id = element.to_i
roles << server.roles.find { |r| r.id == role_id }
end
user.update_roles(server, roles)
if @users[user.id]
# If the user is already cached, just add the new roles
@users[user.id].merge_roles(server, user.roles[server.id])
else
@users[user.id] = user
end
server.add_user(user)
end
# Internal handler for GUILD_MEMBER_UPDATE
def update_guild_member(data)
user_id = data['user']['id'].to_i
user = @users[user_id]
server_id = data['guild_id'].to_i
server = @servers[server_id]
roles = []
data['roles'].each do |element|
role_id = element.to_i
roles << server.roles.find { |r| r.id == role_id }
end
user.update_roles(server, roles)
end
# Internal handler for GUILD_MEMBER_DELETE
def delete_guild_member(data)
user_id = data['user']['id'].to_i
user = @users[user_id]
server_id = data['guild_id'].to_i
server = @servers[server_id]
user.delete_roles(server_id)
server.delete_user(user_id)
end
# Internal handler for GUILD_CREATE
def create_guild(data)
add_server(data)
end
# Internal handler for GUILD_UPDATE
def update_guild(data)
@servers[data['id'].to_i].update_data(data)
end
# Internal handler for GUILD_DELETE
def delete_guild(data)
id = data['id'].to_i
@users.each do |_, user|
user.delete_roles(id)
end
@servers.delete(id)
end
# Internal handler for GUILD_ROLE_UPDATE
def update_guild_role(data)
role_data = data['role']
server_id = data['guild_id'].to_i
server = @servers[server_id]
new_role = Role.new(role_data, self, server)
role_id = role_data['id'].to_i
old_role = server.roles.find { |r| r.id == role_id }
old_role.update_from(new_role)
end
# Internal handler for GUILD_ROLE_CREATE
def create_guild_role(data)
role_data = data['role']
server_id = data['guild_id'].to_i
server = @servers[server_id]
new_role = Role.new(role_data, self, server)
server.add_role(new_role)
end
# Internal handler for GUILD_ROLE_DELETE
def delete_guild_role(data)
role_id = data['role_id'].to_i
server_id = data['guild_id'].to_i
server = @servers[server_id]
server.delete_role(role_id)
end
# Internal handler for MESSAGE_CREATE
def create_message(data); end
# Internal handler for TYPING_START
def start_typing(data); end
# Internal handler for MESSAGE_UPDATE
def update_message(data); end
# Internal handler for MESSAGE_DELETE
def delete_message(data); end
# Internal handler for GUILD_BAN_ADD
def add_user_ban(data); end
# Internal handler for GUILD_BAN_REMOVE
def remove_user_ban(data); end
## ####### ###### #### ## ##
## ## ## ## ## ## ### ##
## ## ## ## ## #### ##
## ## ## ## #### ## ## ## ##
## ## ## ## ## ## ## ####
## ## ## ## ## ## ## ###
######## ####### ###### #### ## ##
def login
debug('Logging in')
login_attempts ||= 0
# First, attempt to get the token from the cache
token = @token_cache.token(@email, @password)
if token
debug('Token successfully obtained from cache!')
return token
end
# Login
login_response = API.login(@email, @password)
fail HTTPStatusException, login_response.code if login_response.code >= 400
# Parse response
login_response_object = JSON.parse(login_response)
fail InvalidAuthenticationException unless login_response_object['token']
debug('Received token from Discord!')
# Cache the token
@token_cache.store_token(@email, @password, login_response_object['token'])
login_response_object['token']
rescue Exception => e
response_code = login_response.nil? ? 0 : login_response.code ######## mackmm145
if login_attempts < 100 && (e.inspect.include?('No such host is known.') || response_code == 523)
debug("Login failed! Reattempting in 5 seconds. #{100 - login_attempts} attempts remaining.")
debug("Error was: #{e.inspect}")
sleep 5
login_attempts += 1
retry
else
debug("Login failed permanently after #{login_attempts + 1} attempts")
# Apparently we get a 400 if the password or username is incorrect. In that case, tell the user
debug("Are you sure you're using the correct username and password?") if e.class == RestClient::BadRequest
log_exception(e)
raise $ERROR_INFO
end
end
def find_gateway
# Get updated websocket_hub
response = API.gateway(token)
JSON.parse(response)['url']
end
## ## ###### ######## ## ## ######## ## ## ######## ######
## ## ## ## ## ## ## ## ## ### ## ## ## ##
## ## ## ## ## ## ## ## #### ## ## ##
## ## ## ###### ###### ## ## ###### ## ## ## ## ######
## ## ## ## ## ## ## ## ## #### ## ##
## ## ## ## ## ## ## ## ## ## ### ## ## ##
#### ### ###### ######## ### ######## ## ## ## ######
def websocket_connect
debug('Attempting to get gateway URL...')
websocket_hub = find_gateway
debug("Success! Gateway URL is #{websocket_hub}.")
debug('Now running bot')
EM.run do
@ws = Faye::WebSocket::Client.new(websocket_hub)
@ws.on(:open) { |event| websocket_open(event) }
@ws.on(:message) { |event| websocket_message(event) }
@ws.on(:error) { |event| debug(event.message) }
@ws.on :close do |event|
websocket_close(event)
@ws = nil
end
end
end
def websocket_message(event)
# Parse packet
packet = JSON.parse(event.data)
if @prevent_ready && packet['t'] == 'READY'
debug('READY packet was received and suppressed')
elsif @prevent_ready && packet['t'] == 'GUILD_MEMBERS_CHUNK'
# Ignore chunks as they will be handled later anyway
else
debug("Received packet #{event.data}")
end
fail 'Invalid Packet' unless packet['op'] == 0 # TODO
data = packet['d']
case packet['t']
when 'READY'
# Activate the heartbeats
@heartbeat_interval = data['heartbeat_interval'].to_f / 1000.0
@heartbeat_active = true
debug("Desired heartbeat_interval: #{@heartbeat_interval}")
bot_user_id = data['user']['id'].to_i
@profile = Profile.new(data['user'], self, @email, @password)
# Initialize servers
@servers = {}
data['guilds'].each do |element|
add_server(element)
# Save the bot user
@bot_user = @users[bot_user_id]
end
# Add private channels
@private_channels = {}
data['private_channels'].each do |element|
channel = Channel.new(element, self)
@channels[channel.id] = channel
@private_channels[channel.recipient.id] = channel
end
# Make sure to raise the event
raise_event(ReadyEvent.new)
# Afterwards, send out a members request to get the chunk data
chunk_packet = {
op: 8,
d: {
guild_id: @servers.keys,
query: '',
limit: 0
}
}.to_json
@ws.send(chunk_packet)
# Tell the run method that everything was successful
@ws_success = true
when 'GUILD_MEMBERS_CHUNK'
id = data['guild_id'].to_i
members = data['members']
start_time = Time.now
members.each do |member|
# Add the guild_id to the member so we can reuse add_guild_member
member['guild_id'] = id
add_guild_member(member)
end
duration = Time.now - start_time
if members.length < 1000
debug "Got final chunk for server #{id}, parsing took #{duration} seconds"
else
debug "Got one chunk for server #{id}, parsing took #{duration} seconds"
end
when 'MESSAGE_CREATE'
create_message(data)
message = Message.new(data, self)
return if message.from_bot? && !should_parse_self
event = MessageEvent.new(message, self)
raise_event(event)
if message.mentions.any? { |user| user.id == @bot_user.id }
event = MentionEvent.new(message, self)
raise_event(event)
end
if message.channel.private?
event = PrivateMessageEvent.new(message, self)
raise_event(event)
end
when 'MESSAGE_UPDATE'
update_message(data)
event = MessageEditEvent.new(data, self)
raise_event(event)
when 'MESSAGE_DELETE'
delete_message(data)
event = MessageDeleteEvent.new(data, self)
raise_event(event)
when 'TYPING_START'
start_typing(data)
event = TypingEvent.new(data, self)
raise_event(event)
when 'PRESENCE_UPDATE'
now_playing = data['game']
played_before = user(data['user']['id'].to_i).game
update_presence(data)
event = if now_playing != played_before
PlayingEvent.new(data, self)
else
PresenceEvent.new(data, self)
end
raise_event(event)
when 'VOICE_STATE_UPDATE'
update_voice_state(data)
event = VoiceStateUpdateEvent.new(data, self)
raise_event(event)
when 'VOICE_SERVER_UPDATE'
update_voice_server(data)
# no event as this is irrelevant to users
when 'CHANNEL_CREATE'
create_channel(data)
event = ChannelCreateEvent.new(data, self)
raise_event(event)
when 'CHANNEL_UPDATE'
update_channel(data)
event = ChannelUpdateEvent.new(data, self)
raise_event(event)
when 'CHANNEL_DELETE'
delete_channel(data)
event = ChannelDeleteEvent.new(data, self)
raise_event(event)
when 'GUILD_MEMBER_ADD'
add_guild_member(data)
event = GuildMemberAddEvent.new(data, self)
raise_event(event)
when 'GUILD_MEMBER_UPDATE'
update_guild_member(data)
event = GuildMemberUpdateEvent.new(data, self)
raise_event(event)
when 'GUILD_MEMBER_REMOVE'
delete_guild_member(data)
event = GuildMemberDeleteEvent.new(data, self)
raise_event(event)
when 'GUILD_BAN_ADD'
add_user_ban(data)
event = UserBanEvent.new(data, self)
raise_event(event)
when 'GUILD_BAN_REMOVE'
remove_user_ban(data)
event = UserUnbanEvent.new(data, self)
raise_event(event)
when 'GUILD_ROLE_UPDATE'
update_guild_role(data)
event = GuildRoleUpdateEvent.new(data, self)
raise_event(event)
when 'GUILD_ROLE_CREATE'
create_guild_role(data)
event = GuildRoleCreateEvent.new(data, self)
raise_event(event)
when 'GUILD_ROLE_DELETE'
delete_guild_role(data)
event = GuildRoleDeleteEvent.new(data, self)
raise_event(event)
when 'GUILD_CREATE'
create_guild(data)
event = GuildCreateEvent.new(data, self)
raise_event(event)
when 'GUILD_UPDATE'
update_guild(data)
event = GuildUpdateEvent.new(data, self)
raise_event(event)
when 'GUILD_DELETE'
delete_guild(data)
event = GuildDeleteEvent.new(data, self)
raise_event(event)
else
# another event that we don't support yet
debug "Event #{packet['t']} has been received but is unsupported, ignoring"
end
rescue Exception => e
log_exception(e)
end
def websocket_close(event)
debug('Disconnected from WebSocket!')
debug(" (Reason: #{event.reason})")
debug(" (Code: #{event.code})")
raise_event(DisconnectEvent.new)
EM.stop
end
def websocket_open(_)
# Send the initial packet
packet = {
op: 2, # Packet identifier
d: { # Packet data
v: 3, # WebSocket protocol version
token: @token,
properties: { # I'm unsure what these values are for exactly, but they don't appear to impact bot functionality in any way.
:'$os' => RUBY_PLATFORM.to_s,
:'$browser' => 'discordrb',
:'$device' => 'discordrb',
:'$referrer' => '',
:'$referring_domain' => ''
},
large_threshold: 100
}
}
@ws.send(packet.to_json)
end
def send_heartbeat
millis = Time.now.strftime('%s%L').to_i
debug("Sending heartbeat at #{millis}")
data = {
op: 1,
d: millis
}
@ws.send(data.to_json)
end
def raise_event(event)
debug("Raised a #{event.class}")
handle_awaits(event)
@event_handlers ||= {}
handlers = @event_handlers[event.class]
(handlers || []).each do |handler|
call_event(handler, event) if handler.matches?(event)
end
end
def call_event(handler, event)
t = Thread.new do
@event_threads ||= []
@current_thread ||= 0
@event_threads << t
Thread.current[:discordrb_name] = "et-#{@current_thread += 1}"
begin
handler.call(event)
handler.after_call(event)
rescue => e
log_exception(e)
ensure
@event_threads.delete(t)
end
end
end
def handle_awaits(event)
@awaits ||= {}
@awaits.each do |_, await|
key, should_delete = await.match(event)
next unless key
debug("should_delete: #{should_delete}")
@awaits.delete(await.key) if should_delete
await_event = Discordrb::Events::AwaitEvent.new(await, event, self)
raise_event(await_event)
end
end
end
end
|
require 'set'
module DataMapper
module Model
##
#
# Extends the model with this module after DataMapper::Resource has been
# included.
#
# This is a useful way to extend DataMapper::Model while
# still retaining a self.extended method.
#
# @param [Module] extensions the module that is to be extend the model after
# after DataMapper::Model
#
# @return [TrueClass, FalseClass] whether or not the inclusions have been
# successfully appended to the list
#-
# @api public
#
# TODO: Move this do DataMapper::Model when DataMapper::Model is created
def self.append_extensions(*extensions)
extra_extensions.concat extensions
true
end
def self.extra_extensions
@extra_extensions ||= []
end
def self.extended(model)
model.instance_variable_set(:@storage_names, Hash.new { |h,k| h[k] = repository(k).adapter.resource_naming_convention.call(model.send(:default_storage_name)) })
model.instance_variable_set(:@properties, Hash.new { |h,k| h[k] = k == Repository.default_name ? PropertySet.new : h[Repository.default_name].dup })
extra_extensions.each { |extension| model.extend(extension) }
end
def inherited(target)
target.instance_variable_set(:@storage_names, @storage_names.dup)
target.instance_variable_set(:@properties, Hash.new { |h,k| h[k] = k == Repository.default_name ? PropertySet.new : h[Repository.default_name].dup })
target.instance_variable_set(:@base_model, self.base_model)
@properties.each do |repository_name,properties|
repository(repository_name) do
properties.each { |p| target.property(p.name, p.type, p.options.dup) }
end
end
if @relationships
duped_relationships = Hash.new { |h,k| h[k] = {} }
@relationships.each do |repository_name,relationships|
relationships.each do |name, relationship|
duped_relationships[repository_name][name] = relationship.dup
end
end
target.instance_variable_set(:@relationships, duped_relationships)
end
end
def self.new(storage_name, &block)
model = Class.new
model.send(:include, Resource)
model.class_eval <<-EOS, __FILE__, __LINE__
def self.default_storage_name
#{Extlib::Inflection.classify(storage_name).inspect}
end
EOS
model.instance_eval(&block) if block_given?
model
end
def base_model
@base_model ||= self
end
##
# Get the repository with a given name, or the default one for the current
# context, or the default one for this class.
#
# @param name<Symbol> the name of the repository wanted
# @param block<Block> block to execute with the fetched repository as parameter
#
# @return <Object, DataMapper::Respository> whatever the block returns,
# if given a block, otherwise the requested repository.
#-
# @api public
def repository(name = nil, &block)
#
# There has been a couple of different strategies here, but me (zond) and dkubb are at least
# united in the concept of explicitness over implicitness. That is - the explicit wish of the
# caller (+name+) should be given more priority than the implicit wish of the caller (Repository.context.last).
#
DataMapper.repository(*Array(name || (Repository.context.last ? nil : default_repository_name)), &block)
end
##
# the name of the storage recepticle for this resource. IE. table name, for database stores
#
# @return <String> the storage name (IE table name, for database stores) associated with this resource in the given repository
def storage_name(repository_name = default_repository_name)
@storage_names[repository_name]
end
##
# the names of the storage recepticles for this resource across all repositories
#
# @return <Hash(Symbol => String)> All available names of storage recepticles
def storage_names
@storage_names
end
##
# defines a property on the resource
#
# @param <Symbol> name the name for which to call this property
# @param <Type> type the type to define this property ass
# @param <Hash(Symbol => String)> options a hash of available options
# @see DataMapper::Property
def property(name, type, options = {})
property = Property.new(self, name, type, options)
create_property_getter(property)
create_property_setter(property)
@properties[repository.name] << property
# Add property to the other mappings as well if this is for the default
# repository.
if repository.name == default_repository_name
@properties.each_pair do |repository_name, properties|
next if repository_name == default_repository_name
properties << property
end
end
# Add the property to the lazy_loads set for this resources repository
# only.
# TODO Is this right or should we add the lazy contexts to all
# repositories?
if property.lazy?
context = options.fetch(:lazy, :default)
context = :default if context == true
Array(context).each do |item|
@properties[repository.name].lazy_context(item) << name
end
end
# add the property to the child classes only if the property was
# added after the child classes' properties have been copied from
# the parent
if respond_to?(:descendants)
descendants.each do |model|
next if model.properties(repository.name).has_property?(name)
model.property(name, type, options)
end
end
property
end
def repositories
[ repository ].to_set + @properties.keys.collect { |repository_name| DataMapper.repository(repository_name) }
end
def properties(repository_name = default_repository_name)
@properties[repository_name]
end
# @api private
def properties_with_subclasses(repository_name = default_repository_name)
properties = PropertySet.new
([ self ].to_set + (respond_to?(:descendants) ? descendants : [])).each do |model|
model.relationships(repository_name).each_value { |relationship| relationship.child_key }
model.many_to_one_relationships.each do |relationship| relationship.child_key end
model.properties(repository_name).each do |property|
properties << property unless properties.has_property?(property.name)
end
end
properties
end
def key(repository_name = default_repository_name)
@properties[repository_name].key
end
def inheritance_property(repository_name = default_repository_name)
@properties[repository_name].inheritance_property
end
def default_order
@default_order ||= key.map { |property| Query::Direction.new(property) }
end
def get(*key)
key = typecast_key(key)
repository.identity_map(self).get(key) || first(to_query(repository, key))
end
def get!(*key)
get(*key) || raise(ObjectNotFoundError, "Could not find #{self.name} with key #{key.inspect}")
end
def all(query = {})
query = scoped_query(query)
query.repository.read_many(query)
end
def first(*args)
query = args.last.respond_to?(:merge) ? args.pop : {}
query = scoped_query(query.merge(:limit => args.first || 1))
if args.any?
query.repository.read_many(query)
else
query.repository.read_one(query)
end
end
def [](*key)
warn("#{name}[] is deprecated. Use #{name}.get! instead.")
get!(*key)
end
def first_or_create(query, attributes = {})
first(query) || begin
resource = allocate
query = query.dup
properties(repository.name).key.each do |property|
if value = query.delete(property.name)
resource.send("#{property.name}=", value)
end
end
resource.attributes = query.merge(attributes)
resource.save
resource
end
end
##
# Create an instance of Resource with the given attributes
#
# @param <Hash(Symbol => Object)> attributes hash of attributes to set
def create(attributes = {})
resource = new(attributes)
resource.save
resource
end
##
# Dangerous version of #create. Raises if there is a failure
#
# @see DataMapper::Resource#create
# @param <Hash(Symbol => Object)> attributes hash of attributes to set
# @raise <PersistenceError> The resource could not be saved
def create!(attributes = {})
resource = create(attributes)
raise PersistenceError, "Resource not saved: :new_record => #{resource.new_record?}, :dirty_attributes => #{resource.dirty_attributes.inspect}" if resource.new_record?
resource
end
# TODO SPEC
def copy(source, destination, query = {})
repository(destination) do
repository(source).read_many(query).each do |resource|
self.create(resource)
end
end
end
# @api private
# TODO: spec this
def load(values, query)
repository = query.repository
model = self
if inheritance_property_index = query.inheritance_property_index(repository)
model = values.at(inheritance_property_index) || model
end
if key_property_indexes = query.key_property_indexes(repository)
key_values = values.values_at(*key_property_indexes)
identity_map = repository.identity_map(model)
if resource = identity_map.get(key_values)
return resource unless query.reload?
else
resource = model.allocate
resource.instance_variable_set(:@repository, repository)
identity_map.set(key_values, resource)
end
else
resource = model.allocate
resource.readonly!
end
resource.instance_variable_set(:@new_record, false)
query.fields.zip(values) do |property,value|
value = property.custom? ? property.type.load(value, property) : property.typecast(value)
property.set!(resource, value)
if track = property.track
case track
when :hash
resource.original_values[property.name] = value.dup.hash unless resource.original_values.has_key?(property.name) rescue value.hash
when :load
resource.original_values[property.name] = value unless resource.original_values.has_key?(property.name)
end
end
end
resource
end
# TODO: spec this
def to_query(repository, key, query = {})
conditions = Hash[ *self.key(repository.name).zip(key).flatten ]
Query.new(repository, self, query.merge(conditions))
end
def typecast_key(key)
self.key(repository.name).zip(key).map { |k, v| k.typecast(v) }
end
private
def default_storage_name
self.name
end
def default_repository_name
Repository.default_name
end
def scoped_query(query = self.query)
assert_kind_of 'query', query, Query, Hash
return self.query if query == self.query
query = if query.kind_of?(Hash)
Query.new(query.has_key?(:repository) ? query.delete(:repository) : self.repository, self, query)
else
query
end
self.query ? self.query.merge(query) : query
end
# defines the getter for the property
def create_property_getter(property)
class_eval <<-EOS, __FILE__, __LINE__
#{property.reader_visibility}
def #{property.getter}
attribute_get(#{property.name.inspect})
end
EOS
if property.primitive == TrueClass && !instance_methods.include?(property.name.to_s)
class_eval <<-EOS, __FILE__, __LINE__
#{property.reader_visibility}
alias #{property.name} #{property.getter}
EOS
end
end
# defines the setter for the property
def create_property_setter(property)
unless instance_methods.include?("#{property.name}=")
class_eval <<-EOS, __FILE__, __LINE__
#{property.writer_visibility}
def #{property.name}=(value)
attribute_set(#{property.name.inspect}, value)
end
EOS
end
end
def relationships(*args)
# DO NOT REMOVE!
# method_missing depends on these existing. Without this stub,
# a missing module can cause misleading recursive errors.
raise NotImplementedError.new
end
def method_missing(method, *args, &block)
if relationship = self.relationships(repository.name)[method]
klass = self == relationship.child_model ? relationship.parent_model : relationship.child_model
return DataMapper::Query::Path.new(repository, [ relationship ], klass)
end
if property = properties(repository.name)[method]
return property
end
super
end
# TODO: move to dm-more/dm-transactions
module Transaction
#
# Produce a new Transaction for this Resource class
#
# @return <DataMapper::Adapters::Transaction
# a new DataMapper::Adapters::Transaction with all DataMapper::Repositories
# of the class of this DataMapper::Resource added.
#-
# @api public
#
# TODO: move to dm-more/dm-transactions
def transaction(&block)
DataMapper::Transaction.new(self, &block)
end
end # module Transaction
include Transaction
# TODO: move to dm-more/dm-migrations
module Migration
# TODO: move to dm-more/dm-migrations
def storage_exists?(repository_name = default_repository_name)
repository(repository_name).storage_exists?(storage_name(repository_name))
end
end # module Migration
include Migration
end # module Model
end # module DataMapper
STI models get updated relationships
require 'set'
module DataMapper
module Model
##
#
# Extends the model with this module after DataMapper::Resource has been
# included.
#
# This is a useful way to extend DataMapper::Model while
# still retaining a self.extended method.
#
# @param [Module] extensions the module that is to be extend the model after
# after DataMapper::Model
#
# @return [TrueClass, FalseClass] whether or not the inclusions have been
# successfully appended to the list
#-
# @api public
#
# TODO: Move this do DataMapper::Model when DataMapper::Model is created
def self.append_extensions(*extensions)
extra_extensions.concat extensions
true
end
def self.extra_extensions
@extra_extensions ||= []
end
def self.extended(model)
model.instance_variable_set(:@storage_names, Hash.new { |h,k| h[k] = repository(k).adapter.resource_naming_convention.call(model.send(:default_storage_name)) })
model.instance_variable_set(:@properties, Hash.new { |h,k| h[k] = k == Repository.default_name ? PropertySet.new : h[Repository.default_name].dup })
extra_extensions.each { |extension| model.extend(extension) }
end
def inherited(target)
target.instance_variable_set(:@storage_names, @storage_names.dup)
target.instance_variable_set(:@properties, Hash.new { |h,k| h[k] = k == Repository.default_name ? PropertySet.new : h[Repository.default_name].dup })
target.instance_variable_set(:@base_model, self.base_model)
@properties.each do |repository_name,properties|
repository(repository_name) do
properties.each { |p| target.property(p.name, p.type, p.options.dup) }
end
end
if @relationships
duped_relationships = Hash.new { |h,k| h[k] = {} }
@relationships.each do |repository_name,relationships|
relationships.each do |name, relationship|
dup = relationship.dup
dup.instance_variable_set(:@child_model, target) if dup.instance_variable_get(:@child_model) == self
dup.instance_variable_set(:@parent_model, target) if dup.instance_variable_get(:@parent_model) == self
duped_relationships[repository_name][name] = dup
end
end
target.instance_variable_set(:@relationships, duped_relationships)
end
end
def self.new(storage_name, &block)
model = Class.new
model.send(:include, Resource)
model.class_eval <<-EOS, __FILE__, __LINE__
def self.default_storage_name
#{Extlib::Inflection.classify(storage_name).inspect}
end
EOS
model.instance_eval(&block) if block_given?
model
end
def base_model
@base_model ||= self
end
##
# Get the repository with a given name, or the default one for the current
# context, or the default one for this class.
#
# @param name<Symbol> the name of the repository wanted
# @param block<Block> block to execute with the fetched repository as parameter
#
# @return <Object, DataMapper::Respository> whatever the block returns,
# if given a block, otherwise the requested repository.
#-
# @api public
def repository(name = nil, &block)
#
# There has been a couple of different strategies here, but me (zond) and dkubb are at least
# united in the concept of explicitness over implicitness. That is - the explicit wish of the
# caller (+name+) should be given more priority than the implicit wish of the caller (Repository.context.last).
#
DataMapper.repository(*Array(name || (Repository.context.last ? nil : default_repository_name)), &block)
end
##
# the name of the storage recepticle for this resource. IE. table name, for database stores
#
# @return <String> the storage name (IE table name, for database stores) associated with this resource in the given repository
def storage_name(repository_name = default_repository_name)
@storage_names[repository_name]
end
##
# the names of the storage recepticles for this resource across all repositories
#
# @return <Hash(Symbol => String)> All available names of storage recepticles
def storage_names
@storage_names
end
##
# defines a property on the resource
#
# @param <Symbol> name the name for which to call this property
# @param <Type> type the type to define this property ass
# @param <Hash(Symbol => String)> options a hash of available options
# @see DataMapper::Property
def property(name, type, options = {})
property = Property.new(self, name, type, options)
create_property_getter(property)
create_property_setter(property)
@properties[repository.name] << property
# Add property to the other mappings as well if this is for the default
# repository.
if repository.name == default_repository_name
@properties.each_pair do |repository_name, properties|
next if repository_name == default_repository_name
properties << property
end
end
# Add the property to the lazy_loads set for this resources repository
# only.
# TODO Is this right or should we add the lazy contexts to all
# repositories?
if property.lazy?
context = options.fetch(:lazy, :default)
context = :default if context == true
Array(context).each do |item|
@properties[repository.name].lazy_context(item) << name
end
end
# add the property to the child classes only if the property was
# added after the child classes' properties have been copied from
# the parent
if respond_to?(:descendants)
descendants.each do |model|
next if model.properties(repository.name).has_property?(name)
model.property(name, type, options)
end
end
property
end
def repositories
[ repository ].to_set + @properties.keys.collect { |repository_name| DataMapper.repository(repository_name) }
end
def properties(repository_name = default_repository_name)
@properties[repository_name]
end
# @api private
def properties_with_subclasses(repository_name = default_repository_name)
properties = PropertySet.new
([ self ].to_set + (respond_to?(:descendants) ? descendants : [])).each do |model|
model.relationships(repository_name).each_value { |relationship| relationship.child_key }
model.many_to_one_relationships.each do |relationship| relationship.child_key end
model.properties(repository_name).each do |property|
properties << property unless properties.has_property?(property.name)
end
end
properties
end
def key(repository_name = default_repository_name)
@properties[repository_name].key
end
def inheritance_property(repository_name = default_repository_name)
@properties[repository_name].inheritance_property
end
def default_order
@default_order ||= key.map { |property| Query::Direction.new(property) }
end
def get(*key)
key = typecast_key(key)
repository.identity_map(self).get(key) || first(to_query(repository, key))
end
def get!(*key)
get(*key) || raise(ObjectNotFoundError, "Could not find #{self.name} with key #{key.inspect}")
end
def all(query = {})
query = scoped_query(query)
query.repository.read_many(query)
end
def first(*args)
query = args.last.respond_to?(:merge) ? args.pop : {}
query = scoped_query(query.merge(:limit => args.first || 1))
if args.any?
query.repository.read_many(query)
else
query.repository.read_one(query)
end
end
def [](*key)
warn("#{name}[] is deprecated. Use #{name}.get! instead.")
get!(*key)
end
def first_or_create(query, attributes = {})
first(query) || begin
resource = allocate
query = query.dup
properties(repository.name).key.each do |property|
if value = query.delete(property.name)
resource.send("#{property.name}=", value)
end
end
resource.attributes = query.merge(attributes)
resource.save
resource
end
end
##
# Create an instance of Resource with the given attributes
#
# @param <Hash(Symbol => Object)> attributes hash of attributes to set
def create(attributes = {})
resource = new(attributes)
resource.save
resource
end
##
# Dangerous version of #create. Raises if there is a failure
#
# @see DataMapper::Resource#create
# @param <Hash(Symbol => Object)> attributes hash of attributes to set
# @raise <PersistenceError> The resource could not be saved
def create!(attributes = {})
resource = create(attributes)
raise PersistenceError, "Resource not saved: :new_record => #{resource.new_record?}, :dirty_attributes => #{resource.dirty_attributes.inspect}" if resource.new_record?
resource
end
# TODO SPEC
def copy(source, destination, query = {})
repository(destination) do
repository(source).read_many(query).each do |resource|
self.create(resource)
end
end
end
# @api private
# TODO: spec this
def load(values, query)
repository = query.repository
model = self
if inheritance_property_index = query.inheritance_property_index(repository)
model = values.at(inheritance_property_index) || model
end
if key_property_indexes = query.key_property_indexes(repository)
key_values = values.values_at(*key_property_indexes)
identity_map = repository.identity_map(model)
if resource = identity_map.get(key_values)
return resource unless query.reload?
else
resource = model.allocate
resource.instance_variable_set(:@repository, repository)
identity_map.set(key_values, resource)
end
else
resource = model.allocate
resource.readonly!
end
resource.instance_variable_set(:@new_record, false)
query.fields.zip(values) do |property,value|
value = property.custom? ? property.type.load(value, property) : property.typecast(value)
property.set!(resource, value)
if track = property.track
case track
when :hash
resource.original_values[property.name] = value.dup.hash unless resource.original_values.has_key?(property.name) rescue value.hash
when :load
resource.original_values[property.name] = value unless resource.original_values.has_key?(property.name)
end
end
end
resource
end
# TODO: spec this
def to_query(repository, key, query = {})
conditions = Hash[ *self.key(repository.name).zip(key).flatten ]
Query.new(repository, self, query.merge(conditions))
end
def typecast_key(key)
self.key(repository.name).zip(key).map { |k, v| k.typecast(v) }
end
private
def default_storage_name
self.name
end
def default_repository_name
Repository.default_name
end
def scoped_query(query = self.query)
assert_kind_of 'query', query, Query, Hash
return self.query if query == self.query
query = if query.kind_of?(Hash)
Query.new(query.has_key?(:repository) ? query.delete(:repository) : self.repository, self, query)
else
query
end
self.query ? self.query.merge(query) : query
end
# defines the getter for the property
def create_property_getter(property)
class_eval <<-EOS, __FILE__, __LINE__
#{property.reader_visibility}
def #{property.getter}
attribute_get(#{property.name.inspect})
end
EOS
if property.primitive == TrueClass && !instance_methods.include?(property.name.to_s)
class_eval <<-EOS, __FILE__, __LINE__
#{property.reader_visibility}
alias #{property.name} #{property.getter}
EOS
end
end
# defines the setter for the property
def create_property_setter(property)
unless instance_methods.include?("#{property.name}=")
class_eval <<-EOS, __FILE__, __LINE__
#{property.writer_visibility}
def #{property.name}=(value)
attribute_set(#{property.name.inspect}, value)
end
EOS
end
end
def relationships(*args)
# DO NOT REMOVE!
# method_missing depends on these existing. Without this stub,
# a missing module can cause misleading recursive errors.
raise NotImplementedError.new
end
def method_missing(method, *args, &block)
if relationship = self.relationships(repository.name)[method]
klass = self == relationship.child_model ? relationship.parent_model : relationship.child_model
return DataMapper::Query::Path.new(repository, [ relationship ], klass)
end
if property = properties(repository.name)[method]
return property
end
super
end
# TODO: move to dm-more/dm-transactions
module Transaction
#
# Produce a new Transaction for this Resource class
#
# @return <DataMapper::Adapters::Transaction
# a new DataMapper::Adapters::Transaction with all DataMapper::Repositories
# of the class of this DataMapper::Resource added.
#-
# @api public
#
# TODO: move to dm-more/dm-transactions
def transaction(&block)
DataMapper::Transaction.new(self, &block)
end
end # module Transaction
include Transaction
# TODO: move to dm-more/dm-migrations
module Migration
# TODO: move to dm-more/dm-migrations
def storage_exists?(repository_name = default_repository_name)
repository(repository_name).storage_exists?(storage_name(repository_name))
end
end # module Migration
include Migration
end # module Model
end # module DataMapper
|
require 'concurrent'
require 'pathname'
class DockerClient
CONTAINER_WORKSPACE_PATH = '/workspace' #'/home/python/workspace' #'/tmp/workspace'
DEFAULT_MEMORY_LIMIT = 256
# Ralf: I suggest to replace this with the environment variable. Ask Hauke why this is not the case!
LOCAL_WORKSPACE_ROOT = Rails.root.join('tmp', 'files', Rails.env)
MINIMUM_MEMORY_LIMIT = 4
RECYCLE_CONTAINERS = true
RETRY_COUNT = 2
attr_reader :container
attr_reader :socket
attr_accessor :tubesock
def self.check_availability!
Timeout.timeout(config[:connection_timeout]) { Docker.version }
rescue Excon::Errors::SocketError, Timeout::Error
raise(Error, "The Docker host at #{Docker.url} is not reachable!")
end
def self.clean_container_workspace(container)
container.exec(['bash', '-c', 'rm -rf ' + CONTAINER_WORKSPACE_PATH])
=begin
local_workspace_path = local_workspace_path(container)
if local_workspace_path && Pathname.new(local_workspace_path).exist?
Pathname.new(local_workspace_path).children.each{ |p| p.rmtree}
#FileUtils.rmdir(Pathname.new(local_workspace_path))
end
=end
end
def command_substitutions(filename)
{class_name: File.basename(filename, File.extname(filename)).camelize, filename: filename, module_name: File.basename(filename, File.extname(filename)).underscore}
end
private :command_substitutions
def self.config
@config ||= CodeOcean::Config.new(:docker).read(erb: true)
end
def self.container_creation_options(execution_environment)
{
'Image' => find_image_by_tag(execution_environment.docker_image).info['RepoTags'].first,
'Memory' => execution_environment.memory_limit.megabytes,
'NetworkDisabled' => !execution_environment.network_enabled?,
#'HostConfig' => { 'CpusetCpus' => '0', 'CpuQuota' => 10000 },
#DockerClient.config['allowed_cpus']
'OpenStdin' => true,
'StdinOnce' => true,
# required to expose standard streams over websocket
'AttachStdout' => true,
'AttachStdin' => true,
'AttachStderr' => true,
'Tty' => true
}
end
def self.container_start_options(execution_environment, local_workspace_path)
{
'Binds' => mapped_directories(local_workspace_path),
'PortBindings' => mapped_ports(execution_environment)
}
end
def create_socket(container, stderr=false)
# todo factor out query params
# todo separate stderr
query_params = 'logs=0&stream=1&' + (stderr ? 'stderr=1' : 'stdout=1&stdin=1')
# Headers are required by Docker
headers = {'Origin' => 'http://localhost'}
socket = Faye::WebSocket::Client.new(DockerClient.config['ws_host'] + '/containers/' + @container.id + '/attach/ws?' + query_params, [], :headers => headers)
socket.on :error do |event|
Rails.logger.info "Websocket error: " + event.message
end
socket.on :close do |event|
Rails.logger.info "Websocket closed."
end
socket.on :open do |event|
Rails.logger.info "Websocket created."
kill_after_timeout(container)
end
socket
end
def copy_file_to_workspace(options = {})
FileUtils.cp(options[:file].native_file.path, local_file_path(options))
end
def self.create_container(execution_environment)
tries ||= 0
#Rails.logger.info "docker_client: self.create_container with creation options:"
#Rails.logger.info(container_creation_options(execution_environment))
container = Docker::Container.create(container_creation_options(execution_environment))
local_workspace_path = generate_local_workspace_path
# container.start always creates the passed local_workspace_path on disk. Seems like we have to live with that, therefore we can also just create the empty folder ourselves.
# FileUtils.mkdir(local_workspace_path)
container.start(container_start_options(execution_environment, local_workspace_path))
container.start_time = Time.now
container.status = :created
container
rescue Docker::Error::NotFoundError => error
Rails.logger.info('create_container: Got Docker::Error::NotFoundError: ' + error.to_s)
destroy_container(container)
#(tries += 1) <= RETRY_COUNT ? retry : raise(error)
end
def create_workspace_files(container, submission)
#clear directory (it should be empty anyhow)
#Pathname.new(self.class.local_workspace_path(container)).children.each{ |p| p.rmtree}
submission.collect_files.each do |file|
FileUtils.mkdir_p(File.join(self.class.local_workspace_path(container), file.path || ''))
if file.file_type.binary?
copy_file_to_workspace(container: container, file: file)
else
create_workspace_file(container: container, file: file)
end
end
rescue Docker::Error::NotFoundError => error
Rails.logger.info('create_workspace_files: Rescued from Docker::Error::NotFoundError: ' + error.to_s)
end
private :create_workspace_files
def create_workspace_file(options = {})
#TODO: try catch i/o exception and log failed attempts
file = File.new(local_file_path(options), 'w')
file.write(options[:file].content)
file.close
end
private :create_workspace_file
def create_workspace_files_transmit(container, submission)
begin
# create a temporary dir, put all files in it, and put it into the container. the dir is automatically removed when leaving the block.
Dir.mktmpdir {|dir|
submission.collect_files.each do |file|
disk_file = File.new(dir + '/' + (file.path || '') + file.name_with_extension, 'w')
disk_file.write(file.content)
disk_file.close
end
begin
# create target folder
container.exec(['bash', '-c', 'mkdir ' + CONTAINER_WORKSPACE_PATH])
#container.exec(['bash', '-c', 'chown -R python ' + CONTAINER_WORKSPACE_PATH])
#container.exec(['bash', '-c', 'chgrp -G python ' + CONTAINER_WORKSPACE_PATH])
rescue StandardError => error
Rails.logger.error('create workspace folder: Rescued from StandardError: ' + error.to_s)
end
#sleep 1000
begin
# tar the files in dir and put the tar to CONTAINER_WORKSPACE_PATH in the container
container.archive_in(dir, CONTAINER_WORKSPACE_PATH, overwrite: false)
rescue StandardError => error
Rails.logger.error('insert tar: Rescued from StandardError: ' + error.to_s)
end
Rails.logger.info('command: tar -xf ' + CONTAINER_WORKSPACE_PATH + '/' + dir.split('/tmp/')[1] + ' -C ' + CONTAINER_WORKSPACE_PATH)
begin
# untar the tar file placed in the CONTAINER_WORKSPACE_PATH
container.exec(['bash', '-c', 'tar -xf ' + CONTAINER_WORKSPACE_PATH + '/' + dir.split('/tmp/')[1] + ' -C ' + CONTAINER_WORKSPACE_PATH])
rescue StandardError => error
Rails.logger.error('untar: Rescued from StandardError: ' + error.to_s)
end
#sleep 1000
}
rescue StandardError => error
Rails.logger.error('create_workspace_files_transmit: Rescued from StandardError: ' + error.to_s)
end
end
def self.destroy_container(container)
Rails.logger.info('destroying container ' + container.to_s)
container.stop.kill
container.port_bindings.values.each { |port| PortPool.release(port) }
clean_container_workspace(container)
if(container)
container.delete(force: true, v: true)
end
rescue Docker::Error::NotFoundError => error
Rails.logger.error('destroy_container: Rescued from Docker::Error::NotFoundError: ' + error.to_s)
Rails.logger.error('No further actions are done concerning that.')
end
#currently only used to check if containers have been started correctly, or other internal checks
def execute_arbitrary_command(command, &block)
execute_command(command, nil, block)
end
#only used by server sent events (deprecated?)
def execute_command(command, before_execution_block, output_consuming_block)
#tries ||= 0
@container = DockerContainerPool.get_container(@execution_environment)
if @container
@container.status = :executing
before_execution_block.try(:call)
send_command(command, @container, &output_consuming_block)
else
{status: :container_depleted}
end
rescue Excon::Errors::SocketError => error
# socket errors seems to be normal when using exec
# so lets ignore them for now
#(tries += 1) <= RETRY_COUNT ? retry : raise(error)
end
#called when the user clicks the "Run" button
def execute_websocket_command(command, before_execution_block, output_consuming_block)
@container = DockerContainerPool.get_container(@execution_environment)
if @container
@container.status = :executing
# do not use try here, directly call the passed proc and rescue from the error in order to log the problem.
#before_execution_block.try(:call)
begin
before_execution_block.call
rescue StandardError => error
Rails.logger.error('execute_websocket_command: Rescued from StandardError caused by before_execution_block.call: ' + error.to_s)
end
# TODO: catch exception if socket could not be created
@socket ||= create_socket(@container)
# Newline required to flush
@socket.send command + "\n"
Rails.logger.info('Sent command: ' + command.to_s)
{status: :container_running, socket: @socket, container: @container}
else
{status: :container_depleted}
end
end
def kill_after_timeout(container)
"""
We need to start a second thread to kill the websocket connection,
as it is impossible to determine whether further input is requested.
"""
@thread = Thread.new do
#begin
timeout = @execution_environment.permitted_execution_time.to_i # seconds
sleep(timeout)
if container.status != :returned
Rails.logger.info('Killing container after timeout of ' + timeout.to_s + ' seconds.')
# send timeout to the tubesock socket
if(@tubesock)
@tubesock.send_data JSON.dump({'cmd' => 'timeout'})
end
kill_container(container)
end
#ensure
# guarantee that the thread is releasing the DB connection after it is done
# ActiveRecord::Base.connectionpool.releaseconnection
#end
end
end
def exit_container(container)
Rails.logger.debug('exiting container ' + container.to_s)
# exit the timeout thread if it is still alive
if(@thread && @thread.alive?)
@thread.exit
end
# if we use pooling and recylce the containers, put it back. otherwise, destroy it.
(DockerContainerPool.config[:active] && RECYCLE_CONTAINERS) ? self.class.return_container(container, @execution_environment) : self.class.destroy_container(container)
end
def kill_container(container)
Rails.logger.info('killing container ' + container.to_s)
# remove container from pool, then destroy it
if (DockerContainerPool.config[:active])
DockerContainerPool.remove_from_all_containers(container, @execution_environment)
end
self.class.destroy_container(container)
# if we recylce containers, we start a fresh one
if(DockerContainerPool.config[:active] && RECYCLE_CONTAINERS)
# create new container and add it to @all_containers and @containers.
container = self.class.create_container(@execution_environment)
DockerContainerPool.add_to_all_containers(container, @execution_environment)
end
end
def execute_run_command(submission, filename, &block)
"""
Run commands by attaching a websocket to Docker.
"""
command = submission.execution_environment.run_command % command_substitutions(filename)
create_workspace_files = proc { create_workspace_files_transmit(container, submission) }
execute_websocket_command(command, create_workspace_files, block)
end
def execute_test_command(submission, filename, &block)
"""
Stick to existing Docker API with exec command.
"""
command = submission.execution_environment.test_command % command_substitutions(filename)
create_workspace_files = proc { create_workspace_files_transmit(container, submission) }
execute_command(command, create_workspace_files, block)
end
def self.find_image_by_tag(tag)
# todo: cache this.
Docker::Image.all.detect { |image| image.info['RepoTags'].flatten.include?(tag) }
end
def self.generate_local_workspace_path
File.join(LOCAL_WORKSPACE_ROOT, SecureRandom.uuid)
end
def self.image_tags
Docker::Image.all.map { |image| image.info['RepoTags'] }.flatten.reject { |tag| tag.include?('<none>') }
end
def initialize(options = {})
@execution_environment = options[:execution_environment]
# todo: eventually re-enable this if it is cached. But in the end, we do not need this.
# docker daemon got much too much load. all not 100% necessary calls to the daemon were removed.
#@image = self.class.find_image_by_tag(@execution_environment.docker_image)
#fail(Error, "Cannot find image #{@execution_environment.docker_image}!") unless @image
end
def self.initialize_environment
unless config[:connection_timeout] && config[:workspace_root]
fail(Error, 'Docker configuration missing!')
end
Docker.url = config[:host] if config[:host]
# todo: availability check disabled for performance reasons. Reconsider if this is necessary.
# docker daemon got much too much load. all not 100% necessary calls to the daemon were removed.
# check_availability!
FileUtils.mkdir_p(LOCAL_WORKSPACE_ROOT)
end
def local_file_path(options = {})
File.join(self.class.local_workspace_path(options[:container]), options[:file].path || '', options[:file].name_with_extension)
end
private :local_file_path
def self.local_workspace_path(container)
Pathname.new(container.binds.first.split(':').first.sub(config[:workspace_root], LOCAL_WORKSPACE_ROOT.to_s)) if container.binds.present?
end
def self.mapped_directories(local_workspace_path)
remote_workspace_path = local_workspace_path.sub(LOCAL_WORKSPACE_ROOT.to_s, config[:workspace_root])
# create the string to be returned
["#{remote_workspace_path}:#{CONTAINER_WORKSPACE_PATH}"]
end
def self.mapped_ports(execution_environment)
(execution_environment.exposed_ports || '').gsub(/\s/, '').split(',').map do |port|
["#{port}/tcp", [{'HostPort' => PortPool.available_port.to_s}]]
end.to_h
end
def self.pull(docker_image)
`docker pull #{docker_image}` if docker_image
end
def self.return_container(container, execution_environment)
Rails.logger.debug('returning container ' + container.to_s)
begin
clean_container_workspace(container)
rescue Docker::Error::NotFoundError => error
Rails.logger.info('return_container: Rescued from Docker::Error::NotFoundError: ' + error.to_s)
Rails.logger.info('Nothing is done here additionally. The container will be exchanged upon its next retrieval.')
end
DockerContainerPool.return_container(container, execution_environment)
container.status = :returned
end
#private :return_container
def send_command(command, container, &block)
result = {status: :failed, stdout: '', stderr: ''}
Timeout.timeout(@execution_environment.permitted_execution_time.to_i) do
#TODO: check phusion doku again if we need -i -t options here
output = container.exec(['bash', '-c', command])
Rails.logger.info "output from container.exec"
Rails.logger.info output
result = {status: output[2] == 0 ? :ok : :failed, stdout: output[0].join.force_encoding('utf-8'), stderr: output[1].join.force_encoding('utf-8')}
end
# if we use pooling and recylce the containers, put it back. otherwise, destroy it.
(DockerContainerPool.config[:active] && RECYCLE_CONTAINERS) ? self.class.return_container(container, @execution_environment) : self.class.destroy_container(container)
result
rescue Timeout::Error
Rails.logger.info('got timeout error for container ' + container.to_s)
# remove container from pool, then destroy it
if (DockerContainerPool.config[:active])
DockerContainerPool.remove_from_all_containers(container, @execution_environment)
end
# destroy container
self.class.destroy_container(container)
# if we recylce containers, we start a fresh one
if(DockerContainerPool.config[:active] && RECYCLE_CONTAINERS)
# create new container and add it to @all_containers and @containers.
container = self.class.create_container(@execution_environment)
DockerContainerPool.add_to_all_containers(container, @execution_environment)
end
{status: :timeout}
end
private :send_command
class Error < RuntimeError; end
end
just remove subfolders of CONTAINER_WORKSPACE_PATH, do not create target folder manually.
require 'concurrent'
require 'pathname'
class DockerClient
CONTAINER_WORKSPACE_PATH = '/workspace' #'/home/python/workspace' #'/tmp/workspace'
DEFAULT_MEMORY_LIMIT = 256
# Ralf: I suggest to replace this with the environment variable. Ask Hauke why this is not the case!
LOCAL_WORKSPACE_ROOT = Rails.root.join('tmp', 'files', Rails.env)
MINIMUM_MEMORY_LIMIT = 4
RECYCLE_CONTAINERS = true
RETRY_COUNT = 2
attr_reader :container
attr_reader :socket
attr_accessor :tubesock
def self.check_availability!
Timeout.timeout(config[:connection_timeout]) { Docker.version }
rescue Excon::Errors::SocketError, Timeout::Error
raise(Error, "The Docker host at #{Docker.url} is not reachable!")
end
def self.clean_container_workspace(container)
container.exec(['bash', '-c', 'rm -rf ' + CONTAINER_WORKSPACE_PATH + '/*'])
=begin
local_workspace_path = local_workspace_path(container)
if local_workspace_path && Pathname.new(local_workspace_path).exist?
Pathname.new(local_workspace_path).children.each{ |p| p.rmtree}
#FileUtils.rmdir(Pathname.new(local_workspace_path))
end
=end
end
def command_substitutions(filename)
{class_name: File.basename(filename, File.extname(filename)).camelize, filename: filename, module_name: File.basename(filename, File.extname(filename)).underscore}
end
private :command_substitutions
def self.config
@config ||= CodeOcean::Config.new(:docker).read(erb: true)
end
def self.container_creation_options(execution_environment)
{
'Image' => find_image_by_tag(execution_environment.docker_image).info['RepoTags'].first,
'Memory' => execution_environment.memory_limit.megabytes,
'NetworkDisabled' => !execution_environment.network_enabled?,
#'HostConfig' => { 'CpusetCpus' => '0', 'CpuQuota' => 10000 },
#DockerClient.config['allowed_cpus']
'OpenStdin' => true,
'StdinOnce' => true,
# required to expose standard streams over websocket
'AttachStdout' => true,
'AttachStdin' => true,
'AttachStderr' => true,
'Tty' => true
}
end
def self.container_start_options(execution_environment, local_workspace_path)
{
'Binds' => mapped_directories(local_workspace_path),
'PortBindings' => mapped_ports(execution_environment)
}
end
def create_socket(container, stderr=false)
# todo factor out query params
# todo separate stderr
query_params = 'logs=0&stream=1&' + (stderr ? 'stderr=1' : 'stdout=1&stdin=1')
# Headers are required by Docker
headers = {'Origin' => 'http://localhost'}
socket = Faye::WebSocket::Client.new(DockerClient.config['ws_host'] + '/containers/' + @container.id + '/attach/ws?' + query_params, [], :headers => headers)
socket.on :error do |event|
Rails.logger.info "Websocket error: " + event.message
end
socket.on :close do |event|
Rails.logger.info "Websocket closed."
end
socket.on :open do |event|
Rails.logger.info "Websocket created."
kill_after_timeout(container)
end
socket
end
def copy_file_to_workspace(options = {})
FileUtils.cp(options[:file].native_file.path, local_file_path(options))
end
def self.create_container(execution_environment)
tries ||= 0
#Rails.logger.info "docker_client: self.create_container with creation options:"
#Rails.logger.info(container_creation_options(execution_environment))
container = Docker::Container.create(container_creation_options(execution_environment))
local_workspace_path = generate_local_workspace_path
# container.start always creates the passed local_workspace_path on disk. Seems like we have to live with that, therefore we can also just create the empty folder ourselves.
# FileUtils.mkdir(local_workspace_path)
container.start(container_start_options(execution_environment, local_workspace_path))
container.start_time = Time.now
container.status = :created
container
rescue Docker::Error::NotFoundError => error
Rails.logger.info('create_container: Got Docker::Error::NotFoundError: ' + error.to_s)
destroy_container(container)
#(tries += 1) <= RETRY_COUNT ? retry : raise(error)
end
def create_workspace_files(container, submission)
#clear directory (it should be empty anyhow)
#Pathname.new(self.class.local_workspace_path(container)).children.each{ |p| p.rmtree}
submission.collect_files.each do |file|
FileUtils.mkdir_p(File.join(self.class.local_workspace_path(container), file.path || ''))
if file.file_type.binary?
copy_file_to_workspace(container: container, file: file)
else
create_workspace_file(container: container, file: file)
end
end
rescue Docker::Error::NotFoundError => error
Rails.logger.info('create_workspace_files: Rescued from Docker::Error::NotFoundError: ' + error.to_s)
end
private :create_workspace_files
def create_workspace_file(options = {})
#TODO: try catch i/o exception and log failed attempts
file = File.new(local_file_path(options), 'w')
file.write(options[:file].content)
file.close
end
private :create_workspace_file
def create_workspace_files_transmit(container, submission)
begin
# create a temporary dir, put all files in it, and put it into the container. the dir is automatically removed when leaving the block.
Dir.mktmpdir {|dir|
submission.collect_files.each do |file|
disk_file = File.new(dir + '/' + (file.path || '') + file.name_with_extension, 'w')
disk_file.write(file.content)
disk_file.close
end
begin
# create target folder, TODO re-active this when we remove shared folder bindings
#container.exec(['bash', '-c', 'mkdir ' + CONTAINER_WORKSPACE_PATH])
#container.exec(['bash', '-c', 'chown -R python ' + CONTAINER_WORKSPACE_PATH])
#container.exec(['bash', '-c', 'chgrp -G python ' + CONTAINER_WORKSPACE_PATH])
rescue StandardError => error
Rails.logger.error('create workspace folder: Rescued from StandardError: ' + error.to_s)
end
#sleep 1000
begin
# tar the files in dir and put the tar to CONTAINER_WORKSPACE_PATH in the container
container.archive_in(dir, CONTAINER_WORKSPACE_PATH, overwrite: false)
rescue StandardError => error
Rails.logger.error('insert tar: Rescued from StandardError: ' + error.to_s)
end
#Rails.logger.info('command: tar -xf ' + CONTAINER_WORKSPACE_PATH + '/' + dir.split('/tmp/')[1] + ' -C ' + CONTAINER_WORKSPACE_PATH)
begin
# untar the tar file placed in the CONTAINER_WORKSPACE_PATH
container.exec(['bash', '-c', 'tar -xf ' + CONTAINER_WORKSPACE_PATH + '/' + dir.split('/tmp/')[1] + ' -C ' + CONTAINER_WORKSPACE_PATH])
rescue StandardError => error
Rails.logger.error('untar: Rescued from StandardError: ' + error.to_s)
end
#sleep 1000
}
rescue StandardError => error
Rails.logger.error('create_workspace_files_transmit: Rescued from StandardError: ' + error.to_s)
end
end
def self.destroy_container(container)
Rails.logger.info('destroying container ' + container.to_s)
container.stop.kill
container.port_bindings.values.each { |port| PortPool.release(port) }
clean_container_workspace(container)
if(container)
container.delete(force: true, v: true)
end
rescue Docker::Error::NotFoundError => error
Rails.logger.error('destroy_container: Rescued from Docker::Error::NotFoundError: ' + error.to_s)
Rails.logger.error('No further actions are done concerning that.')
end
#currently only used to check if containers have been started correctly, or other internal checks
def execute_arbitrary_command(command, &block)
execute_command(command, nil, block)
end
#only used by server sent events (deprecated?)
def execute_command(command, before_execution_block, output_consuming_block)
#tries ||= 0
@container = DockerContainerPool.get_container(@execution_environment)
if @container
@container.status = :executing
before_execution_block.try(:call)
send_command(command, @container, &output_consuming_block)
else
{status: :container_depleted}
end
rescue Excon::Errors::SocketError => error
# socket errors seems to be normal when using exec
# so lets ignore them for now
#(tries += 1) <= RETRY_COUNT ? retry : raise(error)
end
#called when the user clicks the "Run" button
def execute_websocket_command(command, before_execution_block, output_consuming_block)
@container = DockerContainerPool.get_container(@execution_environment)
if @container
@container.status = :executing
# do not use try here, directly call the passed proc and rescue from the error in order to log the problem.
#before_execution_block.try(:call)
begin
before_execution_block.call
rescue StandardError => error
Rails.logger.error('execute_websocket_command: Rescued from StandardError caused by before_execution_block.call: ' + error.to_s)
end
# TODO: catch exception if socket could not be created
@socket ||= create_socket(@container)
# Newline required to flush
@socket.send command + "\n"
Rails.logger.info('Sent command: ' + command.to_s)
{status: :container_running, socket: @socket, container: @container}
else
{status: :container_depleted}
end
end
def kill_after_timeout(container)
"""
We need to start a second thread to kill the websocket connection,
as it is impossible to determine whether further input is requested.
"""
@thread = Thread.new do
#begin
timeout = @execution_environment.permitted_execution_time.to_i # seconds
sleep(timeout)
if container.status != :returned
Rails.logger.info('Killing container after timeout of ' + timeout.to_s + ' seconds.')
# send timeout to the tubesock socket
if(@tubesock)
@tubesock.send_data JSON.dump({'cmd' => 'timeout'})
end
kill_container(container)
end
#ensure
# guarantee that the thread is releasing the DB connection after it is done
# ActiveRecord::Base.connectionpool.releaseconnection
#end
end
end
def exit_container(container)
Rails.logger.debug('exiting container ' + container.to_s)
# exit the timeout thread if it is still alive
if(@thread && @thread.alive?)
@thread.exit
end
# if we use pooling and recylce the containers, put it back. otherwise, destroy it.
(DockerContainerPool.config[:active] && RECYCLE_CONTAINERS) ? self.class.return_container(container, @execution_environment) : self.class.destroy_container(container)
end
def kill_container(container)
Rails.logger.info('killing container ' + container.to_s)
# remove container from pool, then destroy it
if (DockerContainerPool.config[:active])
DockerContainerPool.remove_from_all_containers(container, @execution_environment)
end
self.class.destroy_container(container)
# if we recylce containers, we start a fresh one
if(DockerContainerPool.config[:active] && RECYCLE_CONTAINERS)
# create new container and add it to @all_containers and @containers.
container = self.class.create_container(@execution_environment)
DockerContainerPool.add_to_all_containers(container, @execution_environment)
end
end
def execute_run_command(submission, filename, &block)
"""
Run commands by attaching a websocket to Docker.
"""
command = submission.execution_environment.run_command % command_substitutions(filename)
create_workspace_files = proc { create_workspace_files_transmit(container, submission) }
execute_websocket_command(command, create_workspace_files, block)
end
def execute_test_command(submission, filename, &block)
"""
Stick to existing Docker API with exec command.
"""
command = submission.execution_environment.test_command % command_substitutions(filename)
create_workspace_files = proc { create_workspace_files_transmit(container, submission) }
execute_command(command, create_workspace_files, block)
end
def self.find_image_by_tag(tag)
# todo: cache this.
Docker::Image.all.detect { |image| image.info['RepoTags'].flatten.include?(tag) }
end
def self.generate_local_workspace_path
File.join(LOCAL_WORKSPACE_ROOT, SecureRandom.uuid)
end
def self.image_tags
Docker::Image.all.map { |image| image.info['RepoTags'] }.flatten.reject { |tag| tag.include?('<none>') }
end
def initialize(options = {})
@execution_environment = options[:execution_environment]
# todo: eventually re-enable this if it is cached. But in the end, we do not need this.
# docker daemon got much too much load. all not 100% necessary calls to the daemon were removed.
#@image = self.class.find_image_by_tag(@execution_environment.docker_image)
#fail(Error, "Cannot find image #{@execution_environment.docker_image}!") unless @image
end
def self.initialize_environment
unless config[:connection_timeout] && config[:workspace_root]
fail(Error, 'Docker configuration missing!')
end
Docker.url = config[:host] if config[:host]
# todo: availability check disabled for performance reasons. Reconsider if this is necessary.
# docker daemon got much too much load. all not 100% necessary calls to the daemon were removed.
# check_availability!
FileUtils.mkdir_p(LOCAL_WORKSPACE_ROOT)
end
def local_file_path(options = {})
File.join(self.class.local_workspace_path(options[:container]), options[:file].path || '', options[:file].name_with_extension)
end
private :local_file_path
def self.local_workspace_path(container)
Pathname.new(container.binds.first.split(':').first.sub(config[:workspace_root], LOCAL_WORKSPACE_ROOT.to_s)) if container.binds.present?
end
def self.mapped_directories(local_workspace_path)
remote_workspace_path = local_workspace_path.sub(LOCAL_WORKSPACE_ROOT.to_s, config[:workspace_root])
# create the string to be returned
["#{remote_workspace_path}:#{CONTAINER_WORKSPACE_PATH}"]
end
def self.mapped_ports(execution_environment)
(execution_environment.exposed_ports || '').gsub(/\s/, '').split(',').map do |port|
["#{port}/tcp", [{'HostPort' => PortPool.available_port.to_s}]]
end.to_h
end
def self.pull(docker_image)
`docker pull #{docker_image}` if docker_image
end
def self.return_container(container, execution_environment)
Rails.logger.debug('returning container ' + container.to_s)
begin
clean_container_workspace(container)
rescue Docker::Error::NotFoundError => error
Rails.logger.info('return_container: Rescued from Docker::Error::NotFoundError: ' + error.to_s)
Rails.logger.info('Nothing is done here additionally. The container will be exchanged upon its next retrieval.')
end
DockerContainerPool.return_container(container, execution_environment)
container.status = :returned
end
#private :return_container
def send_command(command, container, &block)
result = {status: :failed, stdout: '', stderr: ''}
Timeout.timeout(@execution_environment.permitted_execution_time.to_i) do
#TODO: check phusion doku again if we need -i -t options here
output = container.exec(['bash', '-c', command])
Rails.logger.info "output from container.exec"
Rails.logger.info output
result = {status: output[2] == 0 ? :ok : :failed, stdout: output[0].join.force_encoding('utf-8'), stderr: output[1].join.force_encoding('utf-8')}
end
# if we use pooling and recylce the containers, put it back. otherwise, destroy it.
(DockerContainerPool.config[:active] && RECYCLE_CONTAINERS) ? self.class.return_container(container, @execution_environment) : self.class.destroy_container(container)
result
rescue Timeout::Error
Rails.logger.info('got timeout error for container ' + container.to_s)
# remove container from pool, then destroy it
if (DockerContainerPool.config[:active])
DockerContainerPool.remove_from_all_containers(container, @execution_environment)
end
# destroy container
self.class.destroy_container(container)
# if we recylce containers, we start a fresh one
if(DockerContainerPool.config[:active] && RECYCLE_CONTAINERS)
# create new container and add it to @all_containers and @containers.
container = self.class.create_container(@execution_environment)
DockerContainerPool.add_to_all_containers(container, @execution_environment)
end
{status: :timeout}
end
private :send_command
class Error < RuntimeError; end
end
|
require 'docker'
require 'excon'
require 'tempfile'
require 'zlib'
require 'rubygems/package'
require 'fileutils'
class Dockly::Docker
include Dockly::Util::DSL
include Dockly::Util::Logger::Mixin
autoload :Registry, 'dockly/docker/registry'
logger_prefix '[dockly docker]'
dsl_class_attribute :build_cache, Dockly::BuildCache.model, type: Array
dsl_class_attribute :registry, Dockly::Docker::Registry
dsl_attribute :name, :import, :git_archive, :build, :tag, :build_dir, :package_dir,
:timeout, :cleanup_images, :tar_diff, :s3_bucket, :s3_object_prefix
default_value :tag, nil
default_value :build_dir, 'build/docker'
default_value :package_dir, '/opt/docker'
default_value :cleanup_images, false
default_value :timeout, 60
default_value :tar_diff, false
default_value :s3_bucket, nil
default_value :s3_object_prefix, ""
def generate!
image = generate_build
export_image(image)
ensure
cleanup([image]) if cleanup_images
end
def generate_build
Docker.options = { :read_timeout => timeout, :write_timeout => timeout }
images = {}
if registry_import.nil?
docker_tar = File.absolute_path(ensure_tar(fetch_import))
images[:one] = import_base(docker_tar)
else
registry.authenticate! unless registry.nil?
full_name = "#{registry_import[:name]}:#{registry_import[:tag]}"
info "Pulling #{full_name}"
images[:one] = ::Docker::Image.create('fromImage' => registry_import[:name], 'tag' => registry_import[:tag])
info "Successfully pulled #{full_name}"
end
images[:two] = add_git_archive(images[:one])
images[:three] = run_build_caches(images[:two])
build_image(images[:three])
ensure
cleanup(images.values.compact) if cleanup_images
end
def registry_import(img_name = nil, opts = {})
if img_name
@registry_import ||= {}
@registry_import[:name] = img_name
@registry_import[:tag] = opts[:tag] || 'latest'
else
@registry_import
end
end
def cleanup(images)
info 'Cleaning up intermediate images'
::Docker::Container.all(:all => true).each do |container|
image_id = container.json['Image']
if images.any? { |image| image.id.start_with?(image_id) || image_id.start_with?(image.id) }
container.kill
container.delete
end
end
images.each { |image| image.remove rescue nil }
info 'Done cleaning images'
end
def export_filename
"#{name}-image.tgz"
end
def run_build_caches(image)
info "starting build caches"
(build_cache || []).each do |cache|
cache.image = image
image = cache.execute!
end
info "finished build caches"
image
end
def tar_path
File.join(build_dir, export_filename)
end
def ensure_tar(file_name)
if Dockly::Util::Tar.is_tar?(file_name)
file_name
elsif Dockly::Util::Tar.is_gzip?(file_name)
file_name
else
raise "Expected a (possibly gzipped) tar: #{file_name}"
end
end
def make_git_archive
ensure_present! :git_archive
info "initializing"
prefix = git_archive
prefix += '/' unless prefix.end_with?('/')
FileUtils.rm_rf(git_archive_dir)
FileUtils.mkdir_p(git_archive_dir)
info "archiving #{Dockly::Util::Git.git_sha}"
Grit::Git.with_timeout(120) do
Dockly::Util::Git.git_repo.archive_to_file(Dockly::Util::Git.git_sha, prefix, git_archive_path, 'tar', 'cat')
end
info "made the git archive for sha #{Dockly::Util::Git.git_sha}"
git_archive_path
end
def git_archive_dir
@git_archive_dir ||= File.join(build_dir, "gitarc")
end
def git_archive_path
"#{git_archive_dir}/#{name}.tar"
end
def git_archive_tar
git_archive && File.absolute_path(make_git_archive)
end
def import_base(docker_tar)
info "importing the docker image from #{docker_tar}"
image = ::Docker::Image.import(docker_tar)
info "imported initial docker image: #{image.id}"
image
end
def add_git_archive(image)
return image if git_archive.nil?
info "adding the git archive"
new_image = image.insert_local(
'localPath' => git_archive_tar,
'outputPath' => '/'
)
info "successfully added the git archive"
new_image
end
def build_image(image)
ensure_present! :name, :build
info "running custom build steps, starting with id: #{image.id}"
out_image = ::Docker::Image.build("from #{image.id}\n#{build}")
info "finished running custom build steps, result id: #{out_image.id}"
out_image.tap { |img| img.tag(:repo => repo, :tag => tag) }
end
def repo
@repo ||= case
when registry.nil?
name
when registry.default_server_address?
"#{registry.username}/#{name}"
else
"#{registry.server_address}/#{name}"
end
end
def export_image(image)
ensure_present! :name
if registry.nil?
ensure_present! :build_dir
info "Exporting the image with id #{image.id} to file #{File.expand_path(tar_path)}"
container = image.run('true')
info "created the container: #{container.id}"
unless s3_bucket.nil?
output = Dockly::AWS::S3Writer.new(connection, s3_bucket, s3_object)
else
output = File.open(tar_path, 'wb')
end
gzip_output = Zlib::GzipWriter.new(output)
if tar_diff
export_image_diff(container, gzip_output)
else
export_image_whole(container, gzip_output)
end
else
push_to_registry(image)
end
rescue
if output && !s3_bucket.nil?
output.abort_unless_closed
end
ensure
gzip_output.close if gzip_output
end
def export_image_whole(container, output)
container.export do |chunk, remaining, total|
output.write(chunk)
end
end
def export_image_diff(container, output)
rd, wr = IO.pipe(Encoding::ASCII_8BIT)
thread = Thread.new do
begin
if Dockly::Util::Tar.is_tar?(fetch_import)
base = File.open(fetch_import, 'rb')
else
base = Zlib::GzipReader.new(File.open(fetch_import, 'rb'))
end
td = Dockly::TarDiff.new(base, rd, output)
td.process
info "done writing the docker tar: #{export_filename}"
ensure
base.close if base
rd.close
end
end
begin
container.export do |chunk, remaining, total|
wr.write(chunk)
end
ensure
wr.close
thread.join
end
end
def s3_object
output = "#{s3_object_prefix}"
output << "#{Dockly::Util::Git.git_sha}/"
output << "#{export_filename}"
end
def push_to_registry(image)
ensure_present! :registry
info "Exporting #{image.id} to Docker registry at #{registry.server_address}"
registry.authenticate!
image = Docker::Image.all(:all => true).find { |img|
img.id.start_with?(image.id) || image.id.start_with?(img.id)
}
raise "Could not find image after authentication" if image.nil?
image.push(registry.to_h, :registry => registry.server_address)
end
def fetch_import
ensure_present! :import
path = "/tmp/dockly-docker-import.#{name}.#{File.basename(import)}"
if File.exist?(path)
debug "already fetched #{import}"
else
debug "fetching #{import}"
File.open("#{path}.tmp", 'wb') do |file|
case import
when /^s3:\/\/(?<bucket_name>.+?)\/(?<object_path>.+)$/
connection.get_object(Regexp.last_match[:bucket_name],
Regexp.last_match[:object_path]) do |chunk, remaining, total|
file.write(chunk)
end
when /^https?:\/\//
Excon.get(import, :response_block => lambda { |chunk, remaining, total|
file.write(chunk)
})
else
raise "You can only import from S3 or a public url"
end
end
FileUtils.mv("#{path}.tmp", path, :force => true)
end
path
end
def repository(value = nil)
name(value)
end
private
def connection
Dockly::AWS.s3
end
end
Add S3 url formatting
require 'docker'
require 'excon'
require 'tempfile'
require 'zlib'
require 'rubygems/package'
require 'fileutils'
class Dockly::Docker
include Dockly::Util::DSL
include Dockly::Util::Logger::Mixin
autoload :Registry, 'dockly/docker/registry'
logger_prefix '[dockly docker]'
dsl_class_attribute :build_cache, Dockly::BuildCache.model, type: Array
dsl_class_attribute :registry, Dockly::Docker::Registry
dsl_attribute :name, :import, :git_archive, :build, :tag, :build_dir, :package_dir,
:timeout, :cleanup_images, :tar_diff, :s3_bucket, :s3_object_prefix
default_value :tag, nil
default_value :build_dir, 'build/docker'
default_value :package_dir, '/opt/docker'
default_value :cleanup_images, false
default_value :timeout, 60
default_value :tar_diff, false
default_value :s3_bucket, nil
default_value :s3_object_prefix, ""
def generate!
image = generate_build
export_image(image)
ensure
cleanup([image]) if cleanup_images
end
def generate_build
Docker.options = { :read_timeout => timeout, :write_timeout => timeout }
images = {}
if registry_import.nil?
docker_tar = File.absolute_path(ensure_tar(fetch_import))
images[:one] = import_base(docker_tar)
else
registry.authenticate! unless registry.nil?
full_name = "#{registry_import[:name]}:#{registry_import[:tag]}"
info "Pulling #{full_name}"
images[:one] = ::Docker::Image.create('fromImage' => registry_import[:name], 'tag' => registry_import[:tag])
info "Successfully pulled #{full_name}"
end
images[:two] = add_git_archive(images[:one])
images[:three] = run_build_caches(images[:two])
build_image(images[:three])
ensure
cleanup(images.values.compact) if cleanup_images
end
def registry_import(img_name = nil, opts = {})
if img_name
@registry_import ||= {}
@registry_import[:name] = img_name
@registry_import[:tag] = opts[:tag] || 'latest'
else
@registry_import
end
end
def cleanup(images)
info 'Cleaning up intermediate images'
::Docker::Container.all(:all => true).each do |container|
image_id = container.json['Image']
if images.any? { |image| image.id.start_with?(image_id) || image_id.start_with?(image.id) }
container.kill
container.delete
end
end
images.each { |image| image.remove rescue nil }
info 'Done cleaning images'
end
def export_filename
"#{name}-image.tgz"
end
def run_build_caches(image)
info "starting build caches"
(build_cache || []).each do |cache|
cache.image = image
image = cache.execute!
end
info "finished build caches"
image
end
def tar_path
File.join(build_dir, export_filename)
end
def ensure_tar(file_name)
if Dockly::Util::Tar.is_tar?(file_name)
file_name
elsif Dockly::Util::Tar.is_gzip?(file_name)
file_name
else
raise "Expected a (possibly gzipped) tar: #{file_name}"
end
end
def make_git_archive
ensure_present! :git_archive
info "initializing"
prefix = git_archive
prefix += '/' unless prefix.end_with?('/')
FileUtils.rm_rf(git_archive_dir)
FileUtils.mkdir_p(git_archive_dir)
info "archiving #{Dockly::Util::Git.git_sha}"
Grit::Git.with_timeout(120) do
Dockly::Util::Git.git_repo.archive_to_file(Dockly::Util::Git.git_sha, prefix, git_archive_path, 'tar', 'cat')
end
info "made the git archive for sha #{Dockly::Util::Git.git_sha}"
git_archive_path
end
def git_archive_dir
@git_archive_dir ||= File.join(build_dir, "gitarc")
end
def git_archive_path
"#{git_archive_dir}/#{name}.tar"
end
def git_archive_tar
git_archive && File.absolute_path(make_git_archive)
end
def import_base(docker_tar)
info "importing the docker image from #{docker_tar}"
image = ::Docker::Image.import(docker_tar)
info "imported initial docker image: #{image.id}"
image
end
def add_git_archive(image)
return image if git_archive.nil?
info "adding the git archive"
new_image = image.insert_local(
'localPath' => git_archive_tar,
'outputPath' => '/'
)
info "successfully added the git archive"
new_image
end
def build_image(image)
ensure_present! :name, :build
info "running custom build steps, starting with id: #{image.id}"
out_image = ::Docker::Image.build("from #{image.id}\n#{build}")
info "finished running custom build steps, result id: #{out_image.id}"
out_image.tap { |img| img.tag(:repo => repo, :tag => tag) }
end
def repo
@repo ||= case
when registry.nil?
name
when registry.default_server_address?
"#{registry.username}/#{name}"
else
"#{registry.server_address}/#{name}"
end
end
def s3_url
"s3://#{s3_bucket}/#{s3_object}"
end
def export_image(image)
ensure_present! :name
if registry.nil?
ensure_present! :build_dir
info "Exporting the image with id #{image.id} to file #{File.expand_path(tar_path)}"
container = image.run('true')
info "created the container: #{container.id}"
unless s3_bucket.nil?
output = Dockly::AWS::S3Writer.new(connection, s3_bucket, s3_object)
else
output = File.open(tar_path, 'wb')
end
gzip_output = Zlib::GzipWriter.new(output)
if tar_diff
export_image_diff(container, gzip_output)
else
export_image_whole(container, gzip_output)
end
else
push_to_registry(image)
end
rescue
if output && !s3_bucket.nil?
output.abort_unless_closed
end
ensure
gzip_output.close if gzip_output
end
def export_image_whole(container, output)
container.export do |chunk, remaining, total|
output.write(chunk)
end
end
def export_image_diff(container, output)
rd, wr = IO.pipe(Encoding::ASCII_8BIT)
thread = Thread.new do
begin
if Dockly::Util::Tar.is_tar?(fetch_import)
base = File.open(fetch_import, 'rb')
else
base = Zlib::GzipReader.new(File.open(fetch_import, 'rb'))
end
td = Dockly::TarDiff.new(base, rd, output)
td.process
info "done writing the docker tar: #{export_filename}"
ensure
base.close if base
rd.close
end
end
begin
container.export do |chunk, remaining, total|
wr.write(chunk)
end
ensure
wr.close
thread.join
end
end
def s3_object
output = "#{s3_object_prefix}"
output << "#{Dockly::Util::Git.git_sha}/"
output << "#{export_filename}"
end
def push_to_registry(image)
ensure_present! :registry
info "Exporting #{image.id} to Docker registry at #{registry.server_address}"
registry.authenticate!
image = Docker::Image.all(:all => true).find { |img|
img.id.start_with?(image.id) || image.id.start_with?(img.id)
}
raise "Could not find image after authentication" if image.nil?
image.push(registry.to_h, :registry => registry.server_address)
end
def fetch_import
ensure_present! :import
path = "/tmp/dockly-docker-import.#{name}.#{File.basename(import)}"
if File.exist?(path)
debug "already fetched #{import}"
else
debug "fetching #{import}"
File.open("#{path}.tmp", 'wb') do |file|
case import
when /^s3:\/\/(?<bucket_name>.+?)\/(?<object_path>.+)$/
connection.get_object(Regexp.last_match[:bucket_name],
Regexp.last_match[:object_path]) do |chunk, remaining, total|
file.write(chunk)
end
when /^https?:\/\//
Excon.get(import, :response_block => lambda { |chunk, remaining, total|
file.write(chunk)
})
else
raise "You can only import from S3 or a public url"
end
end
FileUtils.mv("#{path}.tmp", path, :force => true)
end
path
end
def repository(value = nil)
name(value)
end
private
def connection
Dockly::AWS.s3
end
end
|
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'mobilize-hdfs/version'
Gem::Specification.new do |gem|
gem.name = "mobilize-hdfs"
gem.version = Mobilize::Hdfs::VERSION
gem.authors = ["Cassio Paes-Leme"]
gem.email = ["cpaesleme@dena.com"]
gem.description = %q{Adds hdfs read, write, and copy support to mobilize-ssh}
gem.summary = %q{Adds hdfs read, write, and copy support to mobilize-ssh}
gem.homepage = "http://github.com/dena/mobilize-hdfs"
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_runtime_dependency "mobilize-ssh","1.374"
end
update authors, email, license and homepage
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'mobilize-hdfs/version'
Gem::Specification.new do |gem|
gem.name = "mobilize-hdfs"
gem.version = Mobilize::Hdfs::VERSION
gem.authors = ["Cassio Paes-Leme", "Ryosuke IWANAGA"]
gem.email = ["cpaesleme@dena.com", "riywo.jp@gmail.com"]
gem.license = "Apache License, Version 2.0"
gem.homepage = "http://github.com/DeNA/mobilize-hdfs"
gem.description = %q{Adds hdfs read, write, and copy support to mobilize-ssh}
gem.summary = %q{Adds hdfs read, write, and copy support to mobilize-ssh}
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_runtime_dependency "mobilize-ssh","1.374"
end
|
require "dotenv/substitutions/variable"
require "dotenv/substitutions/command" if RUBY_VERSION > "1.8.7"
module Dotenv
class FormatError < SyntaxError; end
# This class enables parsing of a string for key value pairs to be returned
# and stored in the Environment. It allows for variable substitutions and
# exporting of variables.
class Parser
@substitutions =
[Dotenv::Substitutions::Variable, Dotenv::Substitutions::Command]
LINE = /
\s*
(?:export\s+)? # optional export
([\w\.]+) # key
(?:\s*=\s*|:\s+?) # separator
( # optional value begin
'(?:\'|[^'])*' # single quoted value
| # or
"(?:\"|[^"])*" # double quoted value
| # or
[^#\r\n]+ # unquoted value
)? # value end
\s*
(?:\#.*)? # optional comment
/x
class << self
attr_reader :substitutions
def call(string)
new(string).call
end
end
def initialize(string)
@string = string
@hash = {}
end
def call
# Process matches
@string.scan(LINE).each do |key, value|
@hash[key] = parse_value(value || "")
end
# Process non-matches
@string.gsub(LINE, '').split(/[\n\r]+/).each do |line|
parse_line(line)
end
@hash
end
private
def parse_line(line)
if line.split.first == "export"
if variable_not_set?(line)
raise FormatError, "Line #{line.inspect} has an unset variable"
end
elsif line !~ /\A\s*(?:#.*)?\z/ # not comment or blank line
raise FormatError, "Line #{line.inspect} doesn't match format"
end
end
def parse_value(value)
# Remove surrounding quotes
value = value.strip.sub(/\A(['"])(.*)\1\z/, '\2')
if Regexp.last_match(1) == '"'
value = unescape_characters(expand_newlines(value))
end
if Regexp.last_match(1) != "'"
self.class.substitutions.each do |proc|
value = proc.call(value, @hash)
end
end
value
end
def unescape_characters(value)
value.gsub(/\\([^$])/, '\1')
end
def expand_newlines(value)
value.gsub('\n', "\n").gsub('\r', "\r")
end
def variable_not_set?(line)
!line.split[1..-1].all? { |var| @hash.member?(var) }
end
end
end
Fix original regex to escape slash
require "dotenv/substitutions/variable"
require "dotenv/substitutions/command" if RUBY_VERSION > "1.8.7"
module Dotenv
class FormatError < SyntaxError; end
# This class enables parsing of a string for key value pairs to be returned
# and stored in the Environment. It allows for variable substitutions and
# exporting of variables.
class Parser
@substitutions =
[Dotenv::Substitutions::Variable, Dotenv::Substitutions::Command]
LINE = /
\s*
(?:export\s+)? # optional export
([\w\.]+) # key
(?:\s*=\s*|:\s+?) # separator
( # optional value begin
'(?:\\'|[^'])*' # single quoted value
| # or
"(?:\\"|[^"])*" # double quoted value
| # or
[^#\r\n]+ # unquoted value
)? # value end
\s*
(?:\#.*)? # optional comment
/x
class << self
attr_reader :substitutions
def call(string)
new(string).call
end
end
def initialize(string)
@string = string
@hash = {}
end
def call
# Process matches
@string.scan(LINE).each do |key, value|
@hash[key] = parse_value(value || "")
end
# Process non-matches
@string.gsub(LINE, '').split(/[\n\r]+/).each do |line|
parse_line(line)
end
@hash
end
private
def parse_line(line)
if line.split.first == "export"
if variable_not_set?(line)
raise FormatError, "Line #{line.inspect} has an unset variable"
end
elsif line !~ /\A\s*(?:#.*)?\z/ # not comment or blank line
raise FormatError, "Line #{line.inspect} doesn't match format"
end
end
def parse_value(value)
# Remove surrounding quotes
value = value.strip.sub(/\A(['"])(.*)\1\z/, '\2')
if Regexp.last_match(1) == '"'
value = unescape_characters(expand_newlines(value))
end
if Regexp.last_match(1) != "'"
self.class.substitutions.each do |proc|
value = proc.call(value, @hash)
end
end
value
end
def unescape_characters(value)
value.gsub(/\\([^$])/, '\1')
end
def expand_newlines(value)
value.gsub('\n', "\n").gsub('\r', "\r")
end
def variable_not_set?(line)
!line.split[1..-1].all? { |var| @hash.member?(var) }
end
end
end
|
require "dotted_rulers/array"
require "dotted_rulers/version"
require "dotted_rulers/routing"
module DottedRulers
class Application
def call(env)
if env['PATH_INFO'] == '/favicon.ico'
return [404, {'Content-Type' => 'text/html'}[]]
end
klass, act = get_controller_and_action(env)
controller = klass.new(env)
begin
text = controller.send(act)
rescue Exception => e
return [500, {'Content-Type' => 'text/html'},
["Whoa! Something supper colossal happend.... ",
"Message from page: #{e.message}",
]
]
end
[200, {'Content-Type' => 'text/html'},
[text]]
end
end
class Controller
def initialize(env)
@env = env
end
def env
@env
end
end
end
accidently delected a comma
require "dotted_rulers/array"
require "dotted_rulers/version"
require "dotted_rulers/routing"
module DottedRulers
class Application
def call(env)
if env['PATH_INFO'] == '/favicon.ico'
return [404, {'Content-Type' => 'text/html'},[]]
end
klass, act = get_controller_and_action(env)
controller = klass.new(env)
begin
text = controller.send(act)
rescue Exception => e
return [500, {'Content-Type' => 'text/html'},
["Whoa! Something supper colossal happend.... ",
"Message from page: #{e}",
]
]
end
[200, {'Content-Type' => 'text/html'},
[text]]
end
end
class Controller
def initialize(env)
@env = env
end
def env
@env
end
end
end
|
module DR
class Eruby
#complement TOPLEVEL_BINDING
EMPTY_BINDING = binding()
module ClassHelpers
#process some ruby code
#run '_src' in its own execution context
#instead of binding(), binding: TOPLEVEL_BINDING may be useful to not
#pollute the source
def process_ruby(_src, src_info: nil, context: self, eval_binding: binding, wrap: :proc)
#stolen from Erubis
if _src.respond_to?(:read)
src_info=_src unless src_info
_src=_src.read
end
to_eval=case wrap
#todo: a lambda with local parameters to simulate local
#variables, cf Tilt
when :eval; _src
when :lambda; "lambda { |_context| #{_src} }"
when :proc; "Proc.new { |_context| #{_src} }"
when :module; "Module.new { |_context| #{_src} }"
end
_proc=eval(to_eval, eval_binding, "(process_ruby #{src_info})")
case wrap
when :lambda, :proc
#I don't think there is much value [*] to wrap _src into _proc,
#instance_eval("_src") and instance_eval(&_proc) seems to have
#the same effect on binding
#[*] apart from passing _context to _src, but we have 'self' already
#- it allows also to set up block local $SAFE level
#- and we can use break while this is not possible with a string
context.instance_eval(&_proc)
else
_proc
end
end
def eruby_include(template, opt={})
opt={bind: binding}.merge(opt)
file=File.expand_path(template)
Dir.chdir(File.dirname(file)) do |cwd|
erb = Engine.new(File.read(file))
#if context is not empty, then we probably want to evaluate
if opt[:evaluate] or opt[:context]
r=erb.evaluate(opt[:context])
else
r=erb.result(opt[:bind])
end
#if using erubis, it is better to invoke the template in <%= =%> than
#to use chomp=true
r=r.chomp if opt[:chomp]
return r
end
end
end
extend ClassHelpers
module EngineHelper
### Stolen from erubis
## eval(@src) with binding object
def result(_binding_or_hash=TOPLEVEL_BINDING)
_arg = _binding_or_hash
if _arg.is_a?(Hash)
_b = binding()
eval _arg.collect{|k,v| "#{k} = _arg[#{k.inspect}]; "}.join, _b
elsif _arg.is_a?(Binding)
_b = _arg
elsif _arg.nil?
_b = binding()
else
raise ArgumentError.new("#{self.class.name}#result(): argument should be Binding or Hash but passed #{_arg.class.name} object.")
end
return eval(@src, _b, (@filename || '(erubis'))
#erb.rb:
# if @safe_level
# proc {
# $SAFE = @safe_level
# eval(@src, b, (@filename || '(erb)'), @lineno)
# }.call
end
## invoke context.instance_eval(@src)
def evaluate(_context=Context.new)
_context = Context.new(_context) if _context.is_a?(Hash)
#return _context.instance_eval(@src, @filename || '(erubis)')
#@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)')
_proc ||= eval("proc { #{@src} }", binding(), @filename || '(eruby)')
return _context.instance_eval(&_proc)
end
## if object is an Class or Module then define instance method to it,
## else define singleton method to it.
def def_method(object, method_name, filename=nil)
m = object.is_a?(Module) ? :module_eval : :instance_eval
object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)')
#erb.rb: src = self.src.sub(/^(?!#|$)/) {"def #{methodname}\n"} << "\nend\n" #This pattern insert the 'def' after lines with leading comments
end
end
begin
require 'erubi'
Engine=::Erubi::Engine
rescue LoadError
require 'erubis'
Engine=::Erubis::Eruby
rescue LoadError
require 'erb'
Engine=::ERB
end
#prepend so that we have the same implementation
Engine.__send__(:prepend, EngineHelper)
end
## Copy/Pasted from erubis context.rb
##
## context object for Engine#evaluate
##
## ex.
## template = <<'END'
## Hello <%= @user %>!
## <% for item in @list %>
## - <%= item %>
## <% end %>
## END
##
## context = Erubis::Context.new(:user=>'World', :list=>['a','b','c'])
## # or
## # context = Erubis::Context.new
## # context[:user] = 'World'
## # context[:list] = ['a', 'b', 'c']
##
## eruby = Erubis::Eruby.new(template)
## print eruby.evaluate(context)
##
class Eruby::Context
include Enumerable
def initialize(hash=nil)
hash.each do |name, value|
self[name] = value
end if hash
end
def [](key)
return instance_variable_get("@#{key}")
end
def []=(key, value)
return instance_variable_set("@#{key}", value)
end
def keys
return instance_variables.collect { |name| name[1..-1] }
end
def each
instance_variables.each do |name|
key = name[1..-1]
value = instance_variable_get(name)
yield(key, value)
end
end
def to_hash
hash = {}
self.keys.each { |key| hash[key] = self[key] }
return hash
end
def update(context_or_hash)
arg = context_or_hash
if arg.is_a?(Hash)
arg.each do |key, val|
self[key] = val
end
else
arg.instance_variables.each do |varname|
key = varname[1..-1]
val = arg.instance_variable_get(varname)
self[key] = val
end
end
end
end
end
eruby.rb: start adding features from Tilt
module DR
class Eruby
#complement TOPLEVEL_BINDING
EMPTY_BINDING = binding
module ClassHelpers
#process some ruby code
#run '_src' in its own execution context
#instead of binding(), binding: TOPLEVEL_BINDING may be useful to not
#pollute the source
def process_ruby(_src, src_info: nil, context: nil, eval_binding: binding, wrap: :proc, variables: nil)
#stolen from Erubis
if _src.respond_to?(:read)
src_info=_src unless src_info
_src=_src.read
end
to_eval=case wrap
#todo: a lambda with local parameters to simulate local
#variables, cf Tilt
when :eval; _src
when :lambda; "lambda { |_context| #{_src} }"
when :proc; "Proc.new { |_context| #{_src} }"
when :module; "Module.new { |_context| #{_src} }"
end
_proc=eval(to_eval, eval_binding, "(process_ruby #{src_info})")
unless context.nil?
#I don't think there is much value [*] to wrap _src into _proc,
#instance_eval("_src") and instance_eval(&_proc) seems to have
#the same effect on binding
#[*] apart from passing _context to _src, but we have 'self' already
#- it allows also to set up block local $SAFE level
#- and we can use break while this is not possible with a string
context.instance_eval(&_proc)
else
_proc
end
end
def eruby_include(template, opt={})
file=File.expand_path(template)
Dir.chdir(File.dirname(file)) do |cwd|
erb = Engine.new(File.read(file))
#if context is not empty, then we probably want to evaluate
if opt[:evaluate] or opt[:context]
r=erb.evaluate(opt[:context])
else
bind=opt[:bind]||binding
r=erb.result(bind)
end
#if using erubis, it is better to invoke the template in <%= =%> than
#to use chomp=true
r=r.chomp if opt[:chomp]
return r
end
end
# add variables values to a binding; variables is a Hash
def add_variables(variables, _binding=TOPLEVEL_BINDING)
eval _arg.collect{|k,v| "#{k} = _arg[#{k.inspect}]; "}.join, _binding
_binding
end
end
extend ClassHelpers
module EngineHelper
### Stolen from erubis
## eval(@src) with binding object
def result(_binding_or_hash=TOPLEVEL_BINDING)
_arg = _binding_or_hash
if _arg.is_a?(Hash)
_b=self.class.add_variables(_arg, binding)
elsif _arg.is_a?(Binding)
_b = _arg
elsif _arg.nil?
_b = binding
else
raise ArgumentError.new("#{self.class.name}#result(): argument should be Binding or Hash but passed #{_arg.class.name} object.")
end
return eval(@src, _b, (@filename || '(erubis'))
#erb.rb:
# if @safe_level
# proc {
# $SAFE = @safe_level
# eval(@src, b, (@filename || '(erb)'), @lineno)
# }.call
end
## invoke context.instance_eval(@src)
def evaluate(_context=Context.new)
_context = Context.new(_context) if _context.is_a?(Hash)
#return _context.instance_eval(@src, @filename || '(erubis)')
#@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)')
_proc ||= eval("proc { #{@src} }", binding(), @filename || '(eruby)')
return _context.instance_eval(&_proc)
end
## if object is an Class or Module then define instance method to it,
## else define singleton method to it.
def def_method(object, method_name, filename=nil)
m = object.is_a?(Module) ? :module_eval : :instance_eval
object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)')
#erb.rb: src = self.src.sub(/^(?!#|$)/) {"def #{methodname}\n"} << "\nend\n" #This pattern insert the 'def' after lines with leading comments
end
end
begin
require 'erubi'
Engine=::Erubi::Engine
rescue LoadError
require 'erubis'
Engine=::Erubis::Eruby
rescue LoadError
require 'erb'
Engine=::ERB
end
#prepend so that we have the same implementation
Engine.__send__(:prepend, EngineHelper)
end
## Copy/Pasted from erubis context.rb
##
## context object for Engine#evaluate
##
## ex.
## template = <<'END'
## Hello <%= @user %>!
## <% for item in @list %>
## - <%= item %>
## <% end %>
## END
##
## context = Erubis::Context.new(:user=>'World', :list=>['a','b','c'])
## # or
## # context = Erubis::Context.new
## # context[:user] = 'World'
## # context[:list] = ['a', 'b', 'c']
##
## eruby = Erubis::Eruby.new(template)
## print eruby.evaluate(context)
##
class Eruby::Context
include Enumerable
def initialize(hash=nil)
hash.each do |name, value|
self[name] = value
end if hash
end
def [](key)
return instance_variable_get("@#{key}")
end
def []=(key, value)
return instance_variable_set("@#{key}", value)
end
def keys
return instance_variables.collect { |name| name[1..-1] }
end
def each
instance_variables.each do |name|
key = name[1..-1]
value = instance_variable_get(name)
yield(key, value)
end
end
def to_hash
hash = {}
self.keys.each { |key| hash[key] = self[key] }
return hash
end
def update(context_or_hash)
arg = context_or_hash
if arg.is_a?(Hash)
arg.each do |key, val|
self[key] = val
end
else
arg.instance_variables.each do |varname|
key = varname[1..-1]
val = arg.instance_variable_get(varname)
self[key] = val
end
end
end
end
end
|
require 'logger'
require 'forwardable'
module Dragonfly
class App
class << self
private :new # Hide 'new' - need to use 'instance'
def instance(name)
apps[name] ||= new
end
alias [] instance
private
def apps
@apps ||= {}
end
end
def initialize
@analyser, @processor, @encoder, @generator = Analyser.new, Processor.new, Encoder.new, Generator.new
@analyser.use_same_log_as(self)
@processor.use_same_log_as(self)
@encoder.use_same_log_as(self)
@generator.use_same_log_as(self)
@dos_protector = DosProtector.new(self, 'this is a secret yo')
end
include Configurable
extend Forwardable
def_delegator :datastore, :destroy
def_delegators :new_job, :fetch, :generate
def_delegator :server, :call
configurable_attr :datastore do DataStorage::FileDataStore.new end
configurable_attr :default_format
configurable_attr :cache_duration, 3600*24*365 # (1 year)
configurable_attr :fallback_mime_type, 'application/octet-stream'
configurable_attr :path_prefix
configurable_attr :protect_from_dos_attacks, true
configurable_attr :secret
configurable_attr :log do Logger.new('/var/tmp/dragonfly.log') end
attr_reader :analyser
attr_reader :processor
attr_reader :encoder
attr_reader :generator
def server
@server ||= (
app = self
Rack::Builder.new do
map app.mount_path do
use DosProtector, app.secret if app.protect_from_dos_attacks
run SimpleEndpoint.new(app)
end
end
)
end
def new_job
Job.new(self)
end
def endpoint(job=nil, &block)
block ? RoutedEndpoint.new(self, &block) : JobEndpoint.new(job)
end
def store(object, opts={})
datastore.store(TempObject.new(object, opts))
end
def register_analyser(*args, &block)
analyser.register(*args, &block)
end
configuration_method :register_analyser
def register_processor(*args, &block)
processor.register(*args, &block)
end
configuration_method :register_processor
def register_encoder(*args, &block)
encoder.register(*args, &block)
end
configuration_method :register_encoder
def register_generator(*args, &block)
generator.register(*args, &block)
end
configuration_method :register_generator
def register_mime_type(format, mime_type)
registered_mime_types[file_ext_string(format)] = mime_type
end
configuration_method :register_mime_type
def registered_mime_types
@registered_mime_types ||= Rack::Mime::MIME_TYPES.dup
end
def mime_type_for(format)
registered_mime_types[file_ext_string(format)]
end
def mount_path
path_prefix.blank? ? '/' : path_prefix
end
def url_for(job)
"#{path_prefix}/#{job.serialize}"
end
private
def file_ext_string(format)
'.' + format.to_s.downcase.sub(/^.*\./,'')
end
end
end
Can initialize App#new_job with content
require 'logger'
require 'forwardable'
module Dragonfly
class App
class << self
private :new # Hide 'new' - need to use 'instance'
def instance(name)
apps[name] ||= new
end
alias [] instance
private
def apps
@apps ||= {}
end
end
def initialize
@analyser, @processor, @encoder, @generator = Analyser.new, Processor.new, Encoder.new, Generator.new
@analyser.use_same_log_as(self)
@processor.use_same_log_as(self)
@encoder.use_same_log_as(self)
@generator.use_same_log_as(self)
@dos_protector = DosProtector.new(self, 'this is a secret yo')
end
include Configurable
extend Forwardable
def_delegator :datastore, :destroy
def_delegators :new_job, :fetch, :generate
def_delegator :server, :call
configurable_attr :datastore do DataStorage::FileDataStore.new end
configurable_attr :default_format
configurable_attr :cache_duration, 3600*24*365 # (1 year)
configurable_attr :fallback_mime_type, 'application/octet-stream'
configurable_attr :path_prefix
configurable_attr :protect_from_dos_attacks, true
configurable_attr :secret
configurable_attr :log do Logger.new('/var/tmp/dragonfly.log') end
attr_reader :analyser
attr_reader :processor
attr_reader :encoder
attr_reader :generator
def server
@server ||= (
app = self
Rack::Builder.new do
map app.mount_path do
use DosProtector, app.secret if app.protect_from_dos_attacks
run SimpleEndpoint.new(app)
end
end
)
end
def new_job(content=nil)
content ? Job.new(self, TempObject.new(content)) : Job.new(self)
end
def endpoint(job=nil, &block)
block ? RoutedEndpoint.new(self, &block) : JobEndpoint.new(job)
end
def store(object, opts={})
datastore.store(TempObject.new(object, opts))
end
def register_analyser(*args, &block)
analyser.register(*args, &block)
end
configuration_method :register_analyser
def register_processor(*args, &block)
processor.register(*args, &block)
end
configuration_method :register_processor
def register_encoder(*args, &block)
encoder.register(*args, &block)
end
configuration_method :register_encoder
def register_generator(*args, &block)
generator.register(*args, &block)
end
configuration_method :register_generator
def register_mime_type(format, mime_type)
registered_mime_types[file_ext_string(format)] = mime_type
end
configuration_method :register_mime_type
def registered_mime_types
@registered_mime_types ||= Rack::Mime::MIME_TYPES.dup
end
def mime_type_for(format)
registered_mime_types[file_ext_string(format)]
end
def mount_path
path_prefix.blank? ? '/' : path_prefix
end
def url_for(job)
"#{path_prefix}/#{job.serialize}"
end
private
def file_ext_string(format)
'.' + format.to_s.downcase.sub(/^.*\./,'')
end
end
end
|
require 'dragonfly'
require 'dragonfly_libvips'
require 'dragonfly_pdf/plugin'
require 'dragonfly_pdf/version'
module DragonflyPdf
class PageNotFound < RuntimeError; end
class UnsupportedFormat < RuntimeError; end
SUPPORTED_FORMATS = %w[pdf].freeze
SUPPORTED_OUTPUT_FORMATS = %w[png pam pbm pkm pnm pdf tga svg].uniq.sort
private
def self.stringify_keys(hash = {})
hash.each_with_object({}) { |(k, v), memo| memo[k.to_s] = v }
end
def self.symbolize_keys(hash = {})
hash.each_with_object({}) { |(k, v), memo| memo[k.to_sym] = v }
end
end
Remove tga output format
It causes mupdf to throw "cannot detect document format" error
require 'dragonfly'
require 'dragonfly_libvips'
require 'dragonfly_pdf/plugin'
require 'dragonfly_pdf/version'
module DragonflyPdf
class PageNotFound < RuntimeError; end
class UnsupportedFormat < RuntimeError; end
SUPPORTED_FORMATS = %w[pdf].freeze
SUPPORTED_OUTPUT_FORMATS = %w[png pam pbm pkm pnm pdf svg].uniq.sort
private
def self.stringify_keys(hash = {})
hash.each_with_object({}) { |(k, v), memo| memo[k.to_s] = v }
end
def self.symbolize_keys(hash = {})
hash.each_with_object({}) { |(k, v), memo| memo[k.to_sym] = v }
end
end
|
# Quick 1-file dsl accessor
module Dslify
module ClassMethods
def default_options(hsh={})
@default_dsl_options ||= hsh
end
end
module InstanceMethods
def default_dsl_options;self.class.default_options;end
def dsl_options(hsh={})
@dsl_options ||= default_dsl_options.merge(hsh)
end
alias :options :dsl_options
def set_vars_from_options(h={}, contxt=self)
h.each{|k,v| contxt.send k.to_sym, v }
end
def add_method(meth)
# instance_eval <<-EOM
# def #{meth}(n=nil)
# puts "called #{meth}(\#\{n\}) from \#\{self\}"
# n ? (__h[:#{meth}] = n) : __h[:#{meth}]
# end
# def #{meth}=(n)
# __h[:#{meth}] = n
# end
# EOM
end
def method_missing(m,*a,&block)
if block
if a.empty?
(a[0].class == self.class) ? a[0].instance_eval(&block) : super
else
inst = a[0]
inst.instance_eval(&block)
dsl_options[m] = inst
end
else
if a.empty?
if dsl_options.has_key?(m)
dsl_options[m]
elsif m.to_s.index("?") == (m.to_s.length - 1)
if options.has_key?(val = m.to_s.gsub(/\?/, '').to_sym)
options[val] != false
else
false
end
else
if self.class.superclass.respond_to?(:default_options) && self.class.superclass.default_options.has_key?(m)
self.class.superclass.default_options[m]
elsif ((respond_to? :parent) && (parent != self))
parent.send m, *a, &block
else
super
end
end
else
clean_meth = m.to_s.gsub(/\=/,"").to_sym
dsl_options[clean_meth] = (a.size > 1 ? a : a[0])
end
end
end
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end
Fixed set_vars_from_options
# Quick 1-file dsl accessor
module Dslify
module ClassMethods
def default_options(hsh={})
@default_dsl_options ||= hsh
end
end
module InstanceMethods
def default_dsl_options;self.class.default_options;end
def dsl_options(hsh={})
@dsl_options ||= default_dsl_options.merge(hsh)
end
alias :options :dsl_options
def set_vars_from_options(h, contxt=self)
h.each do |k,v|
if contxt.respond_to?(k.to_sym)
contxt.send k.to_sym, v
else
clean_meth = k.to_s.gsub(/\=/,"").to_sym
dsl_options[clean_meth] = v
end
end
end
def add_method(meth)
# instance_eval <<-EOM
# def #{meth}(n=nil)
# puts "called #{meth}(\#\{n\}) from \#\{self\}"
# n ? (__h[:#{meth}] = n) : __h[:#{meth}]
# end
# def #{meth}=(n)
# __h[:#{meth}] = n
# end
# EOM
end
def method_missing(m,*a,&block)
if block
if a.empty?
(a[0].class == self.class) ? a[0].instance_eval(&block) : super
else
inst = a[0]
inst.instance_eval(&block)
dsl_options[m] = inst
end
else
if a.empty?
if dsl_options.has_key?(m)
dsl_options[m]
elsif m.to_s.index("?") == (m.to_s.length - 1)
if options.has_key?(val = m.to_s.gsub(/\?/, '').to_sym)
options[val] != false
else
false
end
else
if self.class.superclass.respond_to?(:default_options) && self.class.superclass.default_options.has_key?(m)
self.class.superclass.default_options[m]
elsif ((respond_to? :parent) && (parent != self))
parent.send m, *a, &block
else
super
end
end
else
clean_meth = m.to_s.gsub(/\=/,"").to_sym
dsl_options[clean_meth] = (a.size > 1 ? a : a[0])
end
end
end
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end |
module Earth
VERSION = '0.4.4'
end
Version bump to 0.4.5
module Earth
VERSION = '0.4.5'
end
|
module Ethos
VERSION = '0.2.0.beta12'
end
Tag version as fourteenth beta
module Ethos
VERSION = '0.2.0.beta14'
end
|
require 'mail'
module Extruder
class Message
attr_accessor :metadata, :digest, :original_message
attr_writer :message
def initialize(msg, metadata, digest = nil)
@msg = msg
@metadata = metadata
set_digest(msg, digest)
end
def digest_as_hex
@digest.unpack('H*')[0]
end
def message
return @message unless @message.nil?
if @msg.is_a?(Mail::Message)
@message = @msg
else
@message = Mail.read_from_string(string_message)
end
end
def original_message
@original_message ||= string_message
end
private
def string_message
if @msg.is_a?(String)
@msg
elsif @msg.respond_to? :read
@msg = @msg.read
end
end
def set_digest(msg, digest)
if digest.nil?
if msg.is_a?(String)
hash = OpenSSL::Digest::SHA256.new
hash << msg
@digest = hash.digest
else
fail InvalidDigestError, 'a digest is required'
end
elsif digest.length == 32
@digest = digest
elsif digest.length == 64
if digest !~ /\A[a-fA-F0-9]{64}\z/
fail InvalidDigestError, 'digest must be a valid SHA-256 value'
end
@digest = [digest].pack('H*')
else
fail InvalidDigestError, 'digest must be a valid SHA-256 value'
end
end
end
class Store
include Enumerable
def each
unless @messages.nil?
@messages.each { |x| yield x }
return
end
@messages = []
(0..255).each do |x|
piece = '%02x' % x
dir = Dir.new(dirname(piece))
json_opts = {create_additions: false, symbolize_names: true}
# TODO: validate the SHA-256 value.
files = dir.each.sort.select { |file| /\A[0-9a-f]{62}\z/ =~ file }
files.each do |component|
file = File.join(dir.path, component)
metadata = JSON.load(File.new("#{file}.meta"), nil, json_opts)
m = Message.new File.new(file), metadata, "#{piece}#{component}"
@messages << m
yield m
end
end
end
def save_metadata
return unless @messages
@messages.each do |m|
f = File.new("#{filename(m)}.meta", 'w')
JSON.dump(m.metadata, f)
end
end
end
end
Read messages from queue as binary.
The default encoding used by Ruby for files is that of the current
locale, which on most systems is UTF-8. However, many mails are not
UTF-8, and the mail gem becomes unhappy if it gets strings which have
the wrong encoding. Read files as binary to ensure that the mail gem
can parse them correctly.
Signed-off-by: brian m. carlson <738bdd359be778fee9f0fc4e2934ad72f436ceda@crustytoothpaste.net>
require 'mail'
module Extruder
class Message
attr_accessor :metadata, :digest, :original_message
attr_writer :message
def initialize(msg, metadata, digest = nil)
@msg = msg
@metadata = metadata
set_digest(msg, digest)
end
def digest_as_hex
@digest.unpack('H*')[0]
end
def message
return @message unless @message.nil?
if @msg.is_a?(Mail::Message)
@message = @msg
else
@message = Mail.read_from_string(string_message)
end
end
def original_message
@original_message ||= string_message
end
private
def string_message
if @msg.is_a?(String)
@msg
elsif @msg.respond_to? :read
@msg = @msg.read
end
end
def set_digest(msg, digest)
if digest.nil?
if msg.is_a?(String)
hash = OpenSSL::Digest::SHA256.new
hash << msg
@digest = hash.digest
else
fail InvalidDigestError, 'a digest is required'
end
elsif digest.length == 32
@digest = digest
elsif digest.length == 64
if digest !~ /\A[a-fA-F0-9]{64}\z/
fail InvalidDigestError, 'digest must be a valid SHA-256 value'
end
@digest = [digest].pack('H*')
else
fail InvalidDigestError, 'digest must be a valid SHA-256 value'
end
end
end
class Store
include Enumerable
def each
unless @messages.nil?
@messages.each { |x| yield x }
return
end
@messages = []
(0..255).each do |x|
piece = '%02x' % x
dir = Dir.new(dirname(piece))
json_opts = {create_additions: false, symbolize_names: true}
# TODO: validate the SHA-256 value.
files = dir.each.sort.select { |file| /\A[0-9a-f]{62}\z/ =~ file }
files.each do |component|
file = File.join(dir.path, component)
metadata = JSON.load(File.new("#{file}.meta"), nil, json_opts)
m = Message.new File.new(file, 'rb'), metadata, "#{piece}#{component}"
@messages << m
yield m
end
end
end
def save_metadata
return unless @messages
@messages.each do |m|
f = File.new("#{filename(m)}.meta", 'w')
JSON.dump(m.metadata, f)
end
end
end
end
|
# orawls.rb
require 'rexml/document'
require 'facter'
require 'yaml'
def get_weblogic_user
weblogicUser = Facter.value('override_weblogic_user')
if weblogicUser.nil?
Puppet.debug 'orawls.rb weblogic user is oracle'
else
Puppet.debug "orawls.rb weblogic user is #{weblogicUser}"
return weblogicUser
end
'oracle'
end
def get_ora_inventory_path
os = Facter.value(:kernel)
if 'Linux' == os
ora_inventory_path = Facter.value('override_orainst_dir')
if ora_inventory_path.nil?
Puppet.debug 'ora_inventory_path is default to /etc'
return '/etc'
else
Puppet.debug "ora_inventory_path is overridden to #{ora_inventory_path}"
return ora_inventory_path
end
elsif 'SunOS' == os
return '/var/opt/oracle'
end
'/etc'
end
def get_user_home_path
os = Facter.value(:kernel)
if 'Linux' == os
return '/home'
elsif 'SunOS' == os
return '/export/home'
end
'/home'
end
# read middleware home in the oracle home folder
def get_middleware_1036_home
beafile = get_user_home_path + '/' + get_weblogic_user + '/bea/beahomelist'
if FileTest.exists?(beafile)
output = File.read(beafile)
if output.nil?
return nil
else
return output.split(/;/)
end
else
return nil
end
end
def get_middleware_1212_home(name)
elements = []
name.split(/;/).each_with_index { |element, index|
elements.push(element) if FileTest.exists?(element + '/wlserver')
}
elements
end
def get_orainst_loc
if FileTest.exists?(get_ora_inventory_path + '/oraInst.loc')
str = ''
output = File.read(get_ora_inventory_path + '/oraInst.loc')
output.split(/\r?\n/).each do |item|
str = item[14, 50] if item.match(/^inventory_loc/)
end
return str
else
return 'NotFound'
end
end
def get_orainst_products(path)
# puts "get_orainst_products with path: "+path
unless path.nil?
if FileTest.exists?(path + '/ContentsXML/inventory.xml')
file = File.read(path + '/ContentsXML/inventory.xml')
doc = REXML::Document.new file
software = ''
patches_fact = {}
doc.elements.each('/INVENTORY/HOME_LIST/HOME') do |element|
str = element.attributes['LOC']
unless str.nil?
software += str + ';'
if str.include? 'plugins'
# skip EM agent
elsif str.include? 'agent'
# skip EM agent
elsif str.include? 'OraPlaceHolderDummyHome'
# skip EM agent
else
home = str.gsub('/', '_').gsub("\\", '_').gsub('c:', '_c').gsub('d:', '_d').gsub('e:', '_e')
opatchver = get_opatch_version(str)
Facter.add("orawls_inst_opatch#{home}") do
setcode do
opatchver
end
end
patches = get_opatch_patches(str)
# Puppet.info "-patches hash- #{patches}"
patches_fact[str] = patches unless patches.nil?
end
end
end
Facter.add('ora_mdw_opatch_patches') do
# Puppet.info "-all patches hash- #{patches_fact}"
setcode { patches_fact }
end
return software
else
return 'NotFound'
end
end
'NotFound'
end
# read weblogic domain
def get_domain(domain_path, n)
prefix = 'ora_mdw'
domainfile = domain_path + '/config/config.xml'
return if FileTest.exists?(domainfile) == false
file = File.read(domainfile)
doc = REXML::Document.new file
root = doc.root
Facter.add("#{prefix}_domain_#{n}") do
setcode do
domain_path
end
end
Puppet.debug "orawls.rb #{prefix}_domain_#{n} #{domain_path}"
Facter.add("#{prefix}_domain_#{n}_name") do
setcode do
root.elements['name'].text
end
end
file = File.read(domainfile)
doc = REXML::Document.new file
root = doc.root
Facter.add("#{prefix}_domain_#{n}") do
setcode do
root.elements['name'].text
end
end
Puppet.debug 'orawls.rb check authentication provider'
oimconfigured = 'false'
root.elements.to_a('security-configuration/realm//sec:name').each do |provider|
# Puppet.debug "orawls.rb check 2 authentication #{provider} "
if (provider.text == 'OIMAuthenticationProvider')
Puppet.debug 'orawls.rb oimconfigured is true'
oimconfigured = 'true'
end
end
Facter.add("#{prefix}_domain_#{n}_oim_configured") do
setcode do
oimconfigured
end
end
k = 0
root.elements.each('server') do |server|
Facter.add("#{prefix}_domain_#{n}_server_#{k}") do
setcode do
server.elements['name'].text
end
end
port = server.elements['listen-port']
unless port.nil?
Facter.add("#{prefix}_domain_#{n}_server_#{k}_port") do
setcode do
port.text
end
end
end
machine = server.elements['machine']
unless machine.nil?
Facter.add("#{prefix}_domain_#{n}_server_#{k}_machine") do
setcode do
machine.text
end
end
end
k += 1
end
servers = ''
root.elements.each('server') do |svr|
servers += svr.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_servers") do
setcode do
servers
end
end
machines = ''
root.elements.each('machine') do |mch|
machines += mch.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_machines") do
setcode do
machines
end
end
server_templates = ''
root.elements.each('server-template') do |svr_template|
server_templates += svr_template.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_server_templates") do
setcode do
server_templates
end
end
clusters = ''
root.elements.each('cluster') do |cluster|
clusters += cluster.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_clusters") do
setcode do
clusters
end
end
coherence_clusters = ''
root.elements.each('coherence-cluster-system-resource') do |coherence|
coherence_clusters += coherence.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_coherence_clusters") do
setcode do
coherence_clusters
end
end
bpmTargets = nil
soaTargets = nil
osbTargets = nil
bamTargets = nil
deployments = ''
root.elements.each("app-deployment[module-type = 'ear']") do |apps|
earName = apps.elements['name'].text
deployments += earName + ';'
bpmTargets = apps.elements['target'].text if earName == 'BPMComposer'
soaTargets = apps.elements['target'].text if earName == 'soa-infra'
osbTargets = apps.elements['target'].text if earName == 'ALSB Routing' || earName == 'Service Bus Routing'
bamTargets = apps.elements['target'].text if earName == 'oracle-bam#11.1.1' || earName == 'BamServer'
end
Facter.add("#{prefix}_domain_#{n}_deployments") do
setcode do
deployments
end
end
unless bpmTargets.nil?
Facter.add("#{prefix}_domain_#{n}_bpm") do
setcode do
bpmTargets
end
end
Puppet.debug "orawls.rb #{prefix}_domain_#{n}_bpm #{bpmTargets}"
else
Facter.add("#{prefix}_domain_#{n}_bpm") do
setcode do
'NotFound'
end
end
end
unless soaTargets.nil?
Facter.add("#{prefix}_domain_#{n}_soa") do
setcode do
soaTargets
end
end
Puppet.debug "orawls.rb #{prefix}_domain_#{n}_soa #{soaTargets}"
else
Facter.add("#{prefix}_domain_#{n}_soa") do
setcode do
'NotFound'
end
end
end
unless osbTargets.nil?
Facter.add("#{prefix}_domain_#{n}_osb") do
setcode do
osbTargets
end
end
Puppet.debug "orawls.rb #{prefix}_domain_#{n}_osb #{osbTargets}"
else
Facter.add("#{prefix}_domain_#{n}_osb") do
setcode do
'NotFound'
end
end
end
unless bamTargets.nil?
Facter.add("#{prefix}_domain_#{n}_bam") do
setcode do
bamTargets
end
end
else
Facter.add("#{prefix}_domain_#{n}_bam") do
setcode do
'NotFound'
end
end
end
fileAdapterPlan = ''
fileAdapterPlanEntries = ''
root.elements.each("app-deployment[name = 'FileAdapter']") do |apps|
unless apps.elements['plan-path'].nil?
unless apps.elements['plan-dir'].attributes['xsi:nil'] == 'true'
fileAdapterPlan += apps.elements['plan-dir'].text + '/' + apps.elements['plan-path'].text
else
fileAdapterPlan += apps.elements['plan-path'].text
end
if FileTest.exists?(fileAdapterPlan)
subfile = File.read(fileAdapterPlan)
subdoc = REXML::Document.new subfile
planroot = subdoc.root
planroot.elements['variable-definition'].elements.each('variable') do |eis|
entry = eis.elements['value'].text
fileAdapterPlanEntries += eis.elements['value'].text + ';'
end
end
end
end
Facter.add("#{prefix}_domain_#{n}_eis_fileadapter_plan") do
setcode do
fileAdapterPlan
end
end
Facter.add("#{prefix}_domain_#{n}_eis_fileadapter_entries") do
setcode do
fileAdapterPlanEntries
end
end
dbAdapterPlan = ''
dbAdapterPlanEntries = ''
root.elements.each("app-deployment[name = 'DbAdapter']") do |apps|
unless apps.elements['plan-path'].nil?
unless apps.elements['plan-dir'].attributes['xsi:nil'] == 'true'
dbAdapterPlan += apps.elements['plan-dir'].text + '/' + apps.elements['plan-path'].text
else
dbAdapterPlan += apps.elements['plan-path'].text
end
Puppet.debug "db #{dbAdapterPlan}"
if FileTest.exists?(dbAdapterPlan)
subfile = File.read(dbAdapterPlan)
subdoc = REXML::Document.new subfile
planroot = subdoc.root
planroot.elements['variable-definition'].elements.each('variable') do |eis|
entry = eis.elements['value'].text
if entry != nil and entry.include? 'eis'
dbAdapterPlanEntries += eis.elements['value'].text + ';'
end
end
end
end
end
Facter.add("#{prefix}_domain_#{n}_eis_dbadapter_plan") do
setcode do
dbAdapterPlan
end
end
Facter.add("#{prefix}_domain_#{n}_eis_dbadapter_entries") do
setcode do
dbAdapterPlanEntries
end
end
aqAdapterPlan = ''
aqAdapterPlanEntries = ''
root.elements.each("app-deployment[name = 'AqAdapter']") do |apps|
unless apps.elements['plan-path'].nil?
unless apps.elements['plan-dir'].attributes['xsi:nil'] == 'true'
aqAdapterPlan += apps.elements['plan-dir'].text + '/' + apps.elements['plan-path'].text
else
aqAdapterPlan += apps.elements['plan-path'].text
end
if FileTest.exists?(aqAdapterPlan)
subfile = File.read(aqAdapterPlan)
subdoc = REXML::Document.new subfile
planroot = subdoc.root
planroot.elements['variable-definition'].elements.each('variable') do |eis|
entry = eis.elements['value'].text
if entry != nil and entry.include? 'eis'
aqAdapterPlanEntries += eis.elements['value'].text + ';'
end
end
end
end
end
Facter.add("#{prefix}_domain_#{n}_eis_aqadapter_plan") do
setcode do
aqAdapterPlan
end
end
Facter.add("#{prefix}_domain_#{n}_eis_aqadapter_entries") do
setcode do
aqAdapterPlanEntries
end
end
jmsAdapterPlan = ''
jmsAdapterPlanEntries = ''
root.elements.each("app-deployment[name = 'JmsAdapter']") do |apps|
unless apps.elements['plan-path'].nil?
unless apps.elements['plan-dir'].attributes['xsi:nil'] == 'true'
jmsAdapterPlan += apps.elements['plan-dir'].text + '/' + apps.elements['plan-path'].text
else
jmsAdapterPlan += apps.elements['plan-path'].text
end
if FileTest.exists?(jmsAdapterPlan)
subfile = File.read(jmsAdapterPlan)
subdoc = REXML::Document.new subfile
planroot = subdoc.root
planroot.elements['variable-definition'].elements.each('variable') do |eis|
entry = eis.elements['value'].text
if entry != nil and entry.include? 'eis'
jmsAdapterPlanEntries += eis.elements['value'].text + ';'
end
end
end
end
end
Facter.add("#{prefix}_domain_#{n}_eis_jmsadapter_plan") do
setcode do
jmsAdapterPlan
end
end
Facter.add("#{prefix}_domain_#{n}_eis_jmsadapter_entries") do
setcode do
jmsAdapterPlanEntries
end
end
ftpAdapterPlan = ''
ftpAdapterPlanEntries = ''
root.elements.each("app-deployment[name = 'FtpAdapter']") do |apps|
unless apps.elements['plan-path'].nil?
unless apps.elements['plan-dir'].attributes['xsi:nil'] == 'true'
ftpAdapterPlan += apps.elements['plan-dir'].text + '/' + apps.elements['plan-path'].text
else
ftpAdapterPlan += apps.elements['plan-path'].text
end
Puppet.debug "ftp #{ftpAdapterPlan}"
if FileTest.exists?(ftpAdapterPlan)
subfile = File.read(ftpAdapterPlan)
subdoc = REXML::Document.new subfile
planroot = subdoc.root
planroot.elements['variable-definition'].elements.each('variable') do |eis|
entry = eis.elements['value'].text
Puppet.debug "ftp found entry #{entry}"
if entry != nil and entry.include? 'eis'
Puppet.debug "ftp eis entry " + eis.elements['value'].text
ftpAdapterPlanEntries += eis.elements['value'].text + ';'
end
end
end
end
end
Facter.add("#{prefix}_domain_#{n}_eis_ftpadapter_plan") do
setcode do
ftpAdapterPlan
end
end
Facter.add("#{prefix}_domain_#{n}_eis_ftpadapter_entries") do
setcode do
ftpAdapterPlanEntries
end
end
mQSeriesAdapterPlan = ''
mQSeriesAdapterPlanEntries = ''
root.elements.each("app-deployment[name = 'MQSeriesAdapter']") do |apps|
unless apps.elements['plan-path'].nil?
unless apps.elements['plan-dir'].attributes['xsi:nil'] == 'true'
mQSeriesAdapterPlan += apps.elements['plan-dir'].text + '/' + apps.elements['plan-path'].text
else
mQSeriesAdapterPlan += apps.elements['plan-path'].text
end
Puppet.debug "mqseries #{mQSeriesAdapterPlan}"
if FileTest.exists?(mQSeriesAdapterPlan)
subfile = File.read(mQSeriesAdapterPlan)
subdoc = REXML::Document.new subfile
planroot = subdoc.root
planroot.elements['variable-definition'].elements.each('variable') do |eis|
entry = eis.elements['value'].text
Puppet.debug "mqesries found entry #{entry}"
if entry != nil and entry.include? 'eis'
Puppet.debug "mqseries eis entry " + eis.elements['value'].text
mQSeriesAdapterPlanEntries += eis.elements['value'].text + ';'
end
end
end
end
end
Facter.add("#{prefix}_domain_#{n}_eis_mqseriesadapter_plan") do
setcode do
mQSeriesAdapterPlan
end
end
Facter.add("#{prefix}_domain_#{n}_eis_mqseriesadapter_entries") do
setcode do
mQSeriesAdapterPlanEntries
end
end
jrfTargets = nil
libraries = ''
root.elements.each('library') do |libs|
libName = libs.elements['name'].text
libraries += libName + ';'
if libName.include? 'adf.oracle.domain#1.0'
jrfTargets = libs.elements['target'].text
end
end
unless jrfTargets.nil?
Facter.add("#{prefix}_domain_#{n}_jrf") do
setcode do
jrfTargets
end
end
Puppet.debug "orawls.rb #{prefix}_domain_#{n}_jrf #{jrfTargets}"
else
Facter.add("#{prefix}_domain_#{n}_jrf") do
setcode do
'NotFound'
end
end
Puppet.debug "orawls.rb #{prefix}_domain_#{n}_jrf NotFound"
end
Facter.add("#{prefix}_domain_#{n}_libraries") do
setcode do
libraries
end
end
filestores = ''
root.elements.each('file-store') do |filestore|
filestores += filestore.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_filestores") do
setcode do
filestores
end
end
jdbcstores = ''
root.elements.each('jdbc-store') do |jdbc|
jdbcstores += jdbc.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_jdbcstores") do
setcode do
jdbcstores
end
end
safagents = ''
root.elements.each('saf-agent') do |agent|
safagents += agent.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_safagents") do
setcode do
safagents
end
end
jmsserversstr = ''
root.elements.each('jms-server') do |jmsservers|
jmsserversstr += jmsservers.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_jmsservers") do
setcode do
jmsserversstr
end
end
k = 0
jmsmodulestr = ''
root.elements.each('jms-system-resource') do |jmsresource|
jmsstr = ''
jmssubdeployments = ''
jmsmodulestr += jmsresource.elements['name'].text + ';'
jmsresource.elements.each('sub-deployment') do |sub|
jmssubdeployments += sub.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_#{k}_subdeployments") do
setcode do
jmssubdeployments
end
end
unless jmsresource.elements['descriptor-file-name'].nil?
fileJms = jmsresource.elements['descriptor-file-name'].text
else
fileJms = 'jms/' + jmsresource.elements['name'].text.downcase + '-jms.xml'
end
subfile = File.read(domain_path + '/config/' + fileJms)
subdoc = REXML::Document.new subfile
jmsroot = subdoc.root
jmsmoduleQuotaStr = ''
jmsroot.elements.each('quota') do |qu|
jmsmoduleQuotaStr += qu.attributes['name'] + ';'
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_#{k}_quotas") do
setcode do
jmsmoduleQuotaStr
end
end
jmsmoduleForeingServerStr = ''
jmsroot.elements.each('foreign-server') do |fs|
fsName = fs.attributes['name']
jmsmoduleForeingServerStr += fsName + ';'
jmsmoduleForeignServerObjectsStr = ''
fs.elements.each('foreign-destination') do |cf|
jmsmoduleForeignServerObjectsStr += cf.attributes['name'] + ';'
end
fs.elements.each('foreign-connection-factory') do |dest|
jmsmoduleForeignServerObjectsStr += dest.attributes['name'] + ';'
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_#{k}_foreign_server_#{fsName}_objects") do
setcode do
jmsmoduleForeignServerObjectsStr
end
end
# puts "#{prefix}_domain_#{n}_jmsmodule_#{k}_foreign_server_#{fsName}_objects"
# puts "values "+jmsmoduleForeignServerObjectsStr
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_#{k}_foreign_servers") do
setcode do
jmsmoduleForeingServerStr
end
end
# puts "#{prefix}_domain_#{n}_jmsmodule_#{k}_foreign_servers"
# puts "values "+jmsmoduleForeingServerStr
jmsroot.elements.each('connection-factory') do |cfs|
jmsstr += cfs.attributes['name'] + ';'
end
jmsroot.elements.each('queue') do |queues|
jmsstr += queues.attributes['name'] + ';'
end
jmsroot.elements.each('uniform-distributed-queue') do |dist_queues|
jmsstr += dist_queues.attributes['name'] + ';'
end
jmsroot.elements.each('topic') do |topics|
jmsstr += topics.attributes['name'] + ';'
end
jmsroot.elements.each('uniform-distributed-topic') do |dist_topics|
jmsstr += dist_topics.attributes['name'] + ';'
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_#{k}_name") do
setcode do
jmsresource.elements['name'].text
end
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_#{k}_objects") do
setcode do
jmsstr
end
end
k += 1
end
Facter.add("#{prefix}_domain_#{n}_jmsmodules") do
setcode do
jmsmodulestr
end
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_cnt") do
setcode do
k
end
end
jdbcstr = ''
root.elements.each('jdbc-system-resource') do |jdbcresource|
jdbcstr += jdbcresource.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_jdbc") do
setcode do
jdbcstr
end
end
end
oraInstPath = get_orainst_loc
oraProducts = get_orainst_products(oraInstPath)
mdw11gHomes = get_middleware_1036_home
mdw12cHomes = get_middleware_1212_home(oraProducts)
Puppet.debug "orawls.rb oraInstPath #{oraInstPath}"
Puppet.debug "orawls.rb oraProducts #{oraProducts}"
Puppet.debug "orawls.rb mdw11gHomes #{mdw11gHomes}"
Puppet.debug "orawls.rb mdw12cHomes #{mdw12cHomes}"
# report all oracle homes / domains
count = -1
unless mdw11gHomes.nil?
mdw11gHomes.each_with_index do |mdw, index|
count += 1
Facter.add("ora_mdw_#{count}") do
setcode do
mdw
end
end
end
end
unless mdw12cHomes.nil?
mdw12cHomes.each_with_index do |mdw, index|
count += 1
Facter.add("ora_mdw_#{count}") do
setcode do
mdw
end
end
end
end
count_domains = -1
def get_domains(domain_folder, count_domains)
# check all domain in a domains folder
if FileTest.exists?(domain_folder)
count_domains += 1
# add domain facts
get_domain(domain_folder, count_domains)
# add a full path domain fact
Facter.add("ora_mdw_domain_#{count_domains}") do
setcode do
domain_folder
end
end
end
count_domains
end
# get wls_domains.yaml file location if overridden
def get_wls_domains_file
wls_domains_file = Facter.value('override_wls_domains_file')
if wls_domains_file.nil?
Puppet.debug 'wls_domains_file is default to /etc/wls_domains.yaml'
else
Puppet.debug "wls_domains_file is overridden to #{wls_domains_file}"
return wls_domains_file
end
'/etc/wls_domains.yaml'
end
def get_opatch_version(name)
opatchOut = Facter::Util::Resolution.exec(name + '/OPatch/opatch version')
if opatchOut.nil?
opatchver = 'Error;'
else
opatchver = opatchOut.split(' ')[2]
end
Puppet.debug "oradb opatch #{opatchver}"
opatchver
end
# read the domains yaml and analyze domain
begin
wls_domains_file = get_wls_domains_file
entries = YAML.load(File.open(wls_domains_file))
unless entries.nil?
domains = entries['domains']
unless domains.nil?
domains.each { |key, values|
Puppet.debug "found #{key} with path #{values}"
count_domains = get_domains(values, count_domains)
}
end
end
rescue
Puppet.debug "#{wls_domains_file} not found"
end
Facter.add('ora_mdw_domain_cnt') do
setcode do
count_domains += 1
end
end
# all homes on 1 row
mdw_home_str = ''
unless mdw11gHomes.nil?
mdw11gHomes.each do |item|
mdw_home_str += item + ';'
end
end
unless mdw12cHomes.nil?
mdw12cHomes.each do |item|
mdw_home_str += item + ';'
end
end
Facter.add('ora_mdw_homes') do
setcode do
mdw_home_str
end
end
Puppet.debug "orawls.rb ora_mdw_homes #{mdw_home_str}"
# all home counter
mdw_count = 0
mdw_count = mdw11gHomes.count unless mdw11gHomes.nil?
mdw_count += mdw12cHomes.count unless mdw12cHomes.nil?
Facter.add('ora_mdw_cnt') do
setcode do
mdw_count
end
end
Puppet.debug "orawls.rb ora_mdw_cnt #{mdw_count}"
# get orainst loc data
Facter.add('ora_inst_loc_data') do
setcode do
oraInstPath
end
end
# get orainst products
Facter.add('ora_inst_products') do
setcode do
oraProducts
end
end
Fixed a debug message: oradb => orawls
# orawls.rb
require 'rexml/document'
require 'facter'
require 'yaml'
def get_weblogic_user
weblogicUser = Facter.value('override_weblogic_user')
if weblogicUser.nil?
Puppet.debug 'orawls.rb weblogic user is oracle'
else
Puppet.debug "orawls.rb weblogic user is #{weblogicUser}"
return weblogicUser
end
'oracle'
end
def get_ora_inventory_path
os = Facter.value(:kernel)
if 'Linux' == os
ora_inventory_path = Facter.value('override_orainst_dir')
if ora_inventory_path.nil?
Puppet.debug 'ora_inventory_path is default to /etc'
return '/etc'
else
Puppet.debug "ora_inventory_path is overridden to #{ora_inventory_path}"
return ora_inventory_path
end
elsif 'SunOS' == os
return '/var/opt/oracle'
end
'/etc'
end
def get_user_home_path
os = Facter.value(:kernel)
if 'Linux' == os
return '/home'
elsif 'SunOS' == os
return '/export/home'
end
'/home'
end
# read middleware home in the oracle home folder
def get_middleware_1036_home
beafile = get_user_home_path + '/' + get_weblogic_user + '/bea/beahomelist'
if FileTest.exists?(beafile)
output = File.read(beafile)
if output.nil?
return nil
else
return output.split(/;/)
end
else
return nil
end
end
def get_middleware_1212_home(name)
elements = []
name.split(/;/).each_with_index { |element, index|
elements.push(element) if FileTest.exists?(element + '/wlserver')
}
elements
end
def get_orainst_loc
if FileTest.exists?(get_ora_inventory_path + '/oraInst.loc')
str = ''
output = File.read(get_ora_inventory_path + '/oraInst.loc')
output.split(/\r?\n/).each do |item|
str = item[14, 50] if item.match(/^inventory_loc/)
end
return str
else
return 'NotFound'
end
end
def get_orainst_products(path)
# puts "get_orainst_products with path: "+path
unless path.nil?
if FileTest.exists?(path + '/ContentsXML/inventory.xml')
file = File.read(path + '/ContentsXML/inventory.xml')
doc = REXML::Document.new file
software = ''
patches_fact = {}
doc.elements.each('/INVENTORY/HOME_LIST/HOME') do |element|
str = element.attributes['LOC']
unless str.nil?
software += str + ';'
if str.include? 'plugins'
# skip EM agent
elsif str.include? 'agent'
# skip EM agent
elsif str.include? 'OraPlaceHolderDummyHome'
# skip EM agent
else
home = str.gsub('/', '_').gsub("\\", '_').gsub('c:', '_c').gsub('d:', '_d').gsub('e:', '_e')
opatchver = get_opatch_version(str)
Facter.add("orawls_inst_opatch#{home}") do
setcode do
opatchver
end
end
patches = get_opatch_patches(str)
# Puppet.info "-patches hash- #{patches}"
patches_fact[str] = patches unless patches.nil?
end
end
end
Facter.add('ora_mdw_opatch_patches') do
# Puppet.info "-all patches hash- #{patches_fact}"
setcode { patches_fact }
end
return software
else
return 'NotFound'
end
end
'NotFound'
end
# read weblogic domain
def get_domain(domain_path, n)
prefix = 'ora_mdw'
domainfile = domain_path + '/config/config.xml'
return if FileTest.exists?(domainfile) == false
file = File.read(domainfile)
doc = REXML::Document.new file
root = doc.root
Facter.add("#{prefix}_domain_#{n}") do
setcode do
domain_path
end
end
Puppet.debug "orawls.rb #{prefix}_domain_#{n} #{domain_path}"
Facter.add("#{prefix}_domain_#{n}_name") do
setcode do
root.elements['name'].text
end
end
file = File.read(domainfile)
doc = REXML::Document.new file
root = doc.root
Facter.add("#{prefix}_domain_#{n}") do
setcode do
root.elements['name'].text
end
end
Puppet.debug 'orawls.rb check authentication provider'
oimconfigured = 'false'
root.elements.to_a('security-configuration/realm//sec:name').each do |provider|
# Puppet.debug "orawls.rb check 2 authentication #{provider} "
if (provider.text == 'OIMAuthenticationProvider')
Puppet.debug 'orawls.rb oimconfigured is true'
oimconfigured = 'true'
end
end
Facter.add("#{prefix}_domain_#{n}_oim_configured") do
setcode do
oimconfigured
end
end
k = 0
root.elements.each('server') do |server|
Facter.add("#{prefix}_domain_#{n}_server_#{k}") do
setcode do
server.elements['name'].text
end
end
port = server.elements['listen-port']
unless port.nil?
Facter.add("#{prefix}_domain_#{n}_server_#{k}_port") do
setcode do
port.text
end
end
end
machine = server.elements['machine']
unless machine.nil?
Facter.add("#{prefix}_domain_#{n}_server_#{k}_machine") do
setcode do
machine.text
end
end
end
k += 1
end
servers = ''
root.elements.each('server') do |svr|
servers += svr.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_servers") do
setcode do
servers
end
end
machines = ''
root.elements.each('machine') do |mch|
machines += mch.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_machines") do
setcode do
machines
end
end
server_templates = ''
root.elements.each('server-template') do |svr_template|
server_templates += svr_template.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_server_templates") do
setcode do
server_templates
end
end
clusters = ''
root.elements.each('cluster') do |cluster|
clusters += cluster.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_clusters") do
setcode do
clusters
end
end
coherence_clusters = ''
root.elements.each('coherence-cluster-system-resource') do |coherence|
coherence_clusters += coherence.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_coherence_clusters") do
setcode do
coherence_clusters
end
end
bpmTargets = nil
soaTargets = nil
osbTargets = nil
bamTargets = nil
deployments = ''
root.elements.each("app-deployment[module-type = 'ear']") do |apps|
earName = apps.elements['name'].text
deployments += earName + ';'
bpmTargets = apps.elements['target'].text if earName == 'BPMComposer'
soaTargets = apps.elements['target'].text if earName == 'soa-infra'
osbTargets = apps.elements['target'].text if earName == 'ALSB Routing' || earName == 'Service Bus Routing'
bamTargets = apps.elements['target'].text if earName == 'oracle-bam#11.1.1' || earName == 'BamServer'
end
Facter.add("#{prefix}_domain_#{n}_deployments") do
setcode do
deployments
end
end
unless bpmTargets.nil?
Facter.add("#{prefix}_domain_#{n}_bpm") do
setcode do
bpmTargets
end
end
Puppet.debug "orawls.rb #{prefix}_domain_#{n}_bpm #{bpmTargets}"
else
Facter.add("#{prefix}_domain_#{n}_bpm") do
setcode do
'NotFound'
end
end
end
unless soaTargets.nil?
Facter.add("#{prefix}_domain_#{n}_soa") do
setcode do
soaTargets
end
end
Puppet.debug "orawls.rb #{prefix}_domain_#{n}_soa #{soaTargets}"
else
Facter.add("#{prefix}_domain_#{n}_soa") do
setcode do
'NotFound'
end
end
end
unless osbTargets.nil?
Facter.add("#{prefix}_domain_#{n}_osb") do
setcode do
osbTargets
end
end
Puppet.debug "orawls.rb #{prefix}_domain_#{n}_osb #{osbTargets}"
else
Facter.add("#{prefix}_domain_#{n}_osb") do
setcode do
'NotFound'
end
end
end
unless bamTargets.nil?
Facter.add("#{prefix}_domain_#{n}_bam") do
setcode do
bamTargets
end
end
else
Facter.add("#{prefix}_domain_#{n}_bam") do
setcode do
'NotFound'
end
end
end
fileAdapterPlan = ''
fileAdapterPlanEntries = ''
root.elements.each("app-deployment[name = 'FileAdapter']") do |apps|
unless apps.elements['plan-path'].nil?
unless apps.elements['plan-dir'].attributes['xsi:nil'] == 'true'
fileAdapterPlan += apps.elements['plan-dir'].text + '/' + apps.elements['plan-path'].text
else
fileAdapterPlan += apps.elements['plan-path'].text
end
if FileTest.exists?(fileAdapterPlan)
subfile = File.read(fileAdapterPlan)
subdoc = REXML::Document.new subfile
planroot = subdoc.root
planroot.elements['variable-definition'].elements.each('variable') do |eis|
entry = eis.elements['value'].text
fileAdapterPlanEntries += eis.elements['value'].text + ';'
end
end
end
end
Facter.add("#{prefix}_domain_#{n}_eis_fileadapter_plan") do
setcode do
fileAdapterPlan
end
end
Facter.add("#{prefix}_domain_#{n}_eis_fileadapter_entries") do
setcode do
fileAdapterPlanEntries
end
end
dbAdapterPlan = ''
dbAdapterPlanEntries = ''
root.elements.each("app-deployment[name = 'DbAdapter']") do |apps|
unless apps.elements['plan-path'].nil?
unless apps.elements['plan-dir'].attributes['xsi:nil'] == 'true'
dbAdapterPlan += apps.elements['plan-dir'].text + '/' + apps.elements['plan-path'].text
else
dbAdapterPlan += apps.elements['plan-path'].text
end
Puppet.debug "db #{dbAdapterPlan}"
if FileTest.exists?(dbAdapterPlan)
subfile = File.read(dbAdapterPlan)
subdoc = REXML::Document.new subfile
planroot = subdoc.root
planroot.elements['variable-definition'].elements.each('variable') do |eis|
entry = eis.elements['value'].text
if entry != nil and entry.include? 'eis'
dbAdapterPlanEntries += eis.elements['value'].text + ';'
end
end
end
end
end
Facter.add("#{prefix}_domain_#{n}_eis_dbadapter_plan") do
setcode do
dbAdapterPlan
end
end
Facter.add("#{prefix}_domain_#{n}_eis_dbadapter_entries") do
setcode do
dbAdapterPlanEntries
end
end
aqAdapterPlan = ''
aqAdapterPlanEntries = ''
root.elements.each("app-deployment[name = 'AqAdapter']") do |apps|
unless apps.elements['plan-path'].nil?
unless apps.elements['plan-dir'].attributes['xsi:nil'] == 'true'
aqAdapterPlan += apps.elements['plan-dir'].text + '/' + apps.elements['plan-path'].text
else
aqAdapterPlan += apps.elements['plan-path'].text
end
if FileTest.exists?(aqAdapterPlan)
subfile = File.read(aqAdapterPlan)
subdoc = REXML::Document.new subfile
planroot = subdoc.root
planroot.elements['variable-definition'].elements.each('variable') do |eis|
entry = eis.elements['value'].text
if entry != nil and entry.include? 'eis'
aqAdapterPlanEntries += eis.elements['value'].text + ';'
end
end
end
end
end
Facter.add("#{prefix}_domain_#{n}_eis_aqadapter_plan") do
setcode do
aqAdapterPlan
end
end
Facter.add("#{prefix}_domain_#{n}_eis_aqadapter_entries") do
setcode do
aqAdapterPlanEntries
end
end
jmsAdapterPlan = ''
jmsAdapterPlanEntries = ''
root.elements.each("app-deployment[name = 'JmsAdapter']") do |apps|
unless apps.elements['plan-path'].nil?
unless apps.elements['plan-dir'].attributes['xsi:nil'] == 'true'
jmsAdapterPlan += apps.elements['plan-dir'].text + '/' + apps.elements['plan-path'].text
else
jmsAdapterPlan += apps.elements['plan-path'].text
end
if FileTest.exists?(jmsAdapterPlan)
subfile = File.read(jmsAdapterPlan)
subdoc = REXML::Document.new subfile
planroot = subdoc.root
planroot.elements['variable-definition'].elements.each('variable') do |eis|
entry = eis.elements['value'].text
if entry != nil and entry.include? 'eis'
jmsAdapterPlanEntries += eis.elements['value'].text + ';'
end
end
end
end
end
Facter.add("#{prefix}_domain_#{n}_eis_jmsadapter_plan") do
setcode do
jmsAdapterPlan
end
end
Facter.add("#{prefix}_domain_#{n}_eis_jmsadapter_entries") do
setcode do
jmsAdapterPlanEntries
end
end
ftpAdapterPlan = ''
ftpAdapterPlanEntries = ''
root.elements.each("app-deployment[name = 'FtpAdapter']") do |apps|
unless apps.elements['plan-path'].nil?
unless apps.elements['plan-dir'].attributes['xsi:nil'] == 'true'
ftpAdapterPlan += apps.elements['plan-dir'].text + '/' + apps.elements['plan-path'].text
else
ftpAdapterPlan += apps.elements['plan-path'].text
end
Puppet.debug "ftp #{ftpAdapterPlan}"
if FileTest.exists?(ftpAdapterPlan)
subfile = File.read(ftpAdapterPlan)
subdoc = REXML::Document.new subfile
planroot = subdoc.root
planroot.elements['variable-definition'].elements.each('variable') do |eis|
entry = eis.elements['value'].text
Puppet.debug "ftp found entry #{entry}"
if entry != nil and entry.include? 'eis'
Puppet.debug "ftp eis entry " + eis.elements['value'].text
ftpAdapterPlanEntries += eis.elements['value'].text + ';'
end
end
end
end
end
Facter.add("#{prefix}_domain_#{n}_eis_ftpadapter_plan") do
setcode do
ftpAdapterPlan
end
end
Facter.add("#{prefix}_domain_#{n}_eis_ftpadapter_entries") do
setcode do
ftpAdapterPlanEntries
end
end
mQSeriesAdapterPlan = ''
mQSeriesAdapterPlanEntries = ''
root.elements.each("app-deployment[name = 'MQSeriesAdapter']") do |apps|
unless apps.elements['plan-path'].nil?
unless apps.elements['plan-dir'].attributes['xsi:nil'] == 'true'
mQSeriesAdapterPlan += apps.elements['plan-dir'].text + '/' + apps.elements['plan-path'].text
else
mQSeriesAdapterPlan += apps.elements['plan-path'].text
end
Puppet.debug "mqseries #{mQSeriesAdapterPlan}"
if FileTest.exists?(mQSeriesAdapterPlan)
subfile = File.read(mQSeriesAdapterPlan)
subdoc = REXML::Document.new subfile
planroot = subdoc.root
planroot.elements['variable-definition'].elements.each('variable') do |eis|
entry = eis.elements['value'].text
Puppet.debug "mqesries found entry #{entry}"
if entry != nil and entry.include? 'eis'
Puppet.debug "mqseries eis entry " + eis.elements['value'].text
mQSeriesAdapterPlanEntries += eis.elements['value'].text + ';'
end
end
end
end
end
Facter.add("#{prefix}_domain_#{n}_eis_mqseriesadapter_plan") do
setcode do
mQSeriesAdapterPlan
end
end
Facter.add("#{prefix}_domain_#{n}_eis_mqseriesadapter_entries") do
setcode do
mQSeriesAdapterPlanEntries
end
end
jrfTargets = nil
libraries = ''
root.elements.each('library') do |libs|
libName = libs.elements['name'].text
libraries += libName + ';'
if libName.include? 'adf.oracle.domain#1.0'
jrfTargets = libs.elements['target'].text
end
end
unless jrfTargets.nil?
Facter.add("#{prefix}_domain_#{n}_jrf") do
setcode do
jrfTargets
end
end
Puppet.debug "orawls.rb #{prefix}_domain_#{n}_jrf #{jrfTargets}"
else
Facter.add("#{prefix}_domain_#{n}_jrf") do
setcode do
'NotFound'
end
end
Puppet.debug "orawls.rb #{prefix}_domain_#{n}_jrf NotFound"
end
Facter.add("#{prefix}_domain_#{n}_libraries") do
setcode do
libraries
end
end
filestores = ''
root.elements.each('file-store') do |filestore|
filestores += filestore.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_filestores") do
setcode do
filestores
end
end
jdbcstores = ''
root.elements.each('jdbc-store') do |jdbc|
jdbcstores += jdbc.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_jdbcstores") do
setcode do
jdbcstores
end
end
safagents = ''
root.elements.each('saf-agent') do |agent|
safagents += agent.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_safagents") do
setcode do
safagents
end
end
jmsserversstr = ''
root.elements.each('jms-server') do |jmsservers|
jmsserversstr += jmsservers.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_jmsservers") do
setcode do
jmsserversstr
end
end
k = 0
jmsmodulestr = ''
root.elements.each('jms-system-resource') do |jmsresource|
jmsstr = ''
jmssubdeployments = ''
jmsmodulestr += jmsresource.elements['name'].text + ';'
jmsresource.elements.each('sub-deployment') do |sub|
jmssubdeployments += sub.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_#{k}_subdeployments") do
setcode do
jmssubdeployments
end
end
unless jmsresource.elements['descriptor-file-name'].nil?
fileJms = jmsresource.elements['descriptor-file-name'].text
else
fileJms = 'jms/' + jmsresource.elements['name'].text.downcase + '-jms.xml'
end
subfile = File.read(domain_path + '/config/' + fileJms)
subdoc = REXML::Document.new subfile
jmsroot = subdoc.root
jmsmoduleQuotaStr = ''
jmsroot.elements.each('quota') do |qu|
jmsmoduleQuotaStr += qu.attributes['name'] + ';'
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_#{k}_quotas") do
setcode do
jmsmoduleQuotaStr
end
end
jmsmoduleForeingServerStr = ''
jmsroot.elements.each('foreign-server') do |fs|
fsName = fs.attributes['name']
jmsmoduleForeingServerStr += fsName + ';'
jmsmoduleForeignServerObjectsStr = ''
fs.elements.each('foreign-destination') do |cf|
jmsmoduleForeignServerObjectsStr += cf.attributes['name'] + ';'
end
fs.elements.each('foreign-connection-factory') do |dest|
jmsmoduleForeignServerObjectsStr += dest.attributes['name'] + ';'
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_#{k}_foreign_server_#{fsName}_objects") do
setcode do
jmsmoduleForeignServerObjectsStr
end
end
# puts "#{prefix}_domain_#{n}_jmsmodule_#{k}_foreign_server_#{fsName}_objects"
# puts "values "+jmsmoduleForeignServerObjectsStr
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_#{k}_foreign_servers") do
setcode do
jmsmoduleForeingServerStr
end
end
# puts "#{prefix}_domain_#{n}_jmsmodule_#{k}_foreign_servers"
# puts "values "+jmsmoduleForeingServerStr
jmsroot.elements.each('connection-factory') do |cfs|
jmsstr += cfs.attributes['name'] + ';'
end
jmsroot.elements.each('queue') do |queues|
jmsstr += queues.attributes['name'] + ';'
end
jmsroot.elements.each('uniform-distributed-queue') do |dist_queues|
jmsstr += dist_queues.attributes['name'] + ';'
end
jmsroot.elements.each('topic') do |topics|
jmsstr += topics.attributes['name'] + ';'
end
jmsroot.elements.each('uniform-distributed-topic') do |dist_topics|
jmsstr += dist_topics.attributes['name'] + ';'
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_#{k}_name") do
setcode do
jmsresource.elements['name'].text
end
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_#{k}_objects") do
setcode do
jmsstr
end
end
k += 1
end
Facter.add("#{prefix}_domain_#{n}_jmsmodules") do
setcode do
jmsmodulestr
end
end
Facter.add("#{prefix}_domain_#{n}_jmsmodule_cnt") do
setcode do
k
end
end
jdbcstr = ''
root.elements.each('jdbc-system-resource') do |jdbcresource|
jdbcstr += jdbcresource.elements['name'].text + ';'
end
Facter.add("#{prefix}_domain_#{n}_jdbc") do
setcode do
jdbcstr
end
end
end
oraInstPath = get_orainst_loc
oraProducts = get_orainst_products(oraInstPath)
mdw11gHomes = get_middleware_1036_home
mdw12cHomes = get_middleware_1212_home(oraProducts)
Puppet.debug "orawls.rb oraInstPath #{oraInstPath}"
Puppet.debug "orawls.rb oraProducts #{oraProducts}"
Puppet.debug "orawls.rb mdw11gHomes #{mdw11gHomes}"
Puppet.debug "orawls.rb mdw12cHomes #{mdw12cHomes}"
# report all oracle homes / domains
count = -1
unless mdw11gHomes.nil?
mdw11gHomes.each_with_index do |mdw, index|
count += 1
Facter.add("ora_mdw_#{count}") do
setcode do
mdw
end
end
end
end
unless mdw12cHomes.nil?
mdw12cHomes.each_with_index do |mdw, index|
count += 1
Facter.add("ora_mdw_#{count}") do
setcode do
mdw
end
end
end
end
count_domains = -1
def get_domains(domain_folder, count_domains)
# check all domain in a domains folder
if FileTest.exists?(domain_folder)
count_domains += 1
# add domain facts
get_domain(domain_folder, count_domains)
# add a full path domain fact
Facter.add("ora_mdw_domain_#{count_domains}") do
setcode do
domain_folder
end
end
end
count_domains
end
# get wls_domains.yaml file location if overridden
def get_wls_domains_file
wls_domains_file = Facter.value('override_wls_domains_file')
if wls_domains_file.nil?
Puppet.debug 'wls_domains_file is default to /etc/wls_domains.yaml'
else
Puppet.debug "wls_domains_file is overridden to #{wls_domains_file}"
return wls_domains_file
end
'/etc/wls_domains.yaml'
end
def get_opatch_version(name)
opatchOut = Facter::Util::Resolution.exec(name + '/OPatch/opatch version')
if opatchOut.nil?
opatchver = 'Error;'
else
opatchver = opatchOut.split(' ')[2]
end
Puppet.debug "orawls opatch #{opatchver}"
opatchver
end
# read the domains yaml and analyze domain
begin
wls_domains_file = get_wls_domains_file
entries = YAML.load(File.open(wls_domains_file))
unless entries.nil?
domains = entries['domains']
unless domains.nil?
domains.each { |key, values|
Puppet.debug "found #{key} with path #{values}"
count_domains = get_domains(values, count_domains)
}
end
end
rescue
Puppet.debug "#{wls_domains_file} not found"
end
Facter.add('ora_mdw_domain_cnt') do
setcode do
count_domains += 1
end
end
# all homes on 1 row
mdw_home_str = ''
unless mdw11gHomes.nil?
mdw11gHomes.each do |item|
mdw_home_str += item + ';'
end
end
unless mdw12cHomes.nil?
mdw12cHomes.each do |item|
mdw_home_str += item + ';'
end
end
Facter.add('ora_mdw_homes') do
setcode do
mdw_home_str
end
end
Puppet.debug "orawls.rb ora_mdw_homes #{mdw_home_str}"
# all home counter
mdw_count = 0
mdw_count = mdw11gHomes.count unless mdw11gHomes.nil?
mdw_count += mdw12cHomes.count unless mdw12cHomes.nil?
Facter.add('ora_mdw_cnt') do
setcode do
mdw_count
end
end
Puppet.debug "orawls.rb ora_mdw_cnt #{mdw_count}"
# get orainst loc data
Facter.add('ora_inst_loc_data') do
setcode do
oraInstPath
end
end
# get orainst products
Facter.add('ora_inst_products') do
setcode do
oraProducts
end
end |
require 'time'
require 'webrick'
require 'webrick/https'
require 'openssl'
require 'securerandom'
require 'cgi'
require 'fakes3/file_store'
require 'fakes3/xml_adapter'
require 'fakes3/bucket_query'
require 'fakes3/unsupported_operation'
require 'fakes3/errors'
module FakeS3
class Request
CREATE_BUCKET = "CREATE_BUCKET"
LIST_BUCKETS = "LIST_BUCKETS"
LS_BUCKET = "LS_BUCKET"
HEAD = "HEAD"
STORE = "STORE"
COPY = "COPY"
GET = "GET"
GET_ACL = "GET_ACL"
SET_ACL = "SET_ACL"
MOVE = "MOVE"
DELETE_OBJECT = "DELETE_OBJECT"
DELETE_BUCKET = "DELETE_BUCKET"
attr_accessor :bucket,:object,:type,:src_bucket,
:src_object,:method,:webrick_request,
:path,:is_path_style,:query,:http_verb
def inspect
puts "-----Inspect FakeS3 Request"
puts "Type: #{@type}"
puts "Is Path Style: #{@is_path_style}"
puts "Request Method: #{@method}"
puts "Bucket: #{@bucket}"
puts "Object: #{@object}"
puts "Src Bucket: #{@src_bucket}"
puts "Src Object: #{@src_object}"
puts "Query: #{@query}"
puts "-----Done"
end
end
class Servlet < WEBrick::HTTPServlet::AbstractServlet
def initialize(server,store,hostname)
super(server)
@store = store
@hostname = hostname
@port = server.config[:Port]
@root_hostnames = [hostname,'localhost','s3.amazonaws.com','s3.localhost']
end
def validate_request(request)
req = request.webrick_request
return if req.nil?
return if not req.header.has_key?('expect')
req.continue if req.header['expect'].first=='100-continue'
end
def do_GET(request, response)
s_req = normalize_request(request)
case s_req.type
when 'LIST_BUCKETS'
response.status = 200
response['Content-Type'] = 'application/xml'
buckets = @store.buckets
response.body = XmlAdapter.buckets(buckets)
when 'LS_BUCKET'
bucket_obj = @store.get_bucket(s_req.bucket)
if bucket_obj
response.status = 200
response['Content-Type'] = "application/xml"
query = {
:marker => s_req.query["marker"] ? s_req.query["marker"].to_s : nil,
:prefix => s_req.query["prefix"] ? s_req.query["prefix"].to_s : nil,
:max_keys => s_req.query["max_keys"] ? s_req.query["max_keys"].to_s : nil,
:delimiter => s_req.query["delimiter"] ? s_req.query["delimiter"].to_s : nil
}
bq = bucket_obj.query_for_range(query)
response.body = XmlAdapter.bucket_query(bq)
else
response.status = 404
response.body = XmlAdapter.error_no_such_bucket(s_req.bucket)
response['Content-Type'] = "application/xml"
end
when 'GET_ACL'
response.status = 200
response.body = XmlAdapter.acl()
response['Content-Type'] = 'application/xml'
when 'GET'
real_obj = @store.get_object(s_req.bucket,s_req.object,request)
if !real_obj
response.status = 404
response.body = XmlAdapter.error_no_such_key(s_req.object)
response['Content-Type'] = "application/xml"
return
end
if_none_match = request["If-None-Match"]
if if_none_match == "\"#{real_obj.md5}\"" or if_none_match == "*"
response.status = 304
return
end
if_modified_since = request["If-Modified-Since"]
if if_modified_since
time = Time.httpdate(if_modified_since)
if time >= Time.iso8601(real_obj.modified_date)
response.status = 304
return
end
end
response.status = 200
response['Content-Type'] = real_obj.content_type
stat = File::Stat.new(real_obj.io.path)
response['Last-Modified'] = Time.iso8601(real_obj.modified_date).httpdate()
response.header['ETag'] = "\"#{real_obj.md5}\""
response['Accept-Ranges'] = "bytes"
response['Last-Ranges'] = "bytes"
response['Access-Control-Allow-Origin'] = '*'
real_obj.custom_metadata.each do |header, value|
response.header['x-amz-meta-' + header] = value
end
content_length = stat.size
# Added Range Query support
if range = request.header["range"].first
response.status = 206
if range =~ /bytes=(\d*)-(\d*)/
start = $1.to_i
finish = $2.to_i
finish_str = ""
if finish == 0
finish = content_length - 1
finish_str = "#{finish}"
else
finish_str = finish.to_s
end
bytes_to_read = finish - start + 1
response['Content-Range'] = "bytes #{start}-#{finish_str}/#{content_length}"
real_obj.io.pos = start
response.body = real_obj.io.read(bytes_to_read)
return
end
end
response['Content-Length'] = File::Stat.new(real_obj.io.path).size
if s_req.http_verb == 'HEAD'
response.body = ""
else
response.body = real_obj.io
end
end
end
def do_PUT(request,response)
s_req = normalize_request(request)
query = CGI::parse(request.request_uri.query || "")
return do_multipartPUT(request, response) if query['uploadId'].first
response.status = 200
response.body = ""
response['Content-Type'] = "text/xml"
response['Access-Control-Allow-Origin'] = '*'
case s_req.type
when Request::COPY
object = @store.copy_object(s_req.src_bucket,s_req.src_object,s_req.bucket,s_req.object,request)
response.body = XmlAdapter.copy_object_result(object)
when Request::STORE
bucket_obj = @store.get_bucket(s_req.bucket)
if !bucket_obj
# Lazily create a bucket. TODO fix this to return the proper error
bucket_obj = @store.create_bucket(s_req.bucket)
end
real_obj = @store.store_object(bucket_obj,s_req.object,s_req.webrick_request)
response.header['ETag'] = "\"#{real_obj.md5}\""
when Request::CREATE_BUCKET
@store.create_bucket(s_req.bucket)
end
end
def do_multipartPUT(request, response)
s_req = normalize_request(request)
query = CGI::parse(request.request_uri.query)
part_number = query['partNumber'].first
upload_id = query['uploadId'].first
part_name = "#{upload_id}_#{s_req.object}_part#{part_number}"
# store the part
if s_req.type == Request::COPY
real_obj = @store.copy_object(
s_req.src_bucket, s_req.src_object,
s_req.bucket , part_name,
request
)
response['Content-Type'] = "text/xml"
response.body = XmlAdapter.copy_object_result real_obj
else
bucket_obj = @store.get_bucket(s_req.bucket)
if !bucket_obj
bucket_obj = @store.create_bucket(s_req.bucket)
end
real_obj = @store.store_object(
bucket_obj, part_name,
request
)
response.body = ""
response.header['ETag'] = "\"#{real_obj.md5}\""
end
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = 'Authorization, Content-Length'
response['Access-Control-Expose-Headers'] = 'ETag'
response.status = 200
end
def do_POST(request,response)
s_req = normalize_request(request)
key = request.query['key']
query = CGI::parse(request.request_uri.query || "")
if query.has_key?('uploads')
upload_id = SecureRandom.hex
response.body = <<-eos.strip
<?xml version="1.0" encoding="UTF-8"?>
<InitiateMultipartUploadResult>
<Bucket>#{ s_req.bucket }</Bucket>
<Key>#{ key }</Key>
<UploadId>#{ upload_id }</UploadId>
</InitiateMultipartUploadResult>
eos
elsif query.has_key?('uploadId')
upload_id = query['uploadId'].first
bucket_obj = @store.get_bucket(s_req.bucket)
real_obj = @store.combine_object_parts(
bucket_obj,
upload_id,
s_req.object,
parse_complete_multipart_upload(request),
request
)
response.body = XmlAdapter.complete_multipart_result real_obj
elsif request.content_type =~ /^multipart\/form-data; boundary=(.+)/
key=request.query['key']
success_action_redirect = request.query['success_action_redirect']
success_action_status = request.query['success_action_status']
filename = 'default'
filename = $1 if request.body =~ /filename="(.*)"/
key = key.gsub('${filename}', filename)
bucket_obj = @store.get_bucket(s_req.bucket) || @store.create_bucket(s_req.bucket)
real_obj = @store.store_object(bucket_obj, key, s_req.webrick_request)
response['Etag'] = "\"#{real_obj.md5}\""
if success_action_redirect
response.status = 307
response.body = ""
response['Location'] = success_action_redirect
else
response.status = success_action_status || 204
if response.status == "201"
response.body = <<-eos.strip
<?xml version="1.0" encoding="UTF-8"?>
<PostResponse>
<Location>http://#{s_req.bucket}.localhost:#{@port}/#{key}</Location>
<Bucket>#{s_req.bucket}</Bucket>
<Key>#{key}</Key>
<ETag>#{response['Etag']}</ETag>
</PostResponse>
eos
end
end
else
raise WEBrick::HTTPStatus::BadRequest
end
response['Content-Type'] = 'text/xml'
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = 'Authorization, Content-Length'
response['Access-Control-Expose-Headers'] = 'ETag'
end
def do_DELETE(request,response)
s_req = normalize_request(request)
case s_req.type
when Request::DELETE_OBJECT
bucket_obj = @store.get_bucket(s_req.bucket)
@store.delete_object(bucket_obj,s_req.object,s_req.webrick_request)
when Request::DELETE_BUCKET
@store.delete_bucket(s_req.bucket)
end
response.status = 204
response.body = ""
end
def do_OPTIONS(request, response)
super
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'PUT, POST, HEAD, GET, OPTIONS'
response['Access-Control-Allow-Headers'] = 'Accept, Content-Type, Authorization, Content-Length, ETag'
response['Access-Control-Expose-Headers'] = 'ETag'
end
private
def normalize_delete(webrick_req,s_req)
path = webrick_req.path
path_len = path.size
query = webrick_req.query
if path == "/" and s_req.is_path_style
# Probably do a 404 here
else
if s_req.is_path_style
elems = path[1,path_len].split("/")
s_req.bucket = elems[0]
else
elems = path.split("/")
end
if elems.size == 0
raise UnsupportedOperation
elsif elems.size == 1
s_req.type = Request::DELETE_BUCKET
s_req.query = query
else
s_req.type = Request::DELETE_OBJECT
object = elems[1,elems.size].join('/')
s_req.object = object
end
end
end
def normalize_get(webrick_req,s_req)
path = webrick_req.path
path_len = path.size
query = webrick_req.query
if path == "/" and s_req.is_path_style
s_req.type = Request::LIST_BUCKETS
else
if s_req.is_path_style
elems = path[1,path_len].split("/")
s_req.bucket = elems[0]
else
elems = path.split("/")
end
if elems.size < 2
s_req.type = Request::LS_BUCKET
s_req.query = query
else
if query["acl"] == ""
s_req.type = Request::GET_ACL
else
s_req.type = Request::GET
end
object = elems[1,elems.size].join('/')
s_req.object = object
end
end
end
def normalize_put(webrick_req,s_req)
path = webrick_req.path
path_len = path.size
if path == "/"
if s_req.bucket
s_req.type = Request::CREATE_BUCKET
end
else
if s_req.is_path_style
elems = path[1,path_len].split("/")
s_req.bucket = elems[0]
if elems.size == 1
s_req.type = Request::CREATE_BUCKET
else
if webrick_req.request_line =~ /\?acl/
s_req.type = Request::SET_ACL
else
s_req.type = Request::STORE
end
s_req.object = elems[1,elems.size].join('/')
end
else
if webrick_req.request_line =~ /\?acl/
s_req.type = Request::SET_ACL
else
s_req.type = Request::STORE
end
s_req.object = webrick_req.path[1..-1]
end
end
# TODO: also parse the x-amz-copy-source-range:bytes=first-last header
# for multipart copy
copy_source = webrick_req.header["x-amz-copy-source"]
if copy_source and copy_source.size == 1
src_elems = copy_source.first.split("/")
root_offset = src_elems[0] == "" ? 1 : 0
s_req.src_bucket = src_elems[root_offset]
s_req.src_object = src_elems[1 + root_offset,src_elems.size].join("/")
s_req.type = Request::COPY
end
s_req.webrick_request = webrick_req
end
def normalize_post(webrick_req,s_req)
path = webrick_req.path
path_len = path.size
s_req.path = webrick_req.query['key']
s_req.webrick_request = webrick_req
if s_req.is_path_style
elems = path[1,path_len].split("/")
s_req.bucket = elems[0]
s_req.object = elems[1..-1].join('/') if elems.size >= 2
else
s_req.object = path[1..-1]
end
end
# This method takes a webrick request and generates a normalized FakeS3 request
def normalize_request(webrick_req)
host_header= webrick_req["Host"]
host = host_header.split(':')[0]
s_req = Request.new
s_req.path = webrick_req.path
s_req.is_path_style = true
if !@root_hostnames.include?(host)
s_req.bucket = host.split(".")[0]
s_req.is_path_style = false
end
s_req.http_verb = webrick_req.request_method
case webrick_req.request_method
when 'PUT'
normalize_put(webrick_req,s_req)
when 'GET','HEAD'
normalize_get(webrick_req,s_req)
when 'DELETE'
normalize_delete(webrick_req,s_req)
when 'POST'
normalize_post(webrick_req,s_req)
else
raise "Unknown Request"
end
validate_request(s_req)
return s_req
end
def parse_complete_multipart_upload request
parts_xml = ""
request.body { |chunk| parts_xml << chunk }
# TODO: I suck at parsing xml
parts_xml = parts_xml.scan /\<Part\>.*?<\/Part\>/m
parts_xml.collect do |xml|
{
number: xml[/\<PartNumber\>(\d+)\<\/PartNumber\>/, 1].to_i,
etag: xml[/\<ETag\>\"(.+)\"\<\/ETag\>/, 1]
}
end
end
def dump_request(request)
puts "----------Dump Request-------------"
puts request.request_method
puts request.path
request.each do |k,v|
puts "#{k}:#{v}"
end
puts "----------End Dump -------------"
end
end
class Server
def initialize(address,port,store,hostname,ssl_cert_path,ssl_key_path)
@address = address
@port = port
@store = store
@hostname = hostname
@ssl_cert_path = ssl_cert_path
@ssl_key_path = ssl_key_path
webrick_config = {
:BindAddress => @address,
:Port => @port
}
if !@ssl_cert_path.to_s.empty?
webrick_config.merge!(
{
:SSLEnable => true,
:SSLCertificate => OpenSSL::X509::Certificate.new(File.read(@ssl_cert_path)),
:SSLPrivateKey => OpenSSL::PKey::RSA.new(File.read(@ssl_key_path))
}
)
end
@server = WEBrick::HTTPServer.new(webrick_config)
end
def serve
@server.mount "/", Servlet, @store,@hostname
trap "INT" do @server.shutdown end
@server.start
end
def shutdown
@server.shutdown
end
end
end
Previously, when parsing the complete multipart upload, quotation marks were expected in the ETags. The Java client don't use quotation marks at all. To solve it:
- get away the quotations in the etag regex
- introduced a function to strip/trim caracters
- used that function to strip the "optional" quotation marks
Note: Im new to ruby so maybe there is a better way to strip. I used http://stackoverflow.com/questions/3165891/ruby-string-strip-defined-characters
require 'time'
require 'webrick'
require 'webrick/https'
require 'openssl'
require 'securerandom'
require 'cgi'
require 'fakes3/file_store'
require 'fakes3/xml_adapter'
require 'fakes3/bucket_query'
require 'fakes3/unsupported_operation'
require 'fakes3/errors'
module FakeS3
class Request
CREATE_BUCKET = "CREATE_BUCKET"
LIST_BUCKETS = "LIST_BUCKETS"
LS_BUCKET = "LS_BUCKET"
HEAD = "HEAD"
STORE = "STORE"
COPY = "COPY"
GET = "GET"
GET_ACL = "GET_ACL"
SET_ACL = "SET_ACL"
MOVE = "MOVE"
DELETE_OBJECT = "DELETE_OBJECT"
DELETE_BUCKET = "DELETE_BUCKET"
attr_accessor :bucket,:object,:type,:src_bucket,
:src_object,:method,:webrick_request,
:path,:is_path_style,:query,:http_verb
def inspect
puts "-----Inspect FakeS3 Request"
puts "Type: #{@type}"
puts "Is Path Style: #{@is_path_style}"
puts "Request Method: #{@method}"
puts "Bucket: #{@bucket}"
puts "Object: #{@object}"
puts "Src Bucket: #{@src_bucket}"
puts "Src Object: #{@src_object}"
puts "Query: #{@query}"
puts "-----Done"
end
end
class Servlet < WEBrick::HTTPServlet::AbstractServlet
def initialize(server,store,hostname)
super(server)
@store = store
@hostname = hostname
@port = server.config[:Port]
@root_hostnames = [hostname,'localhost','s3.amazonaws.com','s3.localhost']
end
def validate_request(request)
req = request.webrick_request
return if req.nil?
return if not req.header.has_key?('expect')
req.continue if req.header['expect'].first=='100-continue'
end
def do_GET(request, response)
s_req = normalize_request(request)
case s_req.type
when 'LIST_BUCKETS'
response.status = 200
response['Content-Type'] = 'application/xml'
buckets = @store.buckets
response.body = XmlAdapter.buckets(buckets)
when 'LS_BUCKET'
bucket_obj = @store.get_bucket(s_req.bucket)
if bucket_obj
response.status = 200
response['Content-Type'] = "application/xml"
query = {
:marker => s_req.query["marker"] ? s_req.query["marker"].to_s : nil,
:prefix => s_req.query["prefix"] ? s_req.query["prefix"].to_s : nil,
:max_keys => s_req.query["max_keys"] ? s_req.query["max_keys"].to_s : nil,
:delimiter => s_req.query["delimiter"] ? s_req.query["delimiter"].to_s : nil
}
bq = bucket_obj.query_for_range(query)
response.body = XmlAdapter.bucket_query(bq)
else
response.status = 404
response.body = XmlAdapter.error_no_such_bucket(s_req.bucket)
response['Content-Type'] = "application/xml"
end
when 'GET_ACL'
response.status = 200
response.body = XmlAdapter.acl()
response['Content-Type'] = 'application/xml'
when 'GET'
real_obj = @store.get_object(s_req.bucket,s_req.object,request)
if !real_obj
response.status = 404
response.body = XmlAdapter.error_no_such_key(s_req.object)
response['Content-Type'] = "application/xml"
return
end
if_none_match = request["If-None-Match"]
if if_none_match == "\"#{real_obj.md5}\"" or if_none_match == "*"
response.status = 304
return
end
if_modified_since = request["If-Modified-Since"]
if if_modified_since
time = Time.httpdate(if_modified_since)
if time >= Time.iso8601(real_obj.modified_date)
response.status = 304
return
end
end
response.status = 200
response['Content-Type'] = real_obj.content_type
stat = File::Stat.new(real_obj.io.path)
response['Last-Modified'] = Time.iso8601(real_obj.modified_date).httpdate()
response.header['ETag'] = "\"#{real_obj.md5}\""
response['Accept-Ranges'] = "bytes"
response['Last-Ranges'] = "bytes"
response['Access-Control-Allow-Origin'] = '*'
real_obj.custom_metadata.each do |header, value|
response.header['x-amz-meta-' + header] = value
end
content_length = stat.size
# Added Range Query support
if range = request.header["range"].first
response.status = 206
if range =~ /bytes=(\d*)-(\d*)/
start = $1.to_i
finish = $2.to_i
finish_str = ""
if finish == 0
finish = content_length - 1
finish_str = "#{finish}"
else
finish_str = finish.to_s
end
bytes_to_read = finish - start + 1
response['Content-Range'] = "bytes #{start}-#{finish_str}/#{content_length}"
real_obj.io.pos = start
response.body = real_obj.io.read(bytes_to_read)
return
end
end
response['Content-Length'] = File::Stat.new(real_obj.io.path).size
if s_req.http_verb == 'HEAD'
response.body = ""
else
response.body = real_obj.io
end
end
end
def do_PUT(request,response)
s_req = normalize_request(request)
query = CGI::parse(request.request_uri.query || "")
return do_multipartPUT(request, response) if query['uploadId'].first
response.status = 200
response.body = ""
response['Content-Type'] = "text/xml"
response['Access-Control-Allow-Origin'] = '*'
case s_req.type
when Request::COPY
object = @store.copy_object(s_req.src_bucket,s_req.src_object,s_req.bucket,s_req.object,request)
response.body = XmlAdapter.copy_object_result(object)
when Request::STORE
bucket_obj = @store.get_bucket(s_req.bucket)
if !bucket_obj
# Lazily create a bucket. TODO fix this to return the proper error
bucket_obj = @store.create_bucket(s_req.bucket)
end
real_obj = @store.store_object(bucket_obj,s_req.object,s_req.webrick_request)
response.header['ETag'] = "\"#{real_obj.md5}\""
when Request::CREATE_BUCKET
@store.create_bucket(s_req.bucket)
end
end
def do_multipartPUT(request, response)
s_req = normalize_request(request)
query = CGI::parse(request.request_uri.query)
part_number = query['partNumber'].first
upload_id = query['uploadId'].first
part_name = "#{upload_id}_#{s_req.object}_part#{part_number}"
# store the part
if s_req.type == Request::COPY
real_obj = @store.copy_object(
s_req.src_bucket, s_req.src_object,
s_req.bucket , part_name,
request
)
response['Content-Type'] = "text/xml"
response.body = XmlAdapter.copy_object_result real_obj
else
bucket_obj = @store.get_bucket(s_req.bucket)
if !bucket_obj
bucket_obj = @store.create_bucket(s_req.bucket)
end
real_obj = @store.store_object(
bucket_obj, part_name,
request
)
response.body = ""
response.header['ETag'] = "\"#{real_obj.md5}\""
end
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = 'Authorization, Content-Length'
response['Access-Control-Expose-Headers'] = 'ETag'
response.status = 200
end
def do_POST(request,response)
s_req = normalize_request(request)
key = request.query['key']
query = CGI::parse(request.request_uri.query || "")
if query.has_key?('uploads')
upload_id = SecureRandom.hex
response.body = <<-eos.strip
<?xml version="1.0" encoding="UTF-8"?>
<InitiateMultipartUploadResult>
<Bucket>#{ s_req.bucket }</Bucket>
<Key>#{ key }</Key>
<UploadId>#{ upload_id }</UploadId>
</InitiateMultipartUploadResult>
eos
elsif query.has_key?('uploadId')
upload_id = query['uploadId'].first
bucket_obj = @store.get_bucket(s_req.bucket)
real_obj = @store.combine_object_parts(
bucket_obj,
upload_id,
s_req.object,
parse_complete_multipart_upload(request),
request
)
response.body = XmlAdapter.complete_multipart_result real_obj
elsif request.content_type =~ /^multipart\/form-data; boundary=(.+)/
key=request.query['key']
success_action_redirect = request.query['success_action_redirect']
success_action_status = request.query['success_action_status']
filename = 'default'
filename = $1 if request.body =~ /filename="(.*)"/
key = key.gsub('${filename}', filename)
bucket_obj = @store.get_bucket(s_req.bucket) || @store.create_bucket(s_req.bucket)
real_obj = @store.store_object(bucket_obj, key, s_req.webrick_request)
response['Etag'] = "\"#{real_obj.md5}\""
if success_action_redirect
response.status = 307
response.body = ""
response['Location'] = success_action_redirect
else
response.status = success_action_status || 204
if response.status == "201"
response.body = <<-eos.strip
<?xml version="1.0" encoding="UTF-8"?>
<PostResponse>
<Location>http://#{s_req.bucket}.localhost:#{@port}/#{key}</Location>
<Bucket>#{s_req.bucket}</Bucket>
<Key>#{key}</Key>
<ETag>#{response['Etag']}</ETag>
</PostResponse>
eos
end
end
else
raise WEBrick::HTTPStatus::BadRequest
end
response['Content-Type'] = 'text/xml'
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = 'Authorization, Content-Length'
response['Access-Control-Expose-Headers'] = 'ETag'
end
def do_DELETE(request,response)
s_req = normalize_request(request)
case s_req.type
when Request::DELETE_OBJECT
bucket_obj = @store.get_bucket(s_req.bucket)
@store.delete_object(bucket_obj,s_req.object,s_req.webrick_request)
when Request::DELETE_BUCKET
@store.delete_bucket(s_req.bucket)
end
response.status = 204
response.body = ""
end
def do_OPTIONS(request, response)
super
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'PUT, POST, HEAD, GET, OPTIONS'
response['Access-Control-Allow-Headers'] = 'Accept, Content-Type, Authorization, Content-Length, ETag'
response['Access-Control-Expose-Headers'] = 'ETag'
end
private
def normalize_delete(webrick_req,s_req)
path = webrick_req.path
path_len = path.size
query = webrick_req.query
if path == "/" and s_req.is_path_style
# Probably do a 404 here
else
if s_req.is_path_style
elems = path[1,path_len].split("/")
s_req.bucket = elems[0]
else
elems = path.split("/")
end
if elems.size == 0
raise UnsupportedOperation
elsif elems.size == 1
s_req.type = Request::DELETE_BUCKET
s_req.query = query
else
s_req.type = Request::DELETE_OBJECT
object = elems[1,elems.size].join('/')
s_req.object = object
end
end
end
def normalize_get(webrick_req,s_req)
path = webrick_req.path
path_len = path.size
query = webrick_req.query
if path == "/" and s_req.is_path_style
s_req.type = Request::LIST_BUCKETS
else
if s_req.is_path_style
elems = path[1,path_len].split("/")
s_req.bucket = elems[0]
else
elems = path.split("/")
end
if elems.size < 2
s_req.type = Request::LS_BUCKET
s_req.query = query
else
if query["acl"] == ""
s_req.type = Request::GET_ACL
else
s_req.type = Request::GET
end
object = elems[1,elems.size].join('/')
s_req.object = object
end
end
end
def normalize_put(webrick_req,s_req)
path = webrick_req.path
path_len = path.size
if path == "/"
if s_req.bucket
s_req.type = Request::CREATE_BUCKET
end
else
if s_req.is_path_style
elems = path[1,path_len].split("/")
s_req.bucket = elems[0]
if elems.size == 1
s_req.type = Request::CREATE_BUCKET
else
if webrick_req.request_line =~ /\?acl/
s_req.type = Request::SET_ACL
else
s_req.type = Request::STORE
end
s_req.object = elems[1,elems.size].join('/')
end
else
if webrick_req.request_line =~ /\?acl/
s_req.type = Request::SET_ACL
else
s_req.type = Request::STORE
end
s_req.object = webrick_req.path[1..-1]
end
end
# TODO: also parse the x-amz-copy-source-range:bytes=first-last header
# for multipart copy
copy_source = webrick_req.header["x-amz-copy-source"]
if copy_source and copy_source.size == 1
src_elems = copy_source.first.split("/")
root_offset = src_elems[0] == "" ? 1 : 0
s_req.src_bucket = src_elems[root_offset]
s_req.src_object = src_elems[1 + root_offset,src_elems.size].join("/")
s_req.type = Request::COPY
end
s_req.webrick_request = webrick_req
end
def normalize_post(webrick_req,s_req)
path = webrick_req.path
path_len = path.size
s_req.path = webrick_req.query['key']
s_req.webrick_request = webrick_req
if s_req.is_path_style
elems = path[1,path_len].split("/")
s_req.bucket = elems[0]
s_req.object = elems[1..-1].join('/') if elems.size >= 2
else
s_req.object = path[1..-1]
end
end
# This method takes a webrick request and generates a normalized FakeS3 request
def normalize_request(webrick_req)
host_header= webrick_req["Host"]
host = host_header.split(':')[0]
s_req = Request.new
s_req.path = webrick_req.path
s_req.is_path_style = true
if !@root_hostnames.include?(host)
s_req.bucket = host.split(".")[0]
s_req.is_path_style = false
end
s_req.http_verb = webrick_req.request_method
case webrick_req.request_method
when 'PUT'
normalize_put(webrick_req,s_req)
when 'GET','HEAD'
normalize_get(webrick_req,s_req)
when 'DELETE'
normalize_delete(webrick_req,s_req)
when 'POST'
normalize_post(webrick_req,s_req)
else
raise "Unknown Request"
end
validate_request(s_req)
return s_req
end
def gral_strip(string, chars)
chars = Regexp.escape(chars)
string.gsub(/\A[#{chars}]+|[#{chars}]+\z/, "")
end
def parse_complete_multipart_upload request
parts_xml = ""
request.body { |chunk| parts_xml << chunk }
# TODO: I suck at parsing xml
parts_xml = parts_xml.scan /\<Part\>.*?<\/Part\>/m
parts_xml.collect do |xml|
{
number: xml[/\<PartNumber\>(\d+)\<\/PartNumber\>/, 1].to_i,
etag: gral_strip(xml[/\<ETag\>(.+)\<\/ETag\>/, 1], "\"")
}
end
end
def dump_request(request)
puts "----------Dump Request-------------"
puts request.request_method
puts request.path
request.each do |k,v|
puts "#{k}:#{v}"
end
puts "----------End Dump -------------"
end
end
class Server
def initialize(address,port,store,hostname,ssl_cert_path,ssl_key_path)
@address = address
@port = port
@store = store
@hostname = hostname
@ssl_cert_path = ssl_cert_path
@ssl_key_path = ssl_key_path
webrick_config = {
:BindAddress => @address,
:Port => @port
}
if !@ssl_cert_path.to_s.empty?
webrick_config.merge!(
{
:SSLEnable => true,
:SSLCertificate => OpenSSL::X509::Certificate.new(File.read(@ssl_cert_path)),
:SSLPrivateKey => OpenSSL::PKey::RSA.new(File.read(@ssl_key_path))
}
)
end
@server = WEBrick::HTTPServer.new(webrick_config)
end
def serve
@server.mount "/", Servlet, @store,@hostname
trap "INT" do @server.shutdown end
@server.start
end
def shutdown
@server.shutdown
end
end
end
|
module String_for_Safe_Writer
def folder_name
File.basename(File.dirname(self))
end
def name
File.basename(self)
end
end
class Safe_Writer
extend Delegator_DSL
attr_reader :config, :from_file, :write_file
delegate_to 'File', :expand_path
delegate_to 'config.ask', :verbose?, :syn_modified_time?
delegate_to 'config.get',
:read_folder, :write_folder,
:read_file, :write_file
def initialize &configs
@config = Config_Switches.new {
switch verbose, false
switch sync_modified_time, false
arrays :read_folder, :write_folder
arrays :read_file, :write_file
}
@config.put &configs
end
def from raw_file
@from_file = expand_path(raw_file)
@from_file.extend String_for_Safe_Writer
readable_from_file!
end
def write raw_file, raw_content
@write_file = expand_path(raw_file)
@write_file.extend String_for_Safe_Writer
content = raw_content.to_s
puts("Writing: #{write_file}") if verbose?
writable_file!( write_file )
File.open( write_file, 'w' ) do |io|
io.write content
end
if sync_modified_time? && has_from_file?
touch( from_file, write_file )
end
end
def touch *args
command = args.map { |str|
%~touch "#{str}"~
}.join( ' && ' )
`#{command}`
end
def readable_from_file!
validate_file! :read
end
def writable_from_file!
validate_file! :write
end
def validate_file! op
file = send("#{op}_file")
valid_folder = validate_default_true(read_folder, file.folder)
valid_file = validate_default_true(read_file, file.name)
unless valid_folder && valid_file
raise "Invalid file for #{op}: #{file}"
end
end
def validate_default_true validators, val
return true if validators.empty?
validate validators, val
end
def validate validators, val
validators.detect { |dator|
case dator
when String
val == dator
when Regexp
val =~ dator
end
}
end
end # === class
Bug fixes to Safe_Writer.
require 'models/Delegator_DSL'
module String_for_Safe_Writer
def folder
File.basename(File.dirname(self))
end
def name
File.basename(self)
end
end
class Safe_Writer
extend Delegator_DSL
attr_reader :config, :file
delegate_to 'File', :expand_path
delegate_to 'config.ask', :verbose?, :sync_modified_time?
delegate_to 'config.get',
:read_folder, :write_folder,
:read_file, :write_file
def initialize &configs
@file = Class.new {
attr_accessor :from, :to
def set op, raw_txt
txt = raw_txt.dup
txt.extend String_for_Safe_Writer
instance_variable_set( "@#{op}".to_sym, txt)
end
}.new
@config = Config_Switches.new {
switch :verbose, false
switch :sync_modified_time, false
arrays :read_folder, :write_folder
arrays :read_file, :write_file
}
@config.put &configs
end
def has_from_file?
!!(file.from)
end
def from raw_file
file.set :from, raw_file
readable_from_file!
self
end
def write raw_file, raw_content
file.set :to, raw_file
content = raw_content.to_s
writable_file!
puts("Writing: #{file.to}") if verbose?
File.open( file.to, 'w' ) do |io|
io.write content
end
if sync_modified_time? && has_from_file?
touch( file.from, file.to )
end
self
end
def touch *args
command = args.map { |str|
%~touch "#{str}"~
}.join( ' && ' )
`#{command}`
end
def readable_from_file!
validate_file! read_file, file.from, :read
end
def writable_file!
validate_file! write_file, file.to, :write
end
def validate_file! validators, file, op = "unknown action"
valid_folder = validate validators, file.folder
valid_file = validate validators, file.name
unless valid_folder && valid_file
raise "Invalid file for #{op}: #{file}"
end
end
def validate validators, val
return true if validators.empty?
validators.detect { |dator|
case dator
when String
val == dator
when Regexp
val =~ dator
end
}
end
end # === class
|
require 'ffi/pcap/bpf_instruction'
require 'ffi/pcap/bpf_program'
require 'enumerator'
module FFI
module PCap
DEFAULT_SNAPLEN = 65535 # Default snapshot length for packets
attach_function :pcap_lookupdev, [:pointer], :string
#
# Find the default device on which to capture.
#
# @return [String]
# Name of default device
#
# @raise [LibError]
# On failure, an exception is raised with the relevant error
# message from libpcap.
#
def PCap.lookupdev
e = ErrorBuffer.new
unless (name = PCap.pcap_lookupdev(e))
raise(LibError,"pcap_lookupdev(): #{e}",caller)
end
return name
end
attach_function :pcap_lookupnet, [:string, :pointer, :pointer, :pointer], :int
#
# Determine the IPv4 network number and mask relevant with a network
# device.
#
# @param [String] device
# The name of the device to look up.
#
# @yield [netp, maskp]
#
# @yieldparam [FFI::MemoryPointer] netp
# A pointer to the network return value.
#
# @yieldparam [FFI::MemoryPointer] maskp
# A pointer to the netmask return value.
#
# @return [nil, String]
# The IPv4 network number and mask presented as `n.n.n.n/m.m.m.m`.
# `nil` is returned when a block is specified.
#
# @raise [LibError]
# On failure, an exception is raised with the relevant error message
# from libpcap.
#
def PCap.lookupnet(device)
netp = MemoryPointer.new(find_type(:bpf_uint32))
maskp = MemoryPointer.new(find_type(:bpf_uint32))
errbuf = ErrorBuffer.new
unless PCap.pcap_lookupnet(device, netp, maskp, errbuf) == 0
raise(LibError, "pcap_lookupnet(): #{errbuf}",caller)
end
if block_given?
yield netp, maskp
else
net = netp.get_array_of_uchar(0,4).join('.')
net << '/'
net << maskp.get_array_of_uchar(0,4).join('.')
return net
end
end
#
# Opens a new Live device for capturing from the network. See
# {Live#initialize} for arguments.
#
# If passed a block, the block is passed to {Live#initialize} and the
# {Live} object is closed after completion of the block
#
def PCap.open_live(opts={},&block)
ret = Live.new(opts, &block)
return block_given? ? ret.close : ret
end
#
# Opens a new Dead pcap interface for compiling filters or opening
# a capture for output.
#
# @see Dead#initialize
#
def PCap.open_dead(opts={}, &block)
ret = Dead.new(opts, &block)
return block_given? ? ret.close : ret
end
#
# Opens a saved capture file for reading.
#
# @see Offline#initialize
#
def PCap.open_offline(path, opts={}, &block)
ret = Offline.new(path, opts={}, &block)
return block_given? ? ret.close : ret
end
#
# @see Pcap.open_offline
#
def PCap.open_file(path, opts={}, &block)
open_offline(path, opts, &block)
end
attach_function :pcap_findalldevs, [:pointer, :pointer], :int
attach_function :pcap_freealldevs, [Interface], :void
#
# List all capture devices and yield them each to a block.
#
# @yield [dev]
#
# @yieldparam [Interface] dev
# An Interface structure for each device.
#
# @return [nil]
#
# @raise [LibError]
# On failure, an exception is raised with the relevant error
# message from libpcap.
#
def PCap.each_device
devices = FFI::MemoryPointer.new(:pointer)
errbuf = ErrorBuffer.new
PCap.pcap_findalldevs(devices, errbuf)
node = devices.get_pointer(0)
if node.null?
raise(LibError,"pcap_findalldevs(): #{errbuf}",caller)
end
device = Interface.new(node)
while device
yield(device)
device = device.next
end
PCap.pcap_freealldevs(node)
return nil
end
#
# Returns an array of device name and network/netmask pairs for
# each interface found on the system.
#
# If an interface does not have an address assigned, its network/netmask
# value is returned as a nil value.
#
def PCap.dump_devices
PCap.enum_for(:each_device).map do |dev|
net = begin
PCap.lookupnet(dev.name)
rescue LibError
end
[dev.name, net]
end
end
#
# Returns an array of device names for each interface found on the
# system.
#
def PCap.device_names
PCap.enum_for(:each_device).map { |dev| dev.name }
end
attach_function :pcap_lib_version, [], :string
#
# Get the version information for libpcap.
#
# @return [String]
# Information about the version of the libpcap library being used;
# note that it contains more information than just a version number.
#
def PCap.lib_version
PCap.pcap_lib_version
end
#
# Extract just the version number from the {PCap.lib_version} string.
#
# @return [String]
# Version number.
#
def PCap.lib_version_number
if (version = PCap.lib_version.match(/libpcap version (\d+\.\d+.\d+)/))
return version[1]
end
end
attach_function :pcap_compile_nopcap, [:int, :int, BPFProgram, :string, :int, :bpf_uint32], :int
attach_function :bpf_filter, [BPFInstruction, :pointer, :uint, :uint], :uint
attach_function :bpf_validate, [BPFInstruction, :int], :int
attach_function :bpf_image, [BPFInstruction, :int], :string
attach_function :bpf_dump, [BPFProgram, :int], :void
attach_function :pcap_freecode, [BPFProgram], :void
# Unix Only:
begin
attach_function :pcap_get_selectable_fd, [:pcap_t], :int
#
# Drops privileges back to the uid of the SUDO_USER environment
# variable.
#
# Only available on Unix.
#
# This is useful for the paranoid when sudo is used to run a
# ruby pcap program as root.
#
# This method can generally be called right after a call to
# open_live() has returned a pcap handle or another privileged
# call has completed. Note, however, that once privileges are
# dropped, pcap functions that a require higher privilege will
# no longer work.
#
# @raise [StandardError]
# An error is raised if privileges cannot be dropped for
# some reason. This may be because the SUDO_USER environment
# variable is not set, because we already have a lower
# privilige and the SUDO_USER id is not the current uid,
# or because the SUDO_USER environment variable is not
# a valid user.
#
def PCap.drop_sudo_privs
if ENV["SUDO_USER"]
if (pwent = Etc.getpwnam(ENV["SUDO_USER"]))
Process::Sys.setgid(pwent.gid)
Process::Sys.setegid(pwent.gid)
Process::Sys.setuid(pwent.uid)
Process::Sys.seteuid(pwent.uid)
return true if (
Process::Sys.getuid == pwent.uid and
Process::Sys.geteuid == pwent.uid and
Process::Sys.getgid == pwent.gid and
Process::Sys.getegid == pwent.gid
)
end
end
raise(StandardError,"Unable to drop privileges",caller)
end
rescue FFI::NotFoundError
$pcap_not_unix = true
end
if $pcap_not_unix
# Win32 only:
begin
attach_function :pcap_setbuff, [:pcap_t, :int], :int
attach_function :pcap_setmode, [:pcap_t, :pcap_w32_modes_enum], :int
attach_function :pcap_setmintocopy, [:pcap_t, :int], :int
rescue FFI::NotFoundError
$pcap_not_win32 = true
end
end
if $pcap_not_win32
# MSDOS only???:
begin
attach_function :pcap_stats_ex, [:pcap_t, StatEx], :int
attach_function :pcap_set_wait, [:pcap_t, :pointer, :int], :void
attach_function :pcap_mac_packets, [], :ulong
rescue FFI::NotFoundError
end
end
attach_function :pcap_fileno, [:pcap_t], :int
### not sure if we want FILE stuff now or ever
#attach_function :pcap_fopen_offline, [:FILE, :pointer], :pcap_t
#attach_function :pcap_file, [:pcap_t], :FILE
#attach_function :pcap_dump_fopen, [:pcap_t, :FILE], :pcap_dumper_t
# MISC functions only in 1.0.0+
# They added a very different way of creating 'live' pcap handles
attach_optional_function :pcap_create, [:string, :pointer], :pcap_t
attach_optional_function :pcap_set_snaplen, [:pcap_t, :int], :int
attach_optional_function :pcap_set_promisc, [:pcap_t, :int], :int
attach_optional_function :pcap_can_set_rfmon, [:pcap_t, :int], :int
attach_optional_function :pcap_set_timeout, [:pcap_t, :int], :int
attach_optional_function :pcap_set_buffer_size, [:pcap_t, :int], :int
attach_optional_function :activate, [:pcap_t], :int
end
end
function "activate" should be "pcap_activate"
require 'ffi/pcap/bpf_instruction'
require 'ffi/pcap/bpf_program'
require 'enumerator'
module FFI
module PCap
DEFAULT_SNAPLEN = 65535 # Default snapshot length for packets
attach_function :pcap_lookupdev, [:pointer], :string
#
# Find the default device on which to capture.
#
# @return [String]
# Name of default device
#
# @raise [LibError]
# On failure, an exception is raised with the relevant error
# message from libpcap.
#
def PCap.lookupdev
e = ErrorBuffer.new
unless (name = PCap.pcap_lookupdev(e))
raise(LibError,"pcap_lookupdev(): #{e}",caller)
end
return name
end
attach_function :pcap_lookupnet, [:string, :pointer, :pointer, :pointer], :int
#
# Determine the IPv4 network number and mask relevant with a network
# device.
#
# @param [String] device
# The name of the device to look up.
#
# @yield [netp, maskp]
#
# @yieldparam [FFI::MemoryPointer] netp
# A pointer to the network return value.
#
# @yieldparam [FFI::MemoryPointer] maskp
# A pointer to the netmask return value.
#
# @return [nil, String]
# The IPv4 network number and mask presented as `n.n.n.n/m.m.m.m`.
# `nil` is returned when a block is specified.
#
# @raise [LibError]
# On failure, an exception is raised with the relevant error message
# from libpcap.
#
def PCap.lookupnet(device)
netp = MemoryPointer.new(find_type(:bpf_uint32))
maskp = MemoryPointer.new(find_type(:bpf_uint32))
errbuf = ErrorBuffer.new
unless PCap.pcap_lookupnet(device, netp, maskp, errbuf) == 0
raise(LibError, "pcap_lookupnet(): #{errbuf}",caller)
end
if block_given?
yield netp, maskp
else
net = netp.get_array_of_uchar(0,4).join('.')
net << '/'
net << maskp.get_array_of_uchar(0,4).join('.')
return net
end
end
#
# Opens a new Live device for capturing from the network. See
# {Live#initialize} for arguments.
#
# If passed a block, the block is passed to {Live#initialize} and the
# {Live} object is closed after completion of the block
#
def PCap.open_live(opts={},&block)
ret = Live.new(opts, &block)
return block_given? ? ret.close : ret
end
#
# Opens a new Dead pcap interface for compiling filters or opening
# a capture for output.
#
# @see Dead#initialize
#
def PCap.open_dead(opts={}, &block)
ret = Dead.new(opts, &block)
return block_given? ? ret.close : ret
end
#
# Opens a saved capture file for reading.
#
# @see Offline#initialize
#
def PCap.open_offline(path, opts={}, &block)
ret = Offline.new(path, opts={}, &block)
return block_given? ? ret.close : ret
end
#
# @see Pcap.open_offline
#
def PCap.open_file(path, opts={}, &block)
open_offline(path, opts, &block)
end
attach_function :pcap_findalldevs, [:pointer, :pointer], :int
attach_function :pcap_freealldevs, [Interface], :void
#
# List all capture devices and yield them each to a block.
#
# @yield [dev]
#
# @yieldparam [Interface] dev
# An Interface structure for each device.
#
# @return [nil]
#
# @raise [LibError]
# On failure, an exception is raised with the relevant error
# message from libpcap.
#
def PCap.each_device
devices = FFI::MemoryPointer.new(:pointer)
errbuf = ErrorBuffer.new
PCap.pcap_findalldevs(devices, errbuf)
node = devices.get_pointer(0)
if node.null?
raise(LibError,"pcap_findalldevs(): #{errbuf}",caller)
end
device = Interface.new(node)
while device
yield(device)
device = device.next
end
PCap.pcap_freealldevs(node)
return nil
end
#
# Returns an array of device name and network/netmask pairs for
# each interface found on the system.
#
# If an interface does not have an address assigned, its network/netmask
# value is returned as a nil value.
#
def PCap.dump_devices
PCap.enum_for(:each_device).map do |dev|
net = begin
PCap.lookupnet(dev.name)
rescue LibError
end
[dev.name, net]
end
end
#
# Returns an array of device names for each interface found on the
# system.
#
def PCap.device_names
PCap.enum_for(:each_device).map { |dev| dev.name }
end
attach_function :pcap_lib_version, [], :string
#
# Get the version information for libpcap.
#
# @return [String]
# Information about the version of the libpcap library being used;
# note that it contains more information than just a version number.
#
def PCap.lib_version
PCap.pcap_lib_version
end
#
# Extract just the version number from the {PCap.lib_version} string.
#
# @return [String]
# Version number.
#
def PCap.lib_version_number
if (version = PCap.lib_version.match(/libpcap version (\d+\.\d+.\d+)/))
return version[1]
end
end
attach_function :pcap_compile_nopcap, [:int, :int, BPFProgram, :string, :int, :bpf_uint32], :int
attach_function :bpf_filter, [BPFInstruction, :pointer, :uint, :uint], :uint
attach_function :bpf_validate, [BPFInstruction, :int], :int
attach_function :bpf_image, [BPFInstruction, :int], :string
attach_function :bpf_dump, [BPFProgram, :int], :void
attach_function :pcap_freecode, [BPFProgram], :void
# Unix Only:
begin
attach_function :pcap_get_selectable_fd, [:pcap_t], :int
#
# Drops privileges back to the uid of the SUDO_USER environment
# variable.
#
# Only available on Unix.
#
# This is useful for the paranoid when sudo is used to run a
# ruby pcap program as root.
#
# This method can generally be called right after a call to
# open_live() has returned a pcap handle or another privileged
# call has completed. Note, however, that once privileges are
# dropped, pcap functions that a require higher privilege will
# no longer work.
#
# @raise [StandardError]
# An error is raised if privileges cannot be dropped for
# some reason. This may be because the SUDO_USER environment
# variable is not set, because we already have a lower
# privilige and the SUDO_USER id is not the current uid,
# or because the SUDO_USER environment variable is not
# a valid user.
#
def PCap.drop_sudo_privs
if ENV["SUDO_USER"]
if (pwent = Etc.getpwnam(ENV["SUDO_USER"]))
Process::Sys.setgid(pwent.gid)
Process::Sys.setegid(pwent.gid)
Process::Sys.setuid(pwent.uid)
Process::Sys.seteuid(pwent.uid)
return true if (
Process::Sys.getuid == pwent.uid and
Process::Sys.geteuid == pwent.uid and
Process::Sys.getgid == pwent.gid and
Process::Sys.getegid == pwent.gid
)
end
end
raise(StandardError,"Unable to drop privileges",caller)
end
rescue FFI::NotFoundError
$pcap_not_unix = true
end
if $pcap_not_unix
# Win32 only:
begin
attach_function :pcap_setbuff, [:pcap_t, :int], :int
attach_function :pcap_setmode, [:pcap_t, :pcap_w32_modes_enum], :int
attach_function :pcap_setmintocopy, [:pcap_t, :int], :int
rescue FFI::NotFoundError
$pcap_not_win32 = true
end
end
if $pcap_not_win32
# MSDOS only???:
begin
attach_function :pcap_stats_ex, [:pcap_t, StatEx], :int
attach_function :pcap_set_wait, [:pcap_t, :pointer, :int], :void
attach_function :pcap_mac_packets, [], :ulong
rescue FFI::NotFoundError
end
end
attach_function :pcap_fileno, [:pcap_t], :int
### not sure if we want FILE stuff now or ever
#attach_function :pcap_fopen_offline, [:FILE, :pointer], :pcap_t
#attach_function :pcap_file, [:pcap_t], :FILE
#attach_function :pcap_dump_fopen, [:pcap_t, :FILE], :pcap_dumper_t
# MISC functions only in 1.0.0+
# They added a very different way of creating 'live' pcap handles
attach_optional_function :pcap_create, [:string, :pointer], :pcap_t
attach_optional_function :pcap_set_snaplen, [:pcap_t, :int], :int
attach_optional_function :pcap_set_promisc, [:pcap_t, :int], :int
attach_optional_function :pcap_can_set_rfmon, [:pcap_t, :int], :int
attach_optional_function :pcap_set_timeout, [:pcap_t, :int], :int
attach_optional_function :pcap_set_buffer_size, [:pcap_t, :int], :int
attach_optional_function :pcap_activate, [:pcap_t], :int
end
end
|
module FlagShihTzu
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'] # taken from ActiveRecord::ConnectionAdapters::Column
SQL_IN_LIMITATION = 16
def self.included(base)
base.extend(ClassMethods)
end
class IncorrectFlagColumnException < Exception; end
class NoSuchFlagException < Exception; end
module ClassMethods
def has_flags(*args)
flag_hash, options = parse_options(*args)
options = {:named_scopes => true, :column => 'flags', :verbose => false}.update(options)
class_inheritable_reader :flag_column
write_inheritable_attribute(:flag_column, options[:column])
return unless check_flag_column(flag_column)
class_inheritable_hash :flag_mapping
# if has_flags is used more than once in a single class, then flag_mapping will already have data in it in successive declarations
write_inheritable_attribute(:flag_mapping, {}) if flag_mapping.nil?
# initialize flag_mapping for this column
flag_mapping[flag_column] ||= {}
flag_hash.each do |flag_key, flag_name|
raise ArgumentError, "has_flags: flag keys should be positive integers, and #{flag_key} is not" unless is_valid_flag_key(flag_key)
raise ArgumentError, "has_flags: flag names should be symbols, and #{flag_name} is not" unless is_valid_flag_name(flag_name)
raise ArgumentError, "has_flags: flag name #{flag_name} already defined, please choose different name" if method_defined?(flag_name)
flag_mapping[flag_column][flag_name] = 1 << (flag_key - 1)
class_eval <<-EVAL
def #{flag_name}
flag_enabled?(:#{flag_name}, '#{flag_column}')
end
def #{flag_name}?
flag_enabled?(:#{flag_name}, '#{flag_column}')
end
def #{flag_name}=(value)
FlagShihTzu::TRUE_VALUES.include?(value) ? enable_flag(:#{flag_name}, '#{flag_column}') : disable_flag(:#{flag_name}, '#{flag_column}')
end
def self.#{flag_name}_condition
sql_condition_for_flag(:#{flag_name}, '#{flag_column}', true)
end
def self.not_#{flag_name}_condition
sql_condition_for_flag(:#{flag_name}, '#{flag_column}', false)
end
EVAL
if respond_to?(:named_scope) && options[:named_scopes]
class_eval <<-EVAL
named_scope :#{flag_name}, lambda { { :conditions => #{flag_name}_condition } }
named_scope :not_#{flag_name}, lambda { { :conditions => not_#{flag_name}_condition } }
EVAL
end
end
end
def check_flag(flag, colmn)
raise ArgumentError, "Column name '#{colmn}' for flag '#{flag}' is not a string" unless colmn.is_a?(String)
raise ArgumentError, "Invalid flag '#{flag}'" if flag_mapping[colmn].nil? || !flag_mapping[colmn].include?(flag)
end
private
def parse_options(*args)
options = args.shift
if args.size >= 1
add_options = args.shift
else
add_options = options.keys.select {|key| !key.is_a?(Fixnum)}.inject({}) do |hash, key|
hash[key] = options.delete(key)
hash
end
end
return options, add_options
end
def check_flag_column(colmn, custom_table_name = self.table_name)
# If you aren't using ActiveRecord (eg. you are outside rails) then do not fail here
# If you are using ActiveRecord then you only want to check for the table if the table exists so it won't fail pre-migration
has_ar = defined?(ActiveRecord) && self.is_a?(ActiveRecord::Base)
# Supposedly Rails 2.3 takes care of this, but this precaution is needed for backwards compatibility
has_table = has_ar ? ActiveRecord::Base.connection.tables.include?(custom_table_name) : true
logger.warn("Error: Table '#{custom_table_name}' doesn't exist") and return false unless has_table
if !has_ar || (has_ar && has_table)
has_column = columns.any? { |column| column.name == colmn }
is_integer_column = columns.any? { |column| column.name == colmn && column.type == :integer }
logger.warn("Warning: Table '#{custom_table_name}' must have an integer column named '#{colmn}' in order to use FlagShihTzu") and return false unless has_column
raise IncorrectFlagColumnException, "Warning: Column '#{colmn}'must be of type integer in order to use FlagShihTzu" unless is_integer_column
end
true
end
def sql_condition_for_flag(flag, colmn, enabled = true, custom_table_name = self.table_name)
check_flag(flag, colmn)
# use & bit operator directly in the SQL query for more than SQL_IN_LIMITATION flags.
# This has the drawback of fetching all records, but MySQL cannot handle more than 64k elements inside the IN parentheses.
if flag_mapping[flag_column].length > SQL_IN_LIMITATION
"(#{custom_table_name}.#{colmn} & #{flag_mapping[colmn][flag]} = #{enabled ? flag_mapping[colmn][flag] : 0})"
else
neg = enabled ? "" : "not "
"(#{custom_table_name}.#{colmn} #{neg}in (#{sql_in_for_flag(flag, colmn).join(',')}))"
end
end
def sql_set_for_flag(flag, colmn, enabled = true, custom_table_name = self.table_name)
check_flag(flag, colmn)
"#{custom_table_name}.#{colmn} = #{custom_table_name}.#{colmn} #{enabled ? "| " : "& ~" }#{flag_mapping[colmn][flag]}"
end
# returns an array of integers suitable for a SQL IN statement.
def sql_in_for_flag(flag, colmn)
val = flag_mapping[colmn][flag]
num = 2 ** flag_mapping[flag_column].length
(1..num).select {|i| i & val == val}
end
def is_valid_flag_key(flag_key)
flag_key > 0 && flag_key == flag_key.to_i
end
def is_valid_flag_name(flag_name)
flag_name.is_a?(Symbol)
end
end
def enable_flag(flag, colmn = nil)
colmn = determine_flag_colmn_for(flag) if colmn.nil?
self.class.check_flag(flag, colmn)
set_flags(self.flags(colmn) | self.class.flag_mapping[colmn][flag], colmn)
end
def disable_flag(flag, colmn = nil)
colmn = determine_flag_colmn_for(flag) if colmn.nil?
self.class.check_flag(flag, colmn)
set_flags(self.flags(colmn) & ~self.class.flag_mapping[colmn][flag], colmn)
end
def flag_enabled?(flag, colmn = nil)
colmn = determine_flag_colmn_for(flag) if colmn.nil?
self.class.check_flag(flag, colmn)
get_bit_for(flag, colmn) == 0 ? false : true
end
def flag_disabled?(flag, colmn = nil)
colmn = determine_flag_colmn_for(flag) if colmn.nil?
self.class.check_flag(flag, colmn)
!flag_enabled?(flag, colmn)
end
def flags(colmn = 'flags')
self[colmn] || 0
end
def set_flags(value, colmn)
self[colmn] = value
end
private
def get_bit_for(flag, colmn)
self.flags(colmn) & self.class.flag_mapping[colmn][flag]
end
def determine_flag_colmn_for(flag)
return 'flags' if self.class.flag_mapping.nil?
self.class.flag_mapping.each_pair do |colmn, mapping|
return colmn if mapping.include?(flag)
end
raise NoSuchFlagException.new("determine_flag_colmn_for: Couldn't determine column for your flags!")
end
end
remove unused method
module FlagShihTzu
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'] # taken from ActiveRecord::ConnectionAdapters::Column
SQL_IN_LIMITATION = 16
def self.included(base)
base.extend(ClassMethods)
end
class IncorrectFlagColumnException < Exception; end
class NoSuchFlagException < Exception; end
module ClassMethods
def has_flags(*args)
flag_hash, options = parse_options(*args)
options = {:named_scopes => true, :column => 'flags', :verbose => false}.update(options)
class_inheritable_reader :flag_column
write_inheritable_attribute(:flag_column, options[:column])
return unless check_flag_column(flag_column)
class_inheritable_hash :flag_mapping
# if has_flags is used more than once in a single class, then flag_mapping will already have data in it in successive declarations
write_inheritable_attribute(:flag_mapping, {}) if flag_mapping.nil?
# initialize flag_mapping for this column
flag_mapping[flag_column] ||= {}
flag_hash.each do |flag_key, flag_name|
raise ArgumentError, "has_flags: flag keys should be positive integers, and #{flag_key} is not" unless is_valid_flag_key(flag_key)
raise ArgumentError, "has_flags: flag names should be symbols, and #{flag_name} is not" unless is_valid_flag_name(flag_name)
raise ArgumentError, "has_flags: flag name #{flag_name} already defined, please choose different name" if method_defined?(flag_name)
flag_mapping[flag_column][flag_name] = 1 << (flag_key - 1)
class_eval <<-EVAL
def #{flag_name}
flag_enabled?(:#{flag_name}, '#{flag_column}')
end
def #{flag_name}?
flag_enabled?(:#{flag_name}, '#{flag_column}')
end
def #{flag_name}=(value)
FlagShihTzu::TRUE_VALUES.include?(value) ? enable_flag(:#{flag_name}, '#{flag_column}') : disable_flag(:#{flag_name}, '#{flag_column}')
end
def self.#{flag_name}_condition
sql_condition_for_flag(:#{flag_name}, '#{flag_column}', true)
end
def self.not_#{flag_name}_condition
sql_condition_for_flag(:#{flag_name}, '#{flag_column}', false)
end
EVAL
if respond_to?(:named_scope) && options[:named_scopes]
class_eval <<-EVAL
named_scope :#{flag_name}, lambda { { :conditions => #{flag_name}_condition } }
named_scope :not_#{flag_name}, lambda { { :conditions => not_#{flag_name}_condition } }
EVAL
end
end
end
def check_flag(flag, colmn)
raise ArgumentError, "Column name '#{colmn}' for flag '#{flag}' is not a string" unless colmn.is_a?(String)
raise ArgumentError, "Invalid flag '#{flag}'" if flag_mapping[colmn].nil? || !flag_mapping[colmn].include?(flag)
end
private
def parse_options(*args)
options = args.shift
if args.size >= 1
add_options = args.shift
else
add_options = options.keys.select {|key| !key.is_a?(Fixnum)}.inject({}) do |hash, key|
hash[key] = options.delete(key)
hash
end
end
return options, add_options
end
def check_flag_column(colmn, custom_table_name = self.table_name)
# If you aren't using ActiveRecord (eg. you are outside rails) then do not fail here
# If you are using ActiveRecord then you only want to check for the table if the table exists so it won't fail pre-migration
has_ar = defined?(ActiveRecord) && self.is_a?(ActiveRecord::Base)
# Supposedly Rails 2.3 takes care of this, but this precaution is needed for backwards compatibility
has_table = has_ar ? ActiveRecord::Base.connection.tables.include?(custom_table_name) : true
logger.warn("Error: Table '#{custom_table_name}' doesn't exist") and return false unless has_table
if !has_ar || (has_ar && has_table)
has_column = columns.any? { |column| column.name == colmn }
is_integer_column = columns.any? { |column| column.name == colmn && column.type == :integer }
logger.warn("Warning: Table '#{custom_table_name}' must have an integer column named '#{colmn}' in order to use FlagShihTzu") and return false unless has_column
raise IncorrectFlagColumnException, "Warning: Column '#{colmn}'must be of type integer in order to use FlagShihTzu" unless is_integer_column
end
true
end
def sql_condition_for_flag(flag, colmn, enabled = true, custom_table_name = self.table_name)
check_flag(flag, colmn)
# use & bit operator directly in the SQL query for more than SQL_IN_LIMITATION flags.
# This has the drawback of fetching all records, but MySQL cannot handle more than 64k elements inside the IN parentheses.
if flag_mapping[flag_column].length > SQL_IN_LIMITATION
"(#{custom_table_name}.#{colmn} & #{flag_mapping[colmn][flag]} = #{enabled ? flag_mapping[colmn][flag] : 0})"
else
neg = enabled ? "" : "not "
"(#{custom_table_name}.#{colmn} #{neg}in (#{sql_in_for_flag(flag, colmn).join(',')}))"
end
end
# returns an array of integers suitable for a SQL IN statement.
def sql_in_for_flag(flag, colmn)
val = flag_mapping[colmn][flag]
num = 2 ** flag_mapping[flag_column].length
(1..num).select {|i| i & val == val}
end
def is_valid_flag_key(flag_key)
flag_key > 0 && flag_key == flag_key.to_i
end
def is_valid_flag_name(flag_name)
flag_name.is_a?(Symbol)
end
end
def enable_flag(flag, colmn = nil)
colmn = determine_flag_colmn_for(flag) if colmn.nil?
self.class.check_flag(flag, colmn)
set_flags(self.flags(colmn) | self.class.flag_mapping[colmn][flag], colmn)
end
def disable_flag(flag, colmn = nil)
colmn = determine_flag_colmn_for(flag) if colmn.nil?
self.class.check_flag(flag, colmn)
set_flags(self.flags(colmn) & ~self.class.flag_mapping[colmn][flag], colmn)
end
def flag_enabled?(flag, colmn = nil)
colmn = determine_flag_colmn_for(flag) if colmn.nil?
self.class.check_flag(flag, colmn)
get_bit_for(flag, colmn) == 0 ? false : true
end
def flag_disabled?(flag, colmn = nil)
colmn = determine_flag_colmn_for(flag) if colmn.nil?
self.class.check_flag(flag, colmn)
!flag_enabled?(flag, colmn)
end
def flags(colmn = 'flags')
self[colmn] || 0
end
def set_flags(value, colmn)
self[colmn] = value
end
private
def get_bit_for(flag, colmn)
self.flags(colmn) & self.class.flag_mapping[colmn][flag]
end
def determine_flag_colmn_for(flag)
return 'flags' if self.class.flag_mapping.nil?
self.class.flag_mapping.each_pair do |colmn, mapping|
return colmn if mapping.include?(flag)
end
raise NoSuchFlagException.new("determine_flag_colmn_for: Couldn't determine column for your flags!")
end
end
|
require 'curses'
require 'gaman/logging'
module Gaman
class Console < Curses::Window
include Logging
@mutex = nil
def setup
@mutex.synchronize {
self.timeout = 0 # ms to block on each read
self.keypad = true
attrset Curses::A_REVERSE
setpos 0, 0
addstr " "*maxx
attrset(Curses::A_NORMAL)
refresh
}
end
def display_prompt text
@mutex.synchronize do
attrset Curses::A_REVERSE
setpos 0, 0
addstr text + " "*(maxx-text.size)
attrset Curses::A_NORMAL
refresh
end
end
def get_character valid_keys
char = nil
loop do
@mutex.synchronize { char = getch }
break if char && # we received a character
char[0].ord > 30 && # it's not a control character (e.g.: ESC)
valid_keys.map { |c| c.downcase }.include?(char.downcase) # it matches the list
end
char
end
def choose_command commands
@mutex.synchronize do
setpos 1,0
commands.each do |c|
attrset Curses::A_REVERSE
addstr c.key
attrset Curses::A_NORMAL
addstr " #{c.label}" + " "*(19-c.label.size)
end
end
selected_character = get_character(commands.map { |c| c.key })
selected_command = nil
commands.each do |c|
selected_command = c if c.key.downcase == selected_character.downcase
end
# selected_command = commands.bsearch { |c| c.key.downcase == selected_character.downcase }
selected_command.value
end
def clear
@mutex.synchronize do
# attrset Curses::A_REVERSE
# setpos 0, 0
# addstr " "*maxx
attrset Curses::A_NORMAL
setpos 1, 0 # start of first line under status bar
clrtoeol
setpos 2,0 # start of second line under status bar
clrtoeol
setpos 1, 0 # start of first line under status bar
end
end
def get_string max_length
# return nil if the user hits ESC
# need to set the location of the cursor and show it
# need to echo the characters that are being typed (manually - noecho should remain on)
# need to support arrow keys and delete properly
logger.debug { "Asking user for string of max length #{max_length}" }
result = ""
clear
loop do
char = nil
loop do
@mutex.synchronize do
Curses.curs_set 1
char = getch
Curses.curs_set 0
end
break if char
end
case char
when 10
logger.debug {"ENTER detected"}
when 27
logger.debug {"ESCAPE detected"}
return nil
when 127
logger.debug {"BACKSPACE detected"}
next
when Curses::Key::BACKSPACE
logger.debug {"BACKSPACE detected through Curses."}
next
when 330
logger.debug {"DELETE detected"}
next
when Curses::Key::LEFT
logger.debug {"LEFT detected through Curses."}
next
when Curses::Key::RIGHT
logger.debug {"RIGHT detected through Curses."}
next
when Curses::Key::UP
logger.debug {"UP detected through Curses."}
next
when Curses::Key::DOWN
logger.debug {"DOWN detected through Curses."}
next
end
logger.debug "Received key. [#{char}] Ord: [#{char[0].ord}] Int: [#{char[0].to_i}]"
break if char == 10
addch char
result += char
end
logger.debug "Received the string #{result}"
clear
result
end
def run mutex, input_queue, output_queue
@mutex = mutex
setup
running = true
while running
command = input_queue.pop # blocks
case command[:type]
when :quit then running = false
when :status
display_prompt command[:message]
when :commands
display_prompt "Please select a command:"
output_queue << choose_command(command[:commands])
when :get_string
display_prompt command[:prompt]
output_queue << get_string(command[:max_length])
end
end
end
end
end
Implemented backspace in get_string
When asking the user for a string they can now use the BACKSPACE key to
correct input.
require 'curses'
require 'gaman/logging'
module Gaman
class Console < Curses::Window
include Logging
@mutex = nil
def setup
@mutex.synchronize {
self.timeout = 0 # ms to block on each read
self.keypad = true
attrset Curses::A_REVERSE
setpos 0, 0
addstr " "*maxx
attrset(Curses::A_NORMAL)
refresh
}
end
def display_prompt text
@mutex.synchronize do
attrset Curses::A_REVERSE
setpos 0, 0
addstr text + " "*(maxx-text.size)
attrset Curses::A_NORMAL
refresh
end
end
def get_character valid_keys
char = nil
loop do
@mutex.synchronize { char = getch }
break if char && # we received a character
char[0].ord > 30 && # it's not a control character (e.g.: ESC)
valid_keys.map { |c| c.downcase }.include?(char.downcase) # it matches the list
end
char
end
def choose_command commands
@mutex.synchronize do
setpos 1,0
commands.each do |c|
attrset Curses::A_REVERSE
addstr c.key
attrset Curses::A_NORMAL
addstr " #{c.label}" + " "*(19-c.label.size)
end
end
selected_character = get_character(commands.map { |c| c.key })
selected_command = nil
commands.each do |c|
selected_command = c if c.key.downcase == selected_character.downcase
end
# selected_command = commands.bsearch { |c| c.key.downcase == selected_character.downcase }
selected_command.value
end
def clear
@mutex.synchronize do
# attrset Curses::A_REVERSE
# setpos 0, 0
# addstr " "*maxx
attrset Curses::A_NORMAL
setpos 1, 0 # start of first line under status bar
clrtoeol
setpos 2,0 # start of second line under status bar
clrtoeol
setpos 1, 0 # start of first line under status bar
end
end
def get_string max_length
# return nil if the user hits ESC
# need to set the location of the cursor and show it
# need to echo the characters that are being typed (manually - noecho should remain on)
# need to support arrow keys and delete properly
logger.debug { "Asking user for string of max length #{max_length}" }
result = ""
clear
loop do
char = nil
loop do
@mutex.synchronize do
Curses.curs_set 1
char = getch
Curses.curs_set 0
end
break if char
end
case char
when 10
logger.debug {"ENTER detected"}
when 27
logger.debug {"ESCAPE detected"}
return nil
when 127
logger.debug {"BACKSPACE detected"}
setpos cury, curx-1
addch " "
setpos cury, curx-1
result = result[0..-2]
next
when Curses::Key::BACKSPACE
logger.debug {"BACKSPACE detected through Curses."}
next
when 330
logger.debug {"DELETE detected"}
next
when Curses::Key::LEFT
logger.debug {"LEFT detected through Curses."}
next
when Curses::Key::RIGHT
logger.debug {"RIGHT detected through Curses."}
next
when Curses::Key::UP
logger.debug {"UP detected through Curses."}
next
when Curses::Key::DOWN
logger.debug {"DOWN detected through Curses."}
next
end
logger.debug "Received key. [#{char}] Ord: [#{char[0].ord}] Int: [#{char[0].to_i}]"
break if char == 10
addch char
result += char
end
logger.debug "Received the string #{result}"
clear
result
end
def run mutex, input_queue, output_queue
@mutex = mutex
setup
running = true
while running
command = input_queue.pop # blocks
case command[:type]
when :quit then running = false
when :status
display_prompt command[:message]
when :commands
display_prompt "Please select a command:"
output_queue << choose_command(command[:commands])
when :get_string
display_prompt command[:prompt]
output_queue << get_string(command[:max_length])
end
end
end
end
end |
module Gisbn
VERSION = "0.0.1"
end
chore: version is updated for bug fix
module Gisbn
VERSION = "0.0.2"
end
|
require "string-scrub"
module GitFame
class Base
include GitFame::Helper
#
# @args[:repository] String Absolute path to git repository
# @args[:sort] String What should #authors be sorted by?
# @args[:bytype] Boolean Should counts be grouped by file extension?
# @args[:exclude] String Comma-separated list of paths in the repo
# which should be excluded
#
def initialize(args)
@sort = "loc"
@progressbar = false
@whitespace = false
@bytype = false
@exclude = ""
@include = ""
@authors = {}
@file_authors = Hash.new { |h,k| h[k] = {} }
args.keys.each do |name|
instance_variable_set "@" + name.to_s, args[name]
end
@exclude = convert_exclude_paths_to_array
end
#
# Generates pretty output
#
def pretty_puts
extend Hirb::Console
Hirb.enable({pager: false})
puts "\nTotal number of files: #{number_with_delimiter(files)}"
puts "Total number of lines: #{number_with_delimiter(loc)}"
puts "Total number of commits: #{number_with_delimiter(commits)}\n"
fields = [:name, :loc, :commits, :files, :distribution]
if @bytype
fields << populate.instance_variable_get("@file_extensions").
uniq.sort
end
table(authors, fields: fields.flatten)
end
#
# @return Fixnum Total number of files
#
def files
populate.instance_variable_get("@files").count
end
#
# @return Array list of repo files processed
#
def file_list
populate.instance_variable_get("@files")
end
#
# @return Fixnum Total number of commits
#
def commits
authors.inject(0){ |result, author| author.raw_commits + result }
end
#
# @return Fixnum Total number of lines
#
def loc
populate.authors.
inject(0){ |result, author| author.raw_loc + result }
end
#
# @return Array<Author> A list of authors
#
def authors
authors = populate.instance_variable_get("@authors").values
if @sort
authors.sort_by do |author|
if @sort == "name"
author.send(@sort)
else
-1 * author.send("raw_#{@sort}")
end
end
else
authors
end
end
#
# @return Boolean Is the given @dir a git repository?
# @dir Path (relative or absolute) to git repository
#
def self.git_repository?(dir)
Dir.exists?(File.join(dir, ".git"))
end
private
#
# @command String Command to be executed inside the @repository path
#
def execute(command)
Dir.chdir(@repository) do
return `#{command}`.scrub
end
end
#
# @author String Author
# @args Hash Argument that should be set in @return
# @return Author
#
def update(author, args)
fetch(author).tap do |found|
args.keys.each do |key|
found.send("#{key}=", args[key])
end
end
end
#
# @return Author
# @author String
#
def fetch(author)
@authors[author] ||= Author.new({name: author, parent: self})
end
#
# @return GitFame
#
def populate
@_populate ||= begin
@files = execute("git ls-files #{@include}").split("\n")
@file_extensions = []
remove_excluded_files
progressbar = SilentProgressbar.new(
"Blame",
@files.count,
@progressbar
)
blame_opts = @whitespace ? "-w" : ""
@files.each do |file|
progressbar.inc
if @bytype
file_extension = File.extname(file).gsub(/^\./, "")
file_extension = "unknown" if file_extension.empty?
end
unless type = Mimer.identify(File.join(@repository, file))
next
end
if type.binary?
next
end
# only count extensions that aren't binary
@file_extensions << file_extension
output = execute(
"git blame '#{file}' #{blame_opts} --line-porcelain"
)
output.scan(/^author (.+)$/).each do |author|
fetch(author.first).raw_loc += 1
@file_authors[author.first][file] ||= 1
if @bytype
fetch(author.first).
file_type_counts[file_extension] += 1
end
end
end
execute("git shortlog -se").split("\n").map do |l|
_, commits, u = l.match(%r{^\s*(\d+)\s+(.+?)\s+<.+?>}).to_a
user = fetch(u)
# Has this user been updated before?
if user.raw_commits.zero?
update(u, {
raw_commits: commits.to_i,
raw_files: @file_authors[u].keys.count,
files_list: @file_authors[u].keys
})
else
# Calculate the number of files edited by users
files = (user.files_list + @file_authors[u].keys).uniq
update(u, {
raw_commits: commits.to_i + user.raw_commits,
raw_files: files.count,
files_list: files
})
end
end
progressbar.finish
end
return self
end
#
# Converts @exclude argument to an array and removes leading slash
#
def convert_exclude_paths_to_array
@exclude.split(",").map{|path| path.strip.sub(/\A\//, "") }
end
#
# Removes files matching paths in @exclude from @files instance variable
#
def remove_excluded_files
return if @exclude.empty?
@files = @files.map do |path|
next if path =~ /\A(#{@exclude.join("|")})/
path
end.compact
end
end
end
Use safer checking of git path
require "string-scrub"
module GitFame
class Base
include GitFame::Helper
#
# @args[:repository] String Absolute path to git repository
# @args[:sort] String What should #authors be sorted by?
# @args[:bytype] Boolean Should counts be grouped by file extension?
# @args[:exclude] String Comma-separated list of paths in the repo
# which should be excluded
#
def initialize(args)
@sort = "loc"
@progressbar = false
@whitespace = false
@bytype = false
@exclude = ""
@include = ""
@authors = {}
@file_authors = Hash.new { |h,k| h[k] = {} }
args.keys.each do |name|
instance_variable_set "@" + name.to_s, args[name]
end
@exclude = convert_exclude_paths_to_array
end
#
# Generates pretty output
#
def pretty_puts
extend Hirb::Console
Hirb.enable({pager: false})
puts "\nTotal number of files: #{number_with_delimiter(files)}"
puts "Total number of lines: #{number_with_delimiter(loc)}"
puts "Total number of commits: #{number_with_delimiter(commits)}\n"
fields = [:name, :loc, :commits, :files, :distribution]
if @bytype
fields << populate.instance_variable_get("@file_extensions").
uniq.sort
end
table(authors, fields: fields.flatten)
end
#
# @return Fixnum Total number of files
#
def files
populate.instance_variable_get("@files").count
end
#
# @return Array list of repo files processed
#
def file_list
populate.instance_variable_get("@files")
end
#
# @return Fixnum Total number of commits
#
def commits
authors.inject(0){ |result, author| author.raw_commits + result }
end
#
# @return Fixnum Total number of lines
#
def loc
populate.authors.
inject(0){ |result, author| author.raw_loc + result }
end
#
# @return Array<Author> A list of authors
#
def authors
authors = populate.instance_variable_get("@authors").values
if @sort
authors.sort_by do |author|
if @sort == "name"
author.send(@sort)
else
-1 * author.send("raw_#{@sort}")
end
end
else
authors
end
end
#
# @return Boolean Is the given @dir a git repository?
# @dir Path (relative or absolute) to git repository
#
def self.git_repository?(dir)
return false unless File.directory?(dir)
Dir.chdir(dir) { system "git rev-parse --git-dir > /dev/null 2>&1" }
end
private
#
# @command String Command to be executed inside the @repository path
#
def execute(command)
Dir.chdir(@repository) do
return `#{command}`.scrub
end
end
#
# @author String Author
# @args Hash Argument that should be set in @return
# @return Author
#
def update(author, args)
fetch(author).tap do |found|
args.keys.each do |key|
found.send("#{key}=", args[key])
end
end
end
#
# @return Author
# @author String
#
def fetch(author)
@authors[author] ||= Author.new({name: author, parent: self})
end
#
# @return GitFame
#
def populate
@_populate ||= begin
@files = execute("git ls-files #{@include}").split("\n")
@file_extensions = []
remove_excluded_files
progressbar = SilentProgressbar.new(
"Blame",
@files.count,
@progressbar
)
blame_opts = @whitespace ? "-w" : ""
@files.each do |file|
progressbar.inc
if @bytype
file_extension = File.extname(file).gsub(/^\./, "")
file_extension = "unknown" if file_extension.empty?
end
unless type = Mimer.identify(File.join(@repository, file))
next
end
if type.binary?
next
end
# only count extensions that aren't binary
@file_extensions << file_extension
output = execute(
"git blame '#{file}' #{blame_opts} --line-porcelain"
)
output.scan(/^author (.+)$/).each do |author|
fetch(author.first).raw_loc += 1
@file_authors[author.first][file] ||= 1
if @bytype
fetch(author.first).
file_type_counts[file_extension] += 1
end
end
end
execute("git shortlog -se").split("\n").map do |l|
_, commits, u = l.match(%r{^\s*(\d+)\s+(.+?)\s+<.+?>}).to_a
user = fetch(u)
# Has this user been updated before?
if user.raw_commits.zero?
update(u, {
raw_commits: commits.to_i,
raw_files: @file_authors[u].keys.count,
files_list: @file_authors[u].keys
})
else
# Calculate the number of files edited by users
files = (user.files_list + @file_authors[u].keys).uniq
update(u, {
raw_commits: commits.to_i + user.raw_commits,
raw_files: files.count,
files_list: files
})
end
end
progressbar.finish
end
return self
end
#
# Converts @exclude argument to an array and removes leading slash
#
def convert_exclude_paths_to_array
@exclude.split(",").map{|path| path.strip.sub(/\A\//, "") }
end
#
# Removes files matching paths in @exclude from @files instance variable
#
def remove_excluded_files
return if @exclude.empty?
@files = @files.map do |path|
next if path =~ /\A(#{@exclude.join("|")})/
path
end.compact
end
end
end
|
module GitHub
module Markup
VERSION = '0.7.7'
Version = VERSION
end
end
bump version to 1.0.0
module GitHub
module Markup
VERSION = '1.0.0'
Version = VERSION
end
end
|
require 'gliffy/request'
require 'gliffy/response'
require 'gliffy/credentials'
module Gliffy
VERSION = '0.1.7'
# A "handle" to access Gliffy on a per-user-session basis
# Since most calls to gliffy require a user-token, this class
# encapsulates that token and the calls made under it.
#
# The methods here are designed to raise exceptions if there are problems from Gliffy.
# These problems usually indicate a programming error or a server-side problem with Gliffy and
# are generally unhandleable. However, if you wish to do something better than simply raise an exception
# you may override handle_error to do something else
#
class Handle
attr_reader :logger
attr_reader :request
attr_reader :token
# Create a new handle to gliffy for the given user. Tokens will be requested as needed
def initialize(api_root,credentials,http=nil,logger=nil)
@credentials = credentials
@request = Request.new(api_root,credentials)
@request.http = http if !http.nil?
@logger = logger || Logger.new(STDOUT)
@logger.level = Logger::INFO
@request.logger = @logger
if !@credentials.has_access_token?
update_token
end
end
# Updates the token being used if there isn't one in the
# credentials, or by forcing
# [+force+] always attempt to update the token
def update_token(force=false)
if !@credentials.has_access_token? || force
@logger.debug("Requesting new token " + (force ? " by force " : " since we have none "))
response = @request.create(token_url,
:description => @credentials.description,
:protocol_override => :https)
@token = Response.from_http_response(response)
@credentials.update_access_token(@token)
end
end
# Delete the current token
def delete_token
make_request(:delete,token_url)
@credentials.clear_access_token
end
# Get admins of your account. Returns users
def account_admins
make_request(:get,"#{account_url}/admins.xml")
end
# Returns all documents in the account
# [+show+] if nil, all documents are returned; if :public only public are returned. If :private only non-public are returned.
def account_documents(show=nil)
if show.nil?
make_request(:get,"#{account_url}/documents.xml")
else
make_request(:get,"#{account_url}/documents.xml",:public => show == :public)
end
end
# Returns all folders in the account
def account_folders
make_request(:get,"#{account_url}/folders.xml")
end
# Returns account meta data
def account_get(show_users=true)
make_request(:get,"#{account_url}.xml", :showUsers => show_users)
end
# Get users in your account
def account_users
end
# Create a new diagram
def diagram_create
end
# Delete an existing diagram
def diagram_delete
end
# Get a diagram
def diagram_get
end
# Get a link to a diagram
def diagram_get_url
end
# Get the link to edit a diagram
def diagram_edit_link
end
# Move a diagram to a different folder
def diagram_move
end
# Update a diagram's XML content
def diagram_update_content
end
# Add a user to a folder
def folder_add_user
end
# Create a new folder
def folder_create
end
# Delete a folder
def folder_delete
end
# Get the documents in a folder
def folder_documents
end
# Get users with access to the folder
def folder_users
end
# Remove a user from access to the folder
def folder_remove_user
end
# Create a new user
def user_add
end
# Delete an existing user
def user_delete
end
# Get the documents a user has access to
def user_documents
end
# Get the folders a user has access to
def user_folders
end
# Update a user's meta-data
def user_update
end
private
def account_url; 'accounts/$account_id'; end
def token_url; "#{account_url}/users/$username/oauth_token.xml"; end
def make_request(method,url,params=nil)
update_token
@logger.debug("Requesting #{url} with {#params.inspect}")
response = @request.send(method,url,params)
@logger.debug("Got back #{response.body}")
Response.from_http_response(response)
end
end
end
Removed lying comments. Truth later
require 'gliffy/request'
require 'gliffy/response'
require 'gliffy/credentials'
module Gliffy
VERSION = '0.1.7'
# A "handle" to access Gliffy on a per-user-session basis
# Since most calls to gliffy require a user-token, this class
# encapsulates that token and the calls made under it.
#
class Handle
attr_reader :logger
attr_reader :request
attr_reader :token
def initialize(api_root,credentials,http=nil,logger=nil)
@credentials = credentials
@request = Request.new(api_root,credentials)
@request.http = http if !http.nil?
@logger = logger || Logger.new(STDOUT)
@logger.level = Logger::INFO
@request.logger = @logger
if !@credentials.has_access_token?
update_token
end
end
# Updates the token being used if there isn't one in the
# credentials, or by forcing
# [+force+] always attempt to update the token
def update_token(force=false)
if !@credentials.has_access_token? || force
@logger.debug("Requesting new token " + (force ? " by force " : " since we have none "))
response = @request.create(token_url,
:description => @credentials.description,
:protocol_override => :https)
@token = Response.from_http_response(response)
@credentials.update_access_token(@token)
end
end
# Delete the current token
def delete_token
make_request(:delete,token_url)
@credentials.clear_access_token
end
# Get admins of your account. Returns users
def account_admins
make_request(:get,"#{account_url}/admins.xml")
end
# Returns all documents in the account
# [+show+] if nil, all documents are returned; if :public only public are returned. If :private only non-public are returned.
def account_documents(show=nil)
if show.nil?
make_request(:get,"#{account_url}/documents.xml")
else
make_request(:get,"#{account_url}/documents.xml",:public => show == :public)
end
end
# Returns all folders in the account
def account_folders
make_request(:get,"#{account_url}/folders.xml")
end
# Returns account meta data
def account_get(show_users=true)
make_request(:get,"#{account_url}.xml", :showUsers => show_users)
end
# Get users in your account
def account_users
end
# Create a new diagram
def diagram_create
end
# Delete an existing diagram
def diagram_delete
end
# Get a diagram
def diagram_get
end
# Get a link to a diagram
def diagram_get_url
end
# Get the link to edit a diagram
def diagram_edit_link
end
# Move a diagram to a different folder
def diagram_move
end
# Update a diagram's XML content
def diagram_update_content
end
# Add a user to a folder
def folder_add_user
end
# Create a new folder
def folder_create
end
# Delete a folder
def folder_delete
end
# Get the documents in a folder
def folder_documents
end
# Get users with access to the folder
def folder_users
end
# Remove a user from access to the folder
def folder_remove_user
end
# Create a new user
def user_add
end
# Delete an existing user
def user_delete
end
# Get the documents a user has access to
def user_documents
end
# Get the folders a user has access to
def user_folders
end
# Update a user's meta-data
def user_update
end
private
def account_url; 'accounts/$account_id'; end
def token_url; "#{account_url}/users/$username/oauth_token.xml"; end
def make_request(method,url,params=nil)
update_token
@logger.debug("Requesting #{url} with {#params.inspect}")
response = @request.send(method,url,params)
@logger.debug("Got back #{response.body}")
Response.from_http_response(response)
end
end
end
|
module Golem
module Packets
PROTOCOL_VERSION = 8
def self.client_packet(kind, code, &blk)
p = Class.new(Packet)
p.kind = kind
p.code = code
p.module_eval(&blk) if blk
Packet.client_packet p
end
def self.server_packet(kind, code, &blk)
p = Class.new(Packet)
p.kind = kind
p.code = code
p.module_eval(&blk) if blk
Packet.server_packet p
end
client_packet :keepalive, 0x00
server_packet :keepalive, 0x00
client_packet :login, 0x01 do
int :protocol_version
string :username
string :password
long :map_seed # always 0, not required
byte :dimension # always 0, not required
end
server_packet :accept_login, 0x01 do
int :player_id
string :server_name # ?
string :motd # ?
long :map_seed
byte :dimension
end
client_packet :handshake, 0x02 do
string :username
end
server_packet :handshake, 0x02 do
string :server_id
end
server_packet :chat, 0x03 do
string :message
end
client_packet :chat, 0x03 do
string :message
end
server_packet :update_time, 0x04 do
long :time
end
server_packet :entity_equipment, 0x05 do
int :entity_id
short :slot # 0 = held, 1-4 = armor slots
short :item_id # -1 for empty
short :damage?
end
server_packet :spawn_position, 0x06 do
int :x
int :y
int :z
end
server_packet :use_entity, 0x07 do
int :player_id
int :entity_id
bool :left_click # true when pointing at an entity, false when using a block
end
client_packet :use_entity, 0x07 do
int :player_id
int :entity_id
bool :left_click # true when pointing at an entity, false when using a block
end
server_packet :player_health, 0x08 do
short :health # 0 = dead, 20 = full
end
server_packet :respawn, 0x09 do
end
client_packet :respawn, 0x09 do
end
client_packet :flying_ack, 0x0a do
bool :flying
end
server_packet :flying, 0x0a do
bool :flying
end
client_packet :player_position, 0x0b do
double :x
double :y
double :stance
double :z
bool :flying
end
server_packet :player_position, 0x0b do
double :x
double :y
double :stance
double :z
bool :flying
end
server_packet :player_look, 0x0c do
float :rotation
float :pitch
bool :flying
end
client_packet :player_look, 0x0c do
float :rotation
float :pitch
bool :flying
end
client_packet :player_move_look, 0x0d do
double :x
double :y
double :stance
double :z
float :rotation
float :pitch
bool :flying
end
server_packet :player_move_look, 0x0d do
double :x
# yes, this is reversed from the packet the client sends.
double :stance
double :y
double :z
float :rotation
float :pitch
bool :flying
end
client_packet :block_dig, 0x0e do
byte :status
int :x
byte :y
int :z
byte :direction
end
client_packet :place, 0x0f do
int :x
byte :y
int :z
byte :direction
field :items, Field::SlotItems
end
client_packet :holding_change, 0x10 do
short :slot_id # slot which player has selected, 0-8
end
server_packet :animation, 0x12 do
int :entity_id
byte :animate # 0 = no animation, 1 = swing, 2 = death? 102 = ?
end
client_packet :animation, 0x12 do
int :entity_id
byte :animate
end
client_packet :entity_action, 0x13 do
int :entity_id
byte :action # 1 crouch, 2 uncrouch?
end
server_packet :named_entity_spawn, 0x14 do
int :id
string :name
int :x
int :y
int :z
byte :rotation
byte :pitch
short :current_item
end
# client drops something
client_packet :pickup_spawn, 0x15 do
int :id
short :item
byte :count
short :damage?
int :x
int :y
int :z
byte :rotation
byte :pitch
byte :roll
end
server_packet :pickup_spawn, 0x15 do
int :id
short :item
byte :count
short :damage?
int :x
int :y
int :z
byte :rotation
byte :pitch
byte :roll
end
server_packet :collect_item, 0x16 do
int :item_id
int :collector_id
end
server_packet :vehicle_spawn, 0x17 do
int :id
byte :type
int :x
int :y
int :z
end
server_packet :mob_spawn, 0x18 do
int :id
byte :type
int :x
int :y
int :z
byte :rotation
byte :pitch
field :mob_data, Field::MobData
end
server_packet :painting, 0x19 do
int :id
string :title # name of the painting
int :x
int :y
int :z
int :type
end
server_packet :entity_velocity, 0x1c do
int :id
short :v_x
short :v_y
short :v_z
end
server_packet :destroy_entity, 0x1d do
int :id
end
server_packet :entity, 0x1e do
int :id
end
server_packet :entity_move, 0x1f do
int :id
byte :x
byte :y
byte :z
end
server_packet :entity_look, 0x20 do
int :id
byte :rotation
byte :pitch
end
server_packet :entity_move_look, 0x21 do
int :id
byte :x
byte :y
byte :z
byte :rotation
byte :pitch
end
server_packet :entity_teleport, 0x22 do
int :id
int :x
int :y
int :z
byte :rotation
byte :pitch
end
server_packet :entity_damage, 0x26 do
int :id
byte :damage
end
server_packet :attach_entity, 0x27 do
int :entity_id
int :vehicle_id # -1 for unattach
end
server_packet :entity_metadata, 0x28 do
int :entity_id
field :metadata, Field::MobData
end
server_packet :pre_chunk, 0x32 do
int :x # multiply by 16
int :z # multiply by 16
bool :add
end
server_packet :map_chunk, 0x33 do
int :x
short :y
int :z
byte :size_x
byte :size_y
byte :size_z
field :chunk, Field::MapChunk
def inspect
"<0x33 map chunk: [#{size_x + 1}, #{size_y + 1}, #{size_x + 1}]>"
end
end
server_packet :multi_block_change, 0x34 do
int :x
int :z
field :block_changes, Field::MultiBlockChange
def changes
offset_x = x * 16
offset_z = z * 16
coords, types, metadata = *block_changes
coords.map.with_index do |num, i|
change_x = ((num & 0xF000) >> 12) + offset_x
change_z = ((num & 0x0F00) >> 8) + offset_z
change_y = num & 0xFF
[[change_x, change_y, change_z], types[i]]
end
end
end
server_packet :block_change, 0x35 do
int :x
byte :y
int :z
byte :type
byte :metadata
end
server_packet :play_note, 0x36 do
int :x
short :y
int :z
byte :instrument
byte :pitch
end
server_packet :explosion, 0x3c do
double :x
double :y
double :z
float :radius # maybe?
field :explosion, Field::ExplosionBlocks
end
server_packet :open_window, 0x64 do
byte :window_id
byte :inventory_type
string :window_title
byte :number_of_slots
end
client_packet :close_window, 0x65 do
byte :window_id
end
client_packet :window_click, 0x66 do
byte :window_id
short :slot
byte :right_click
short :action_number
field :items, Field::SlotItems
end
server_packet :set_slot, 0x67 do
byte :window_id # 0 for inventory
short :slot
field :items, Field::SlotItems
end
server_packet :window_items, 0x68 do
byte :type # 0 for inventory
field :items, Field::WindowItems
end
server_packet :update_progress_bar, 0x69 do
byte :window_id
short :progress_bar # furnace: 0 is progress, 1 is fire
short :value
end
server_packet :transaction, 0x6a do
byte :window_id
short :action_number # must be in sequence
bool :accepted
end
client_packet :transaction, 0x6a do
byte :window_id
short :action_number
bool :accepted
end
client_packet :update_sign, 0x82 do
int :x
short :y
int :z
string :text_1
string :text_2
string :text_3
string :text_4
end
server_packet :update_sign, 0x82 do
int :x
short :y
int :z
string :text_1
string :text_2
string :text_3
string :text_4
end
client_packet :disconnect, 0xff do
string :message
end
server_packet :disconnect, 0xff do
string :message
end
end
end
Server can send close_window packet too
module Golem
module Packets
PROTOCOL_VERSION = 8
def self.client_packet(kind, code, &blk)
p = Class.new(Packet)
p.kind = kind
p.code = code
p.module_eval(&blk) if blk
Packet.client_packet p
end
def self.server_packet(kind, code, &blk)
p = Class.new(Packet)
p.kind = kind
p.code = code
p.module_eval(&blk) if blk
Packet.server_packet p
end
client_packet :keepalive, 0x00
server_packet :keepalive, 0x00
client_packet :login, 0x01 do
int :protocol_version
string :username
string :password
long :map_seed # always 0, not required
byte :dimension # always 0, not required
end
server_packet :accept_login, 0x01 do
int :player_id
string :server_name # ?
string :motd # ?
long :map_seed
byte :dimension
end
client_packet :handshake, 0x02 do
string :username
end
server_packet :handshake, 0x02 do
string :server_id
end
server_packet :chat, 0x03 do
string :message
end
client_packet :chat, 0x03 do
string :message
end
server_packet :update_time, 0x04 do
long :time
end
server_packet :entity_equipment, 0x05 do
int :entity_id
short :slot # 0 = held, 1-4 = armor slots
short :item_id # -1 for empty
short :damage?
end
server_packet :spawn_position, 0x06 do
int :x
int :y
int :z
end
server_packet :use_entity, 0x07 do
int :player_id
int :entity_id
bool :left_click # true when pointing at an entity, false when using a block
end
client_packet :use_entity, 0x07 do
int :player_id
int :entity_id
bool :left_click # true when pointing at an entity, false when using a block
end
server_packet :player_health, 0x08 do
short :health # 0 = dead, 20 = full
end
server_packet :respawn, 0x09 do
end
client_packet :respawn, 0x09 do
end
client_packet :flying_ack, 0x0a do
bool :flying
end
server_packet :flying, 0x0a do
bool :flying
end
client_packet :player_position, 0x0b do
double :x
double :y
double :stance
double :z
bool :flying
end
server_packet :player_position, 0x0b do
double :x
double :y
double :stance
double :z
bool :flying
end
server_packet :player_look, 0x0c do
float :rotation
float :pitch
bool :flying
end
client_packet :player_look, 0x0c do
float :rotation
float :pitch
bool :flying
end
client_packet :player_move_look, 0x0d do
double :x
double :y
double :stance
double :z
float :rotation
float :pitch
bool :flying
end
server_packet :player_move_look, 0x0d do
double :x
# yes, this is reversed from the packet the client sends.
double :stance
double :y
double :z
float :rotation
float :pitch
bool :flying
end
client_packet :block_dig, 0x0e do
byte :status
int :x
byte :y
int :z
byte :direction
end
client_packet :place, 0x0f do
int :x
byte :y
int :z
byte :direction
field :items, Field::SlotItems
end
client_packet :holding_change, 0x10 do
short :slot_id # slot which player has selected, 0-8
end
server_packet :animation, 0x12 do
int :entity_id
byte :animate # 0 = no animation, 1 = swing, 2 = death? 102 = ?
end
client_packet :animation, 0x12 do
int :entity_id
byte :animate
end
client_packet :entity_action, 0x13 do
int :entity_id
byte :action # 1 crouch, 2 uncrouch?
end
server_packet :named_entity_spawn, 0x14 do
int :id
string :name
int :x
int :y
int :z
byte :rotation
byte :pitch
short :current_item
end
# client drops something
client_packet :pickup_spawn, 0x15 do
int :id
short :item
byte :count
short :damage?
int :x
int :y
int :z
byte :rotation
byte :pitch
byte :roll
end
server_packet :pickup_spawn, 0x15 do
int :id
short :item
byte :count
short :damage?
int :x
int :y
int :z
byte :rotation
byte :pitch
byte :roll
end
server_packet :collect_item, 0x16 do
int :item_id
int :collector_id
end
server_packet :vehicle_spawn, 0x17 do
int :id
byte :type
int :x
int :y
int :z
end
server_packet :mob_spawn, 0x18 do
int :id
byte :type
int :x
int :y
int :z
byte :rotation
byte :pitch
field :mob_data, Field::MobData
end
server_packet :painting, 0x19 do
int :id
string :title # name of the painting
int :x
int :y
int :z
int :type
end
server_packet :entity_velocity, 0x1c do
int :id
short :v_x
short :v_y
short :v_z
end
server_packet :destroy_entity, 0x1d do
int :id
end
server_packet :entity, 0x1e do
int :id
end
server_packet :entity_move, 0x1f do
int :id
byte :x
byte :y
byte :z
end
server_packet :entity_look, 0x20 do
int :id
byte :rotation
byte :pitch
end
server_packet :entity_move_look, 0x21 do
int :id
byte :x
byte :y
byte :z
byte :rotation
byte :pitch
end
server_packet :entity_teleport, 0x22 do
int :id
int :x
int :y
int :z
byte :rotation
byte :pitch
end
server_packet :entity_damage, 0x26 do
int :id
byte :damage
end
server_packet :attach_entity, 0x27 do
int :entity_id
int :vehicle_id # -1 for unattach
end
server_packet :entity_metadata, 0x28 do
int :entity_id
field :metadata, Field::MobData
end
server_packet :pre_chunk, 0x32 do
int :x # multiply by 16
int :z # multiply by 16
bool :add
end
server_packet :map_chunk, 0x33 do
int :x
short :y
int :z
byte :size_x
byte :size_y
byte :size_z
field :chunk, Field::MapChunk
def inspect
"<0x33 map chunk: [#{size_x + 1}, #{size_y + 1}, #{size_x + 1}]>"
end
end
server_packet :multi_block_change, 0x34 do
int :x
int :z
field :block_changes, Field::MultiBlockChange
def changes
offset_x = x * 16
offset_z = z * 16
coords, types, metadata = *block_changes
coords.map.with_index do |num, i|
change_x = ((num & 0xF000) >> 12) + offset_x
change_z = ((num & 0x0F00) >> 8) + offset_z
change_y = num & 0xFF
[[change_x, change_y, change_z], types[i]]
end
end
end
server_packet :block_change, 0x35 do
int :x
byte :y
int :z
byte :type
byte :metadata
end
server_packet :play_note, 0x36 do
int :x
short :y
int :z
byte :instrument
byte :pitch
end
server_packet :explosion, 0x3c do
double :x
double :y
double :z
float :radius # maybe?
field :explosion, Field::ExplosionBlocks
end
server_packet :open_window, 0x64 do
byte :window_id
byte :inventory_type
string :window_title
byte :number_of_slots
end
server_packet :close_window, 0x65 do
byte :window_id
end
client_packet :close_window, 0x65 do
byte :window_id
end
client_packet :window_click, 0x66 do
byte :window_id
short :slot
byte :right_click
short :action_number
field :items, Field::SlotItems
end
server_packet :set_slot, 0x67 do
byte :window_id # 0 for inventory
short :slot
field :items, Field::SlotItems
end
server_packet :window_items, 0x68 do
byte :type # 0 for inventory
field :items, Field::WindowItems
end
server_packet :update_progress_bar, 0x69 do
byte :window_id
short :progress_bar # furnace: 0 is progress, 1 is fire
short :value
end
server_packet :transaction, 0x6a do
byte :window_id
short :action_number # must be in sequence
bool :accepted
end
client_packet :transaction, 0x6a do
byte :window_id
short :action_number
bool :accepted
end
client_packet :update_sign, 0x82 do
int :x
short :y
int :z
string :text_1
string :text_2
string :text_3
string :text_4
end
server_packet :update_sign, 0x82 do
int :x
short :y
int :z
string :text_1
string :text_2
string :text_3
string :text_4
end
client_packet :disconnect, 0xff do
string :message
end
server_packet :disconnect, 0xff do
string :message
end
end
end
|
require 'digest/sha1'
require 'cgi'
module Gollum
class Markup
# Initialize a new Markup object.
#
# page - The Gollum::Page.
#
# Returns a new Gollum::Markup object, ready for rendering.
def initialize(page)
@wiki = page.wiki
@name = page.filename
@data = page.text_data
@version = page.version.id
@dir = ::File.dirname(page.path)
@tagmap = {}
@codemap = {}
@texmap = {}
end
# Render the content with Gollum wiki syntax on top of the file's own
# markup language.
#
# no_follow - Boolean that determines if rel="nofollow" is added to all
# <a> tags.
#
# Returns the formatted String content.
def render(no_follow = false)
sanitize_options = no_follow ?
@wiki.history_sanitization :
@wiki.sanitization
data = extract_tex(@data)
data = extract_code(data)
data = extract_tags(data)
begin
data = GitHub::Markup.render(@name, data)
if data.nil?
raise "There was an error converting #{@name} to HTML."
end
rescue Object => e
data = %{<p class="gollum-error">#{e.message}</p>}
end
data = process_tags(data)
data = process_code(data)
data = Sanitize.clean(data, sanitize_options.to_hash) if sanitize_options
data = process_tex(data)
data.gsub!(/<p><\/p>/, '')
data
end
#########################################################################
#
# TeX
#
#########################################################################
# Extract all TeX into the texmap and replace with placeholders.
#
# data - The raw String data.
#
# Returns the placeholder'd String data.
def extract_tex(data)
data.gsub(/\\\[\s*(.*?)\s*\\\]/m) do
id = Digest::SHA1.hexdigest($1)
@texmap[id] = [:block, $1]
id
end.gsub(/\\\(\s*(.*?)\s*\\\)/m) do
id = Digest::SHA1.hexdigest($1)
@texmap[id] = [:inline, $1]
id
end
end
# Process all TeX from the texmap and replace the placeholders with the
# final markup.
#
# data - The String data (with placeholders).
#
# Returns the marked up String data.
def process_tex(data)
@texmap.each do |id, spec|
type, tex = *spec
out =
case type
when :block
%{<script type="math/tex; mode=display">#{tex}</script>}
when :inline
%{<script type="math/tex">#{tex}</script>}
end
data.gsub!(id, out)
end
data
end
#########################################################################
#
# Tags
#
#########################################################################
# Extract all tags into the tagmap and replace with placeholders.
#
# data - The raw String data.
#
# Returns the placeholder'd String data.
def extract_tags(data)
data.gsub(/(.?)\[\[(.+?)\]\]([^\[]?)/m) do
if $1 == "'" && $3 != "'"
"[[#{$2}]]#{$3}"
elsif $2.include?('][')
$&
else
id = Digest::SHA1.hexdigest($2)
@tagmap[id] = $2
"#{$1}#{id}#{$3}"
end
end
end
# Process all tags from the tagmap and replace the placeholders with the
# final markup.
#
# data - The String data (with placeholders).
# no_follow - Boolean that determines if rel="nofollow" is added to all
# <a> tags.
#
# Returns the marked up String data.
def process_tags(data, no_follow = false)
@tagmap.each do |id, tag|
data.gsub!(id, process_tag(tag, no_follow))
end
data
end
# Process a single tag into its final HTML form.
#
# tag - The String tag contents (the stuff inside the double
# brackets).
# no_follow - Boolean that determines if rel="nofollow" is added to all
# <a> tags.
#
# Returns the String HTML version of the tag.
def process_tag(tag, no_follow = false)
if html = process_image_tag(tag)
html
elsif html = process_file_link_tag(tag, no_follow)
html
else
process_page_link_tag(tag, no_follow)
end
end
# Attempt to process the tag as an image tag.
#
# tag - The String tag contents (the stuff inside the double brackets).
#
# Returns the String HTML if the tag is a valid image tag or nil
# if it is not.
def process_image_tag(tag)
parts = tag.split('|')
name = parts[0].strip
path = if file = find_file(name)
::File.join @wiki.base_path, file.path
elsif name =~ /^https?:\/\/.+(jpg|png|gif|svg|bmp)$/i
name
end
if path
opts = parse_image_tag_options(tag)
containered = false
classes = [] # applied to whatever the outermost container is
attrs = [] # applied to the image
align = opts['align']
if opts['float']
containered = true
align ||= 'left'
if %w{left right}.include?(align)
classes << "float-#{align}"
end
elsif %w{top texttop middle absmiddle bottom absbottom baseline}.include?(align)
attrs << %{align="#{align}"}
elsif align
if %w{left center right}.include?(align)
containered = true
classes << "align-#{align}"
end
end
if width = opts['width']
if width =~ /^\d+(\.\d+)?(em|px)$/
attrs << %{width="#{width}"}
end
end
if height = opts['height']
if height =~ /^\d+(\.\d+)?(em|px)$/
attrs << %{height="#{height}"}
end
end
if alt = opts['alt']
attrs << %{alt="#{alt}"}
end
attr_string = attrs.size > 0 ? attrs.join(' ') + ' ' : ''
if opts['frame'] || containered
classes << 'frame' if opts['frame']
%{<span class="#{classes.join(' ')}">} +
%{<span>} +
%{<img src="#{path}" #{attr_string}/>} +
(alt ? %{<span>#{alt}</span>} : '') +
%{</span>} +
%{</span>}
else
%{<img src="#{path}" #{attr_string}/>}
end
end
end
# Parse any options present on the image tag and extract them into a
# Hash of option names and values.
#
# tag - The String tag contents (the stuff inside the double brackets).
#
# Returns the options Hash:
# key - The String option name.
# val - The String option value or true if it is a binary option.
def parse_image_tag_options(tag)
tag.split('|')[1..-1].inject({}) do |memo, attr|
parts = attr.split('=').map { |x| x.strip }
memo[parts[0]] = (parts.size == 1 ? true : parts[1])
memo
end
end
# Attempt to process the tag as a file link tag.
#
# tag - The String tag contents (the stuff inside the double
# brackets).
# no_follow - Boolean that determines if rel="nofollow" is added to all
# <a> tags.
#
# Returns the String HTML if the tag is a valid file link tag or nil
# if it is not.
def process_file_link_tag(tag, no_follow = false)
parts = tag.split('|')
name = parts[0].strip
path = parts[1] && parts[1].strip
path = if path && file = find_file(path)
::File.join @wiki.base_path, file.path
elsif path =~ %r{^https?://}
path
else
nil
end
tag = if name && path && file
%{<a href="#{::File.join @wiki.base_path, file.path}">#{name}</a>}
elsif name && path
%{<a href="#{path}">#{name}</a>}
else
nil
end
if tag && no_follow
tag.sub! /^<a/, '<a ref="nofollow"'
end
tag
end
# Attempt to process the tag as a page link tag.
#
# tag - The String tag contents (the stuff inside the double
# brackets).
# no_follow - Boolean that determines if rel="nofollow" is added to all
# <a> tags.
#
# Returns the String HTML if the tag is a valid page link tag or nil
# if it is not.
def process_page_link_tag(tag, no_follow = false)
parts = tag.split('|')
name = parts[0].strip
cname = @wiki.page_class.cname((parts[1] || parts[0]).strip)
tag = if name =~ %r{^https?://} && parts[1].nil?
%{<a href="#{name}">#{name}</a>}
else
presence = "absent"
link_name = cname
page, extra = find_page_from_name(cname)
if page
link_name = @wiki.page_class.cname(page.name)
presence = "present"
end
link = ::File.join(@wiki.base_path, CGI.escape(link_name))
%{<a class="internal #{presence}" href="#{link}#{extra}">#{name}</a>}
end
if tag && no_follow
tag.sub! /^<a/, '<a ref="nofollow"'
end
tag
end
# Find the given file in the repo.
#
# name - The String absolute or relative path of the file.
#
# Returns the Gollum::File or nil if none was found.
def find_file(name)
if name =~ /^\//
@wiki.file(name[1..-1], @version)
else
path = @dir == '.' ? name : ::File.join(@dir, name)
@wiki.file(path, @version)
end
end
# Find a page from a given cname. If the page has an anchor (#) and has
# no match, strip the anchor and try again.
#
# cname - The String canonical page name.
#
# Returns a Gollum::Page instance if a page is found, or an Array of
# [Gollum::Page, String extra] if a page without the extra anchor data
# is found.
def find_page_from_name(cname)
if page = @wiki.page(cname)
return page
end
if pos = cname.index('#')
[@wiki.page(cname[0...pos]), cname[pos..-1]]
end
end
#########################################################################
#
# Code
#
#########################################################################
# Extract all code blocks into the codemap and replace with placeholders.
#
# data - The raw String data.
#
# Returns the placeholder'd String data.
def extract_code(data)
data.gsub(/^``` ?(.+?)\r?\n(.+?)\r?\n```\r?$/m) do
id = Digest::SHA1.hexdigest($2)
cached = check_cache(:code, id)
@codemap[id] = cached ?
{ :output => cached } :
{ :lang => $1, :code => $2 }
id
end
end
# Process all code from the codemap and replace the placeholders with the
# final HTML.
#
# data - The String data (with placeholders).
#
# Returns the marked up String data.
def process_code(data)
@codemap.each do |id, spec|
formatted = spec[:output] || begin
lang = spec[:lang]
code = spec[:code]
if code.lines.all? { |line| line =~ /\A\r?\n\Z/ || line =~ /^( |\t)/ }
code.gsub!(/^( |\t)/m, '')
end
formatted = Gollum::Albino.new(code, lang).colorize
update_cache(:code, id, formatted)
formatted
end
data.gsub!(id, formatted)
end
data
end
# Hook for getting the formatted value of extracted tag data.
#
# type - Symbol value identifying what type of data is being extracted.
# id - String SHA1 hash of original extracted tag data.
#
# Returns the String cached formatted data, or nil.
def check_cache(type, id)
end
# Hook for caching the formatted value of extracted tag data.
#
# type - Symbol value identifying what type of data is being extracted.
# id - String SHA1 hash of original extracted tag data.
# data - The String formatted value to be cached.
#
# Returns nothing.
def update_cache(type, id, data)
end
end
end
re-use Sanitize instances in Gollum::Markup
require 'digest/sha1'
require 'cgi'
module Gollum
class Markup
# Initialize a new Markup object.
#
# page - The Gollum::Page.
#
# Returns a new Gollum::Markup object, ready for rendering.
def initialize(page)
@wiki = page.wiki
@name = page.filename
@data = page.text_data
@version = page.version.id
@dir = ::File.dirname(page.path)
@tagmap = {}
@codemap = {}
@texmap = {}
end
# Render the content with Gollum wiki syntax on top of the file's own
# markup language.
#
# no_follow - Boolean that determines if rel="nofollow" is added to all
# <a> tags.
#
# Returns the formatted String content.
def render(no_follow = false)
sanitize = no_follow ?
@wiki.history_sanitizer :
@wiki.sanitizer
data = extract_tex(@data)
data = extract_code(data)
data = extract_tags(data)
begin
data = GitHub::Markup.render(@name, data)
if data.nil?
raise "There was an error converting #{@name} to HTML."
end
rescue Object => e
data = %{<p class="gollum-error">#{e.message}</p>}
end
data = process_tags(data)
data = process_code(data)
data = sanitize.clean!(data) if sanitize
data = process_tex(data)
data.gsub!(/<p><\/p>/, '')
data
end
def doc_to_html(doc)
doc.to_xhtml(:save_with => Nokogiri::XML::Node::SaveOptions::AS_XHTML)
end
#########################################################################
#
# TeX
#
#########################################################################
# Extract all TeX into the texmap and replace with placeholders.
#
# data - The raw String data.
#
# Returns the placeholder'd String data.
def extract_tex(data)
data.gsub(/\\\[\s*(.*?)\s*\\\]/m) do
id = Digest::SHA1.hexdigest($1)
@texmap[id] = [:block, $1]
id
end.gsub(/\\\(\s*(.*?)\s*\\\)/m) do
id = Digest::SHA1.hexdigest($1)
@texmap[id] = [:inline, $1]
id
end
end
# Process all TeX from the texmap and replace the placeholders with the
# final markup.
#
# data - The String data (with placeholders).
#
# Returns the marked up String data.
def process_tex(data)
@texmap.each do |id, spec|
type, tex = *spec
out =
case type
when :block
%{<script type="math/tex; mode=display">#{tex}</script>}
when :inline
%{<script type="math/tex">#{tex}</script>}
end
data.gsub!(id, out)
end
data
end
#########################################################################
#
# Tags
#
#########################################################################
# Extract all tags into the tagmap and replace with placeholders.
#
# data - The raw String data.
#
# Returns the placeholder'd String data.
def extract_tags(data)
data.gsub(/(.?)\[\[(.+?)\]\]([^\[]?)/m) do
if $1 == "'" && $3 != "'"
"[[#{$2}]]#{$3}"
elsif $2.include?('][')
$&
else
id = Digest::SHA1.hexdigest($2)
@tagmap[id] = $2
"#{$1}#{id}#{$3}"
end
end
end
# Process all tags from the tagmap and replace the placeholders with the
# final markup.
#
# data - The String data (with placeholders).
# no_follow - Boolean that determines if rel="nofollow" is added to all
# <a> tags.
#
# Returns the marked up String data.
def process_tags(data, no_follow = false)
@tagmap.each do |id, tag|
data.gsub!(id, process_tag(tag, no_follow))
end
data
end
# Process a single tag into its final HTML form.
#
# tag - The String tag contents (the stuff inside the double
# brackets).
# no_follow - Boolean that determines if rel="nofollow" is added to all
# <a> tags.
#
# Returns the String HTML version of the tag.
def process_tag(tag, no_follow = false)
if html = process_image_tag(tag)
html
elsif html = process_file_link_tag(tag, no_follow)
html
else
process_page_link_tag(tag, no_follow)
end
end
# Attempt to process the tag as an image tag.
#
# tag - The String tag contents (the stuff inside the double brackets).
#
# Returns the String HTML if the tag is a valid image tag or nil
# if it is not.
def process_image_tag(tag)
parts = tag.split('|')
name = parts[0].strip
path = if file = find_file(name)
::File.join @wiki.base_path, file.path
elsif name =~ /^https?:\/\/.+(jpg|png|gif|svg|bmp)$/i
name
end
if path
opts = parse_image_tag_options(tag)
containered = false
classes = [] # applied to whatever the outermost container is
attrs = [] # applied to the image
align = opts['align']
if opts['float']
containered = true
align ||= 'left'
if %w{left right}.include?(align)
classes << "float-#{align}"
end
elsif %w{top texttop middle absmiddle bottom absbottom baseline}.include?(align)
attrs << %{align="#{align}"}
elsif align
if %w{left center right}.include?(align)
containered = true
classes << "align-#{align}"
end
end
if width = opts['width']
if width =~ /^\d+(\.\d+)?(em|px)$/
attrs << %{width="#{width}"}
end
end
if height = opts['height']
if height =~ /^\d+(\.\d+)?(em|px)$/
attrs << %{height="#{height}"}
end
end
if alt = opts['alt']
attrs << %{alt="#{alt}"}
end
attr_string = attrs.size > 0 ? attrs.join(' ') + ' ' : ''
if opts['frame'] || containered
classes << 'frame' if opts['frame']
%{<span class="#{classes.join(' ')}">} +
%{<span>} +
%{<img src="#{path}" #{attr_string}/>} +
(alt ? %{<span>#{alt}</span>} : '') +
%{</span>} +
%{</span>}
else
%{<img src="#{path}" #{attr_string}/>}
end
end
end
# Parse any options present on the image tag and extract them into a
# Hash of option names and values.
#
# tag - The String tag contents (the stuff inside the double brackets).
#
# Returns the options Hash:
# key - The String option name.
# val - The String option value or true if it is a binary option.
def parse_image_tag_options(tag)
tag.split('|')[1..-1].inject({}) do |memo, attr|
parts = attr.split('=').map { |x| x.strip }
memo[parts[0]] = (parts.size == 1 ? true : parts[1])
memo
end
end
# Attempt to process the tag as a file link tag.
#
# tag - The String tag contents (the stuff inside the double
# brackets).
# no_follow - Boolean that determines if rel="nofollow" is added to all
# <a> tags.
#
# Returns the String HTML if the tag is a valid file link tag or nil
# if it is not.
def process_file_link_tag(tag, no_follow = false)
parts = tag.split('|')
name = parts[0].strip
path = parts[1] && parts[1].strip
path = if path && file = find_file(path)
::File.join @wiki.base_path, file.path
elsif path =~ %r{^https?://}
path
else
nil
end
tag = if name && path && file
%{<a href="#{::File.join @wiki.base_path, file.path}">#{name}</a>}
elsif name && path
%{<a href="#{path}">#{name}</a>}
else
nil
end
if tag && no_follow
tag.sub! /^<a/, '<a ref="nofollow"'
end
tag
end
# Attempt to process the tag as a page link tag.
#
# tag - The String tag contents (the stuff inside the double
# brackets).
# no_follow - Boolean that determines if rel="nofollow" is added to all
# <a> tags.
#
# Returns the String HTML if the tag is a valid page link tag or nil
# if it is not.
def process_page_link_tag(tag, no_follow = false)
parts = tag.split('|')
name = parts[0].strip
cname = @wiki.page_class.cname((parts[1] || parts[0]).strip)
tag = if name =~ %r{^https?://} && parts[1].nil?
%{<a href="#{name}">#{name}</a>}
else
presence = "absent"
link_name = cname
page, extra = find_page_from_name(cname)
if page
link_name = @wiki.page_class.cname(page.name)
presence = "present"
end
link = ::File.join(@wiki.base_path, CGI.escape(link_name))
%{<a class="internal #{presence}" href="#{link}#{extra}">#{name}</a>}
end
if tag && no_follow
tag.sub! /^<a/, '<a ref="nofollow"'
end
tag
end
# Find the given file in the repo.
#
# name - The String absolute or relative path of the file.
#
# Returns the Gollum::File or nil if none was found.
def find_file(name)
if name =~ /^\//
@wiki.file(name[1..-1], @version)
else
path = @dir == '.' ? name : ::File.join(@dir, name)
@wiki.file(path, @version)
end
end
# Find a page from a given cname. If the page has an anchor (#) and has
# no match, strip the anchor and try again.
#
# cname - The String canonical page name.
#
# Returns a Gollum::Page instance if a page is found, or an Array of
# [Gollum::Page, String extra] if a page without the extra anchor data
# is found.
def find_page_from_name(cname)
if page = @wiki.page(cname)
return page
end
if pos = cname.index('#')
[@wiki.page(cname[0...pos]), cname[pos..-1]]
end
end
#########################################################################
#
# Code
#
#########################################################################
# Extract all code blocks into the codemap and replace with placeholders.
#
# data - The raw String data.
#
# Returns the placeholder'd String data.
def extract_code(data)
data.gsub(/^``` ?(.+?)\r?\n(.+?)\r?\n```\r?$/m) do
id = Digest::SHA1.hexdigest($2)
cached = check_cache(:code, id)
@codemap[id] = cached ?
{ :output => cached } :
{ :lang => $1, :code => $2 }
id
end
end
# Process all code from the codemap and replace the placeholders with the
# final HTML.
#
# data - The String data (with placeholders).
#
# Returns the marked up String data.
def process_code(data)
@codemap.each do |id, spec|
formatted = spec[:output] || begin
lang = spec[:lang]
code = spec[:code]
if code.lines.all? { |line| line =~ /\A\r?\n\Z/ || line =~ /^( |\t)/ }
code.gsub!(/^( |\t)/m, '')
end
formatted = Gollum::Albino.new(code, lang).colorize
update_cache(:code, id, formatted)
formatted
end
data.gsub!(id, formatted)
end
data
end
# Hook for getting the formatted value of extracted tag data.
#
# type - Symbol value identifying what type of data is being extracted.
# id - String SHA1 hash of original extracted tag data.
#
# Returns the String cached formatted data, or nil.
def check_cache(type, id)
end
# Hook for caching the formatted value of extracted tag data.
#
# type - Symbol value identifying what type of data is being extracted.
# id - String SHA1 hash of original extracted tag data.
# data - The String formatted value to be cached.
#
# Returns nothing.
def update_cache(type, id, data)
end
end
end
|
module GraderScript
def self.grader_control_enabled?
if defined? GRADER_ROOT_DIR
GRADER_ROOT_DIR != ''
else
false
end
end
def self.raw_dir
File.join GRADER_ROOT_DIR, "raw"
end
def self.call_grader(params)
if GraderScript.grader_control_enabled?
cmd = File.join(GRADER_ROOT_DIR, "scripts/grader") + " " + params
system(cmd)
end
end
def self.stop_grader(pid)
GraderScript.call_grader "stop #{pid}"
end
def self.stop_graders(pids)
pid_str = (pids.map { |process| process.pid.to_a }).join ' '
GraderScript.call_grader "stop #{pid_str}"
end
def self.start_grader(env)
GraderScript.call_grader "#{env} queue &"
GraderScript.call_grader "#{env} test_request &"
end
def self.call_import_problem(problem_name,
problem_dir,
time_limit=1,
memory_limit=32,
checker_name='text')
if GraderScript.grader_control_enabled?
cur_dir = `pwd`.chomp
Dir.chdir(GRADER_ROOT_DIR)
script_name = File.join(GRADER_ROOT_DIR, "scripts/import_problem")
cmd = "#{script_name} #{problem_name} #{problem_dir} #{checker_name}" +
" -t #{time_limit} -m #{memory_limit}"
output = `#{cmd}`
Dir.chdir(cur_dir)
return output
end
return ''
end
end
changed to_a to to_s
module GraderScript
def self.grader_control_enabled?
if defined? GRADER_ROOT_DIR
GRADER_ROOT_DIR != ''
else
false
end
end
def self.raw_dir
File.join GRADER_ROOT_DIR, "raw"
end
def self.call_grader(params)
if GraderScript.grader_control_enabled?
cmd = File.join(GRADER_ROOT_DIR, "scripts/grader") + " " + params
system(cmd)
end
end
def self.stop_grader(pid)
GraderScript.call_grader "stop #{pid}"
end
def self.stop_graders(pids)
pid_str = (pids.map { |process| process.pid.to_s }).join ' '
GraderScript.call_grader "stop #{pid_str}"
end
def self.start_grader(env)
GraderScript.call_grader "#{env} queue &"
GraderScript.call_grader "#{env} test_request &"
end
def self.call_import_problem(problem_name,
problem_dir,
time_limit=1,
memory_limit=32,
checker_name='text')
if GraderScript.grader_control_enabled?
cur_dir = `pwd`.chomp
Dir.chdir(GRADER_ROOT_DIR)
script_name = File.join(GRADER_ROOT_DIR, "scripts/import_problem")
cmd = "#{script_name} #{problem_name} #{problem_dir} #{checker_name}" +
" -t #{time_limit} -m #{memory_limit}"
output = `#{cmd}`
Dir.chdir(cur_dir)
return output
end
return ''
end
end
|
require 'guard'
require 'guard/guard'
require 'guard/watcher'
module Guard
class Jasmine < Guard
autoload :Formatter, 'guard/jasmine/formatter'
autoload :Inspector, 'guard/jasmine/inspector'
autoload :Runner, 'guard/jasmine/runner'
def initialize(watchers = [], options = { })
defaults = {
:jasmine_url => 'http://localhost:3000/jasmine',
:phantomjs_bin => '/usr/local/bin/phantomjs',
:notification => true,
:hide_success => false,
:all_on_start => true
}
super(watchers, defaults.merge(options))
end
def start
run_all if options[:all_on_start]
end
def run_all
run_on_change(['spec/javascripts'])
end
def run_on_change(paths)
Runner.run(Inspector.clean(paths), options)
end
end
end
Add yardoc to the Jasmine Guard.
require 'guard'
require 'guard/guard'
require 'guard/watcher'
module Guard
# The Jasmine guard that gets notifications about the following
# Guard events: `start`, `stop`, `reload`, `run_all` and `run_on_change`.
#
class Jasmine < Guard
autoload :Formatter, 'guard/jasmine/formatter'
autoload :Inspector, 'guard/jasmine/inspector'
autoload :Runner, 'guard/jasmine/runner'
# Initialize Guard::Jasmine.
#
# @param [Array<Guard::Watcher>] watchers the watchers in the Guard block
# @param [Hash] options the options for the Guard
# @option options [String] :jasmine_url the url of the Jasmine test runner
# @option options [String] :phantomjs_bin the location of the PhantomJS binary
# @option options [Boolean] :notification show notifications
# @option options [Boolean] :hide_success hide success message notification
# @option options [Boolean] :all_on_start run all suites on start
#
def initialize(watchers = [], options = { })
defaults = {
:jasmine_url => 'http://localhost:3000/jasmine',
:phantomjs_bin => '/usr/local/bin/phantomjs',
:notification => true,
:hide_success => false,
:all_on_start => true
}
super(watchers, defaults.merge(options))
end
# Gets called once when Guard starts.
#
def start
run_all if options[:all_on_start]
end
# Gets called when all specs should be run.
#
def run_all
run_on_change(['spec/javascripts'])
end
# Gets called when watched paths and files have changes.
#
# @param [Array<String>] paths the changed paths and files
#
def run_on_change(paths)
Runner.run(Inspector.clean(paths), options)
end
end
end
|
require 'guard'
require 'guard/guard'
module Guard
class Migrate < Guard
autoload :Notify, 'guard/migrate/notify'
attr_reader :seed, :rails_env
def initialize(watchers=[], options={})
super
@reset = true if options[:reset] == true
@test_clone = true unless options[:test_clone] == false
@run_on_start = true if options[:run_on_start] == true
@rails_env = options[:rails_env]
@seed = options[:seed]
end
def bundler?
@bundler ||= File.exist?("#{Dir.pwd}/Gemfile")
end
def run_on_start?
!!@run_on_start
end
def test_clone?
!!@test_clone
end
def reset?
!!@reset
end
# =================
# = Guard methods =
# =================
# If one of those methods raise an exception, the Guard::GuardName instance
# will be removed from the active guards.
# Called once when Guard starts
# Please override initialize method to init stuff
def start
migrate if run_on_start?
end
# Called on Ctrl-C signal (when Guard quits)
def stop
true
end
# Called on Ctrl-Z signal
# This method should be mainly used for "reload" (really!) actions like reloading passenger/spork/bundler/...
def reload
migrate if run_on_start?
end
# Called on Ctrl-/ signal
# This method should be principally used for long action like running all specs/tests/...
def run_all
migrate if run_on_start?
end
# Called on file(s) modifications
def run_on_changes(paths)
if paths.any?{|path| path.match(%r{^db/migrate/(\d+).+\.rb})}
paths.delete_if { |path| invalid?(path) }
migrate(paths.map{|path| path.scan(%r{^db/migrate/(\d+).+\.rb}).flatten.first})
elsif paths.any?{|path| path.match(%r{^db/seeds\.rb$})}
seed_only
end
end
def migrate(paths = [])
return if !reset? && paths.empty?
if reset?
UI.info "Running #{rake_string}"
result = system(rake_string)
result &&= "reset"
else
result = run_all_migrations(paths)
end
Notify.new(result).notify
end
def seed_only
UI.info "Running #{seed_only_string}"
result = system(seed_only_string)
result &&= "seed"
Notify.new(result).notify
end
def run_redo?(path)
!reset? && path && !path.empty?
end
def rake_string(path = nil)
[
rake_command,
migrate_string(path),
seed_string,
clone_string,
rails_env_string
].compact.join(" ")
end
def seed_only_string
[
rake_command,
seed_string,
clone_string,
rails_env_string
].compact.join(" ")
end
private
def run_all_migrations(paths)
result = nil
paths.each do |path|
UI.info "Running #{rake_string(path)}"
result = system rake_string(path)
break unless result
end
result
end
def rake_command
command = ""
command += "bundle exec " if bundler?
command += "rake"
command
end
def rails_env_string
"RAILS_ENV=#{rails_env}" if rails_env
end
def clone_string
"db:test:clone" if test_clone?
end
def seed_string
"db:seed" if @seed
end
def migrate_string(path)
string = "db:migrate"
string += ":reset" if reset?
string += ":redo VERSION=#{path}" if run_redo?(path)
string
end
def invalid?(path)
migration = File.open(path, 'r')
!migration.read.match(/def (up|down|change)(\n|\s)+end/).nil?
rescue Errno::ENOENT
true
end
end
end
Close file properly
require 'guard'
require 'guard/guard'
module Guard
class Migrate < Guard
autoload :Notify, 'guard/migrate/notify'
attr_reader :seed, :rails_env
def initialize(watchers=[], options={})
super
@reset = true if options[:reset] == true
@test_clone = true unless options[:test_clone] == false
@run_on_start = true if options[:run_on_start] == true
@rails_env = options[:rails_env]
@seed = options[:seed]
end
def bundler?
@bundler ||= File.exist?("#{Dir.pwd}/Gemfile")
end
def run_on_start?
!!@run_on_start
end
def test_clone?
!!@test_clone
end
def reset?
!!@reset
end
# =================
# = Guard methods =
# =================
# If one of those methods raise an exception, the Guard::GuardName instance
# will be removed from the active guards.
# Called once when Guard starts
# Please override initialize method to init stuff
def start
migrate if run_on_start?
end
# Called on Ctrl-C signal (when Guard quits)
def stop
true
end
# Called on Ctrl-Z signal
# This method should be mainly used for "reload" (really!) actions like reloading passenger/spork/bundler/...
def reload
migrate if run_on_start?
end
# Called on Ctrl-/ signal
# This method should be principally used for long action like running all specs/tests/...
def run_all
migrate if run_on_start?
end
# Called on file(s) modifications
def run_on_changes(paths)
if paths.any?{|path| path.match(%r{^db/migrate/(\d+).+\.rb})}
paths.delete_if { |path| invalid?(path) }
migrate(paths.map{|path| path.scan(%r{^db/migrate/(\d+).+\.rb}).flatten.first})
elsif paths.any?{|path| path.match(%r{^db/seeds\.rb$})}
seed_only
end
end
def migrate(paths = [])
return if !reset? && paths.empty?
if reset?
UI.info "Running #{rake_string}"
result = system(rake_string)
result &&= "reset"
else
result = run_all_migrations(paths)
end
Notify.new(result).notify
end
def seed_only
UI.info "Running #{seed_only_string}"
result = system(seed_only_string)
result &&= "seed"
Notify.new(result).notify
end
def run_redo?(path)
!reset? && path && !path.empty?
end
def rake_string(path = nil)
[
rake_command,
migrate_string(path),
seed_string,
clone_string,
rails_env_string
].compact.join(" ")
end
def seed_only_string
[
rake_command,
seed_string,
clone_string,
rails_env_string
].compact.join(" ")
end
private
def run_all_migrations(paths)
result = nil
paths.each do |path|
UI.info "Running #{rake_string(path)}"
result = system rake_string(path)
break unless result
end
result
end
def rake_command
command = ""
command += "bundle exec " if bundler?
command += "rake"
command
end
def rails_env_string
"RAILS_ENV=#{rails_env}" if rails_env
end
def clone_string
"db:test:clone" if test_clone?
end
def seed_string
"db:seed" if @seed
end
def migrate_string(path)
string = "db:migrate"
string += ":reset" if reset?
string += ":redo VERSION=#{path}" if run_redo?(path)
string
end
def invalid?(path)
migration = File.open(path, 'r')
!migration.read.match(/def (up|down|change)(\n|\s)+end/).nil?
rescue Errno::ENOENT
true
ensure
begin; migration.close; rescue; end
end
end
end
|
# frozen_string_literal: true
require 'temple'
require 'hamlit/parser'
require 'hamlit/compiler'
require 'hamlit/html'
require 'hamlit/escapable'
require 'hamlit/force_escapable'
require 'hamlit/dynamic_merger'
require 'hamlit/ambles'
module Hamlit
class Engine < Temple::Engine
define_options(
:buffer_class,
generator: Temple::Generators::ArrayBuffer,
format: :html,
attr_quote: "'",
escape_html: true,
escape_attrs: true,
autoclose: %w(area base basefont br col command embed frame
hr img input isindex keygen link menuitem meta
param source track wbr),
filename: "",
)
use Parser
use Compiler
use HTML
filter :StringSplitter
filter :StaticAnalyzer
use Escapable
use ForceEscapable
filter :ControlFlow
filter :MultiFlattener
filter :StaticMerger
use DynamicMerger
use Ambles
use :Generator, -> { options[:generator] }
end
end
Put Ambles before MultiFlattener for optimization
somehow it wasn't committed when I came up with it.
# frozen_string_literal: true
require 'temple'
require 'hamlit/parser'
require 'hamlit/compiler'
require 'hamlit/html'
require 'hamlit/escapable'
require 'hamlit/force_escapable'
require 'hamlit/dynamic_merger'
require 'hamlit/ambles'
module Hamlit
class Engine < Temple::Engine
define_options(
:buffer_class,
generator: Temple::Generators::ArrayBuffer,
format: :html,
attr_quote: "'",
escape_html: true,
escape_attrs: true,
autoclose: %w(area base basefont br col command embed frame
hr img input isindex keygen link menuitem meta
param source track wbr),
filename: "",
)
use Parser
use Compiler
use HTML
filter :StringSplitter
filter :StaticAnalyzer
use Escapable
use ForceEscapable
filter :ControlFlow
use Ambles
filter :MultiFlattener
filter :StaticMerger
use DynamicMerger
use :Generator, -> { options[:generator] }
end
end
|
module Happy
VERSION = "0.1.0.pre7"
end
Bump version to 0.1.0.pre8
module Happy
VERSION = "0.1.0.pre8"
end
|
module Happy
VERSION = "0.1.0.pre27"
end
Bump version to 0.1.0.pre28
module Happy
VERSION = "0.1.0.pre28"
end
|
module Hatokura
# A zone represents a place where objects can exist during a game.
#
# Original term: 領域
class Zone
def initialize()
@cards = []
end
# TODO: Define the owner of a zone for (actual) multiplayer games.
# Returns true for public zones such as Field and Market.
# Cards in public zones are always revealed.
def public?
@publicp
end
# Represent a pile of cards in this zone.
#
# The 0th element is corresponding to the top card of the pile, and
# the last element is corresponding to the bottom card of the pile.
#
# Note that cards in zones should not be accessed from everywhere.
# Cards should be accessed via high-level API.
protected def cards
@cards
end
end
end
Define Zone#put!
module Hatokura
# A zone represents a place where objects can exist during a game.
#
# Original term: 領域
class Zone
def initialize()
@cards = []
end
# TODO: Define the owner of a zone for (actual) multiplayer games.
# Returns true for public zones such as Field and Market.
# Cards in public zones are always revealed.
def public?
@publicp
end
# Represent a pile of cards in this zone.
#
# The 0th element is corresponding to the top card of the pile, and
# the last element is corresponding to the bottom card of the pile.
#
# Note that cards in zones should not be accessed from everywhere.
# Cards should be accessed via high-level API.
protected def cards
@cards
end
def put!(card, position)
# TODO: Change the revealed status of a card if necessary.
# For now, all cards are treated as revealed.
case position
when :top
cards.unshift(card)
when :bottom
cards.push(card)
else
throw ArgumentError.new("Invalid position #{position} to put a card")
end
end
end
end
|
$:.push File.expand_path('../lib', __FILE__)
require 'country_flags/version'
Gem::Specification.new do |s|
s.name = 'country_flags'
s.version = CountryFlags::VERSION
s.authors = ['Alexander Lazarov']
s.description = 'Gemified collection of country flags. See homepage for details: https://github.com/alexander-lazarov/isaf_id_validator'
s.email = 'alexander.lazaroff@gmail.com'
s.extra_rdoc_files = [ 'LICENSE' ]
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {spec}/*`.split("\n")
s.homepage = 'https://github.com/alexander-lazarov/country_flags'
s.require_paths = %w(lib)
s.summary = 'Gemified collection of country flags.'
s.license = 'MIT'
s.add_development_dependency('rspec', '>= 2.11')
end
add railties to dependencies
$:.push File.expand_path('../lib', __FILE__)
require 'country_flags/version'
Gem::Specification.new do |s|
s.name = 'country_flags'
s.version = CountryFlags::VERSION
s.authors = ['Alexander Lazarov']
s.description = 'Gemified collection of country flags. See homepage for details: https://github.com/alexander-lazarov/isaf_id_validator'
s.email = 'alexander.lazaroff@gmail.com'
s.extra_rdoc_files = [ 'LICENSE' ]
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {spec}/*`.split("\n")
s.homepage = 'https://github.com/alexander-lazarov/country_flags'
s.require_paths = %w(lib)
s.summary = 'Gemified collection of country flags.'
s.license = 'MIT'
s.add_development_dependency('rspec', '>= 2.11')
s.add_dependency "railties", ">= 3.1"
end
|
require_relative 'boot'
require 'rails/all'
require File.expand_path('../../lib/intercode/dynamic_cookie_domain', __FILE__)
require File.expand_path('../../lib/intercode/virtual_host_constraint', __FILE__)
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Intercode
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
config.autoloader = :zeitwerk
config.hosts << /.*#{Regexp.escape(ENV['INTERCODE_HOST'])/ if ENV['INTERCODE_HOST'].present?
config.hosts << ->(host) do
Convention.where(domain: host).any?
end
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
config.active_job.queue_adapter = :shoryuken
config.active_job.queue_name_prefix = "intercode_#{Rails.env}"
config.middleware.use Intercode::DynamicCookieDomain
config.middleware.use Intercode::FindVirtualHost
config.middleware.use Rack::Deflater
# To enable tsvectors and triggers; hopefully can get rid of this at some point :(
config.active_record.schema_format = :sql
config.generators do |g|
g.template_engine :erb
g.test_framework :test_unit, fixture: false
g.stylesheets false
g.javascripts false
end
config.assets.initialize_on_precompile = false
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
%w[liquid_drops presenters services].each do |subdir|
config.eager_load_paths << Rails.root.join("app/#{subdir}")
end
config.to_prepare do
# Only Applications list
Doorkeeper::ApplicationsController.layout 'doorkeeper/admin'
# Only Authorization endpoint
Doorkeeper::AuthorizationsController.layout 'application'
# Only Authorized Applications
Doorkeeper::AuthorizedApplicationsController.layout 'application'
DeviseController.respond_to :html, :json
end
end
end
Better whitelisting
require_relative 'boot'
require 'rails/all'
require File.expand_path('../../lib/intercode/dynamic_cookie_domain', __FILE__)
require File.expand_path('../../lib/intercode/virtual_host_constraint', __FILE__)
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Intercode
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
config.autoloader = :zeitwerk
config.hosts << ENV['ASSETS_HOST'] if ENV['ASSETS_HOST'].present?
config.hosts << /.*#{Regexp.escape(ENV['INTERCODE_HOST'])}/ if ENV['INTERCODE_HOST'].present?
config.hosts << ->(host) do
Convention.where(domain: host).any?
end
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
config.active_job.queue_adapter = :shoryuken
config.active_job.queue_name_prefix = "intercode_#{Rails.env}"
config.middleware.use Intercode::DynamicCookieDomain
config.middleware.use Intercode::FindVirtualHost
config.middleware.use Rack::Deflater
# To enable tsvectors and triggers; hopefully can get rid of this at some point :(
config.active_record.schema_format = :sql
config.generators do |g|
g.template_engine :erb
g.test_framework :test_unit, fixture: false
g.stylesheets false
g.javascripts false
end
config.assets.initialize_on_precompile = false
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
%w[liquid_drops presenters services].each do |subdir|
config.eager_load_paths << Rails.root.join("app/#{subdir}")
end
config.to_prepare do
# Only Applications list
Doorkeeper::ApplicationsController.layout 'doorkeeper/admin'
# Only Authorization endpoint
Doorkeeper::AuthorizationsController.layout 'application'
# Only Authorized Applications
Doorkeeper::AuthorizedApplicationsController.layout 'application'
DeviseController.respond_to :html, :json
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.