CombinedText stringlengths 4 3.42M |
|---|
module Danica
VERSION = '2.0.4'
end
Bump Version
module Danica
VERSION = '2.0.5'
end
|
try method on object
class Object
def try(*args, &block)
return if self.nil?
block.given? ? yield(self) : self.__send__(args.shift, *args)
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{graph.njae}
s.version = ""
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Neil Smith"]
s.date = %q{2011-09-23}
s.description = %q{A simple graph library}
s.email = %q{neil.github@njae.me.uk}
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
".rspec",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"graph.njae.gemspec",
"lib/graph.njae.rb",
"lib/graph/edge.rb",
"lib/graph/graph.rb",
"lib/graph/vertex.rb",
"spec/graph/edge_spec.rb",
"spec/graph/graph_spec.rb",
"spec/graph/vertex_spec.rb",
"spec/spec_helper.rb"
]
s.homepage = %q{http://github.com/NeilNjae/graph.njae}
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.6.2}
s.summary = %q{A simple graph library}
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<rspec>, ["~> 2.6.0"])
s.add_development_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_development_dependency(%q<jeweler>, ["~> 1.6.2"])
s.add_development_dependency(%q<rcov>, [">= 0"])
s.add_development_dependency(%q<rdoc>, [">= 0"])
else
s.add_dependency(%q<rspec>, ["~> 2.6.0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.6.2"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<rdoc>, [">= 0"])
end
else
s.add_dependency(%q<rspec>, ["~> 2.6.0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.6.2"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<rdoc>, [">= 0"])
end
end
Regenerate gemspec for version 0.0.0
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{graph.njae}
s.version = "0.0.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Neil Smith"]
s.date = %q{2011-09-23}
s.description = %q{A simple graph library}
s.email = %q{neil.github@njae.me.uk}
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
".rspec",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"graph.njae.gemspec",
"lib/graph.njae.rb",
"lib/graph/edge.rb",
"lib/graph/graph.rb",
"lib/graph/vertex.rb",
"spec/graph/edge_spec.rb",
"spec/graph/graph_spec.rb",
"spec/graph/vertex_spec.rb",
"spec/spec_helper.rb"
]
s.homepage = %q{http://github.com/NeilNjae/graph.njae}
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.6.2}
s.summary = %q{A simple graph library}
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<rspec>, ["~> 2.6.0"])
s.add_development_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_development_dependency(%q<jeweler>, ["~> 1.6.2"])
s.add_development_dependency(%q<rcov>, [">= 0"])
s.add_development_dependency(%q<rdoc>, [">= 0"])
else
s.add_dependency(%q<rspec>, ["~> 2.6.0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.6.2"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<rdoc>, [">= 0"])
end
else
s.add_dependency(%q<rspec>, ["~> 2.6.0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.6.2"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<rdoc>, [">= 0"])
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{just_giving}
s.version = "0.2.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = [%q{Thomas Pomfret}]
s.date = %q{2011-08-23}
s.description = %q{A ruby wrapper for the justgiving.com API}
s.email = %q{thomas@mintdigital.com}
s.extra_rdoc_files = [
"LICENSE.txt",
"README.md"
]
s.files = [
".document",
"Gemfile",
"LICENSE.txt",
"README.md",
"Rakefile",
"just_giving.gemspec",
"lib/faraday/raise_http_4xx.rb",
"lib/faraday/raise_http_5xx.rb",
"lib/just_giving.rb",
"lib/just_giving/account.rb",
"lib/just_giving/api.rb",
"lib/just_giving/charity.rb",
"lib/just_giving/configuration.rb",
"lib/just_giving/connection.rb",
"lib/just_giving/donation.rb",
"lib/just_giving/error.rb",
"lib/just_giving/event.rb",
"lib/just_giving/fundraising.rb",
"lib/just_giving/railtie.rb",
"lib/just_giving/request.rb",
"lib/just_giving/response.rb",
"lib/just_giving/search.rb",
"lib/just_giving/simple_donation_integration.rb",
"lib/just_giving/version.rb",
"lib/just_giving/view_helpers.rb",
"test/fixtures/account_create_fail.json",
"test/fixtures/account_create_success.json",
"test/fixtures/account_list_all_pages.json",
"test/fixtures/charity_auth_success.json",
"test/fixtures/charity_get_success.json",
"test/fixtures/donation_status_success.json",
"test/fixtures/event_get_success.json",
"test/fixtures/event_pages_success.json",
"test/fixtures/fundraising_donations_success.json",
"test/fixtures/fundraising_get_page_success.json",
"test/fixtures/fundraising_pages_success.json",
"test/fixtures/fundraising_update_story_success.json",
"test/fixtures/search_success.json",
"test/helper.rb",
"test/test_account.rb",
"test/test_charity.rb",
"test/test_configuration.rb",
"test/test_donation.rb",
"test/test_event.rb",
"test/test_fundraising.rb",
"test/test_search.rb",
"test/test_simple_donation_integration.rb"
]
s.homepage = %q{http://github.com/mintdigital/just_giving}
s.licenses = [%q{MIT}]
s.require_paths = [%q{lib}]
s.rubygems_version = %q{1.8.8}
s.summary = %q{A ruby wrapper for the justgiving.com API}
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<faraday>, [">= 0"])
s.add_runtime_dependency(%q<faraday_middleware>, [">= 0"])
s.add_runtime_dependency(%q<hashie>, [">= 0"])
s.add_runtime_dependency(%q<multi_json>, ["~> 1.0.1"])
s.add_runtime_dependency(%q<yajl-ruby>, [">= 0"])
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_development_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"])
s.add_development_dependency(%q<rcov>, [">= 0"])
s.add_development_dependency(%q<webmock>, [">= 0"])
else
s.add_dependency(%q<faraday>, [">= 0"])
s.add_dependency(%q<faraday_middleware>, [">= 0"])
s.add_dependency(%q<hashie>, [">= 0"])
s.add_dependency(%q<multi_json>, ["~> 1.0.1"])
s.add_dependency(%q<yajl-ruby>, [">= 0"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<webmock>, [">= 0"])
end
else
s.add_dependency(%q<faraday>, [">= 0"])
s.add_dependency(%q<faraday_middleware>, [">= 0"])
s.add_dependency(%q<hashie>, [">= 0"])
s.add_dependency(%q<multi_json>, [">= 1.0.1"])
s.add_dependency(%q<yajl-ruby>, [">= 0"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<webmock>, [">= 0"])
end
end
updated multijson
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{just_giving}
s.version = "0.2.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = [%q{Thomas Pomfret}]
s.date = %q{2011-08-23}
s.description = %q{A ruby wrapper for the justgiving.com API}
s.email = %q{thomas@mintdigital.com}
s.extra_rdoc_files = [
"LICENSE.txt",
"README.md"
]
s.files = [
".document",
"Gemfile",
"LICENSE.txt",
"README.md",
"Rakefile",
"just_giving.gemspec",
"lib/faraday/raise_http_4xx.rb",
"lib/faraday/raise_http_5xx.rb",
"lib/just_giving.rb",
"lib/just_giving/account.rb",
"lib/just_giving/api.rb",
"lib/just_giving/charity.rb",
"lib/just_giving/configuration.rb",
"lib/just_giving/connection.rb",
"lib/just_giving/donation.rb",
"lib/just_giving/error.rb",
"lib/just_giving/event.rb",
"lib/just_giving/fundraising.rb",
"lib/just_giving/railtie.rb",
"lib/just_giving/request.rb",
"lib/just_giving/response.rb",
"lib/just_giving/search.rb",
"lib/just_giving/simple_donation_integration.rb",
"lib/just_giving/version.rb",
"lib/just_giving/view_helpers.rb",
"test/fixtures/account_create_fail.json",
"test/fixtures/account_create_success.json",
"test/fixtures/account_list_all_pages.json",
"test/fixtures/charity_auth_success.json",
"test/fixtures/charity_get_success.json",
"test/fixtures/donation_status_success.json",
"test/fixtures/event_get_success.json",
"test/fixtures/event_pages_success.json",
"test/fixtures/fundraising_donations_success.json",
"test/fixtures/fundraising_get_page_success.json",
"test/fixtures/fundraising_pages_success.json",
"test/fixtures/fundraising_update_story_success.json",
"test/fixtures/search_success.json",
"test/helper.rb",
"test/test_account.rb",
"test/test_charity.rb",
"test/test_configuration.rb",
"test/test_donation.rb",
"test/test_event.rb",
"test/test_fundraising.rb",
"test/test_search.rb",
"test/test_simple_donation_integration.rb"
]
s.homepage = %q{http://github.com/mintdigital/just_giving}
s.licenses = [%q{MIT}]
s.require_paths = [%q{lib}]
s.rubygems_version = %q{1.8.8}
s.summary = %q{A ruby wrapper for the justgiving.com API}
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<faraday>, [">= 0"])
s.add_runtime_dependency(%q<faraday_middleware>, [">= 0"])
s.add_runtime_dependency(%q<hashie>, [">= 0"])
s.add_runtime_dependency(%q<multi_json>, [">= 1.0.1"])
s.add_runtime_dependency(%q<yajl-ruby>, [">= 0"])
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_development_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"])
s.add_development_dependency(%q<rcov>, [">= 0"])
s.add_development_dependency(%q<webmock>, [">= 0"])
else
s.add_dependency(%q<faraday>, [">= 0"])
s.add_dependency(%q<faraday_middleware>, [">= 0"])
s.add_dependency(%q<hashie>, [">= 0"])
s.add_dependency(%q<multi_json>, [">= 1.0.1"])
s.add_dependency(%q<yajl-ruby>, [">= 0"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<webmock>, [">= 0"])
end
else
s.add_dependency(%q<faraday>, [">= 0"])
s.add_dependency(%q<faraday_middleware>, [">= 0"])
s.add_dependency(%q<hashie>, [">= 0"])
s.add_dependency(%q<multi_json>, [">= 1.0.1"])
s.add_dependency(%q<yajl-ruby>, [">= 0"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<webmock>, [">= 0"])
end
end
|
require_relative './storer_test_base'
# storer.kata_start_avatar() relies on mkdir being
# atomic on a (non NFS) POSIX file system.
class HostDiskStorerPosixFsTest < StorerTestBase
def self.hex_prefix; '701B5'; end
test '4C0',
'start_avatar on multiple threads doesnt start the same avatar twice' do
20.times do |n|
kata_id = '4C012345' + (n+10).to_s
create_kata(kata_id)
started = []
size = 4
animals = all_avatar_names.shuffle[0...size]
threads = Array.new(size * 2)
names = []
threads.size.times { |i|
threads[i] = Thread.new {
name = storer.kata_start_avatar(kata_id, animals)
names << name unless name.nil?
}
}
threads.size.times { |i| threads[i].join }
assert_equal animals.sort, names.sort
assert_equal names.sort, storer.kata_started_avatars(kata_id).sort
end
end
# - - - - - - - - - - - - - - - - - - - - - - - - - - -
test 'A31',
'start_avatar on multiple processes doesnt start the same avatar twice' do
20.times do |n|
kata_id = 'A3112345' + (n+10).to_s
create_kata(kata_id)
started = []
size = 4
animals = all_avatar_names.shuffle[0...size]
pids = Array.new(size * 2)
read_pipe, write_pipe = IO.pipe
pids.size.times { |i|
pids[i] = Process.fork {
name = storer.kata_start_avatar(kata_id, animals)
write_pipe.puts "#{name} " unless name.nil?
}
}
pids.each { |pid| Process.wait(pid) }
write_pipe.close
names = read_pipe.read.split
read_pipe.close
assert_equal animals.sort, names.sort
assert_equal names.sort, storer.kata_started_avatars(kata_id).sort
end
end
private
def all_avatar_names
%w(alligator antelope bat bear bee beetle buffalo butterfly
cheetah crab deer dolphin eagle elephant flamingo fox
frog gopher gorilla heron hippo hummingbird hyena jellyfish
kangaroo kingfisher koala leopard lion lizard lobster moose
mouse ostrich owl panda parrot peacock penguin porcupine
puffin rabbit raccoon ray rhino salmon seal shark
skunk snake spider squid squirrel starfish swan tiger
toucan tuna turtle vulture walrus whale wolf zebra
)
end
def create_kata(id = kata_id)
manifest = {}
manifest['image_name'] = 'cyberdojofoundation/gcc_assert'
manifest['visible_files'] = starting_files
manifest['id'] = id
storer.create_kata(manifest)
manifest
end
def starting_files
{ 'cyber-dojo.sh' => 'gcc',
'hiker.c' => '#include "hiker.h"',
'hiker.h' => '#include <stdio.h>'
}
end
end
refactoring; removed duplication
require_relative 'storer_test_base'
require_relative '../../src/all_avatar_names'
# storer.kata_start_avatar() relies on mkdir being
# atomic on a (non NFS) POSIX file system.
class HostDiskStorerPosixFsTest < StorerTestBase
def self.hex_prefix; '701B5'; end
test '4C0',
'start_avatar on multiple threads doesnt start the same avatar twice' do
20.times do |n|
kata_id = '4C012345' + (n+10).to_s
create_kata(kata_id)
started = []
size = 4
animals = all_avatar_names.shuffle[0...size]
threads = Array.new(size * 2)
names = []
threads.size.times { |i|
threads[i] = Thread.new {
name = storer.kata_start_avatar(kata_id, animals)
names << name unless name.nil?
}
}
threads.size.times { |i| threads[i].join }
assert_equal animals.sort, names.sort
assert_equal names.sort, storer.kata_started_avatars(kata_id).sort
end
end
# - - - - - - - - - - - - - - - - - - - - - - - - - - -
test 'A31',
'start_avatar on multiple processes doesnt start the same avatar twice' do
20.times do |n|
kata_id = 'A3112345' + (n+10).to_s
create_kata(kata_id)
started = []
size = 4
animals = all_avatar_names.shuffle[0...size]
pids = Array.new(size * 2)
read_pipe, write_pipe = IO.pipe
pids.size.times { |i|
pids[i] = Process.fork {
name = storer.kata_start_avatar(kata_id, animals)
write_pipe.puts "#{name} " unless name.nil?
}
}
pids.each { |pid| Process.wait(pid) }
write_pipe.close
names = read_pipe.read.split
read_pipe.close
assert_equal animals.sort, names.sort
assert_equal names.sort, storer.kata_started_avatars(kata_id).sort
end
end
private
include AllAvatarNames
def create_kata(id = kata_id)
manifest = {}
manifest['image_name'] = 'cyberdojofoundation/gcc_assert'
manifest['visible_files'] = starting_files
manifest['id'] = id
storer.create_kata(manifest)
manifest
end
def starting_files
{ 'cyber-dojo.sh' => 'gcc',
'hiker.c' => '#include "hiker.h"',
'hiker.h' => '#include <stdio.h>'
}
end
end
|
require 'formula'
class Muxy < Formula
homepage "https://github.com/packer-community/packer-windows-plugins"
version "0.0.1"
if Hardware.is_64_bit?
url "https://github.com/mefellows/muxy/releases/download/v#{version}/darwin_amd64.zip"
sha256 'ba29e1b5c2666a91f37198ebef4397d497d262c3a4530eeed96d206824481634'
else
url "https://github.com/mefellows/muxy/releases/download/v#{version}/darwin_386.zip"
sha256 '9dad1e255359738c74d359b3e5e0580ad79f296b4cd6d7cfb350d5055b00fd87'
end
depends_on :arch => :intel
def install
bin.install Dir['*']
end
test do
end
end
chore(release): add latest SHASUMS to brew installer
require 'formula'
class Muxy < Formula
homepage "https://github.com/packer-community/packer-windows-plugins"
version "0.0.4"
if Hardware.is_64_bit?
url "https://github.com/mefellows/muxy/releases/download/v#{version}/darwin_amd64.zip"
sha256 '6d4aa05dfd0d94c98e93b6306bf660228e7254108c9f970e84932be8087d93b5'
else
url "https://github.com/mefellows/muxy/releases/download/v#{version}/darwin_386.zip"
sha256 '51c6b34846cb1a2913e36af9b4eefe29d71b1d5efe053a720a500ec2f52a0378'
end
depends_on :arch => :intel
def install
bin.install Dir['*']
end
test do
end
end
|
#
# Be sure to run `pod lib lint GPUImage.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'GPUImage'
s.version = '0.3.1'
s.summary = 'A short description of GPUImage.'
s.requires_arc = true
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.homepage = 'http://www.ushareit.com'
s.description = <<-DESC
TODO: Add long description of the pod here.
DESC
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'zhipengbird' => 'yuanph@ushareit.com' }
s.source = { :git => 'https://github.com/zhipengbird/GPUImage.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '7.0'
s.frameworks = ['OpenGLES', 'CoreMedia', 'QuartzCore', 'AVFoundation']
s.xcconfig = { 'CLANG_MODULES_AUTOLINK' => 'YES' }
s.default_subspec = 'GL'
s.subspec 'GL' do |cs|
cs.source_files = 'GPUImage/Classes/Core/GL/*.{m,h}'
cs.public_header_files = 'GPUImage/Classes/Core/GL/GLProgram.h'
end
s.subspec 'Basic' do |bs|
bs.dependency 'GPUImage/GL'
bs.public_header_files = 'GPUImage/Classes/Core/Basic/**/*.{h}'
bs.source_files = 'GPUImage/Classes/Core/Basic/**/*.{m,h}'
end
s.subspec 'Filter' do |bl|
bl.dependency 'GPUImage/Basic'
bl.public_header_files = 'GPUImage/Classes/Filter/{Core,Blends,Colors,Effects,Images}/*.{h}'
bl.source_files = 'GPUImage/Classes/Filter/{Core,Blends,Colors,Effects,Images}/*.{m,h}'
end
s.subspec 'CustomFilter' do |cf|
cf.dependency 'GPUImage/Filter'
cf.public_header_files ='GPUImage/Classes/CustomFilter/*.{h}'
cf.source_files =['GPUImage/Classes/CustomFilter/*.{m,h}']
cf.resource_bundles ={
'GPUImage' => ['GPUImage/Assets/**/*.png']
}
end
# s.subspec 'Color' do |co|
# co.dependency 'GPUImage/FilterCore'
# co.dependency 'GPUImage/Image'
#
# co.public_header_files = 'GPUImage/Classes/Filter/Colors/**/*.{h}'
# co.source_files = 'GPUImage/Classes/Filter/Colors/*.{m,h}'
# end
#
# s.subspec 'Effect' do |ef|
# ef.dependency 'GPUImage/FilterCore'
# ef.dependency 'GPUImage/Image'
#
# ef.public_header_files = 'GPUImage/Classes/Filter/Effects/**/*.{h}'
# ef.source_files = 'GPUImage/Classes/Filter/Effects/*.{m,h}'
# end
# s.subspec 'Image' do |im|
# im.dependency 'GPUImage/FilterCore'
## im.dependency 'GPUImage/Color'
## im.dependency 'GPUImage/Blends'
# im.public_header_files = 'GPUImage/Classes/Filter/Images/**/*.{h}'
# im.source_files = 'GPUImage/Classes/Filter/Images/*.{m,h}'
# end
s.resource_bundles = {
'GPUImage' => ['GPUImage/Assets/origin/*.png']
}
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
update version
#
# Be sure to run `pod lib lint GPUImage.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'GPUImage'
s.version = '0.4.0'
s.summary = 'A short description of GPUImage.'
s.requires_arc = true
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.homepage = 'http://www.ushareit.com'
s.description = <<-DESC
TODO: Add long description of the pod here.
DESC
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'zhipengbird' => 'yuanph@ushareit.com' }
s.source = { :git => 'https://github.com/zhipengbird/GPUImage.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '7.0'
s.frameworks = ['OpenGLES', 'CoreMedia', 'QuartzCore', 'AVFoundation']
s.xcconfig = { 'CLANG_MODULES_AUTOLINK' => 'YES' }
s.default_subspec = 'GL'
s.subspec 'GL' do |cs|
cs.source_files = 'GPUImage/Classes/Core/GL/*.{m,h}'
cs.public_header_files = 'GPUImage/Classes/Core/GL/GLProgram.h'
end
s.subspec 'Basic' do |bs|
bs.dependency 'GPUImage/GL'
bs.public_header_files = 'GPUImage/Classes/Core/Basic/**/*.{h}'
bs.source_files = 'GPUImage/Classes/Core/Basic/**/*.{m,h}'
end
s.subspec 'Filter' do |bl|
bl.dependency 'GPUImage/Basic'
bl.public_header_files = 'GPUImage/Classes/Filter/{Core,Blends,Colors,Effects,Images}/*.{h}'
bl.source_files = 'GPUImage/Classes/Filter/{Core,Blends,Colors,Effects,Images}/*.{m,h}'
end
s.subspec 'CustomFilter' do |cf|
cf.dependency 'GPUImage/Filter'
cf.public_header_files ='GPUImage/Classes/CustomFilter/*.{h}'
cf.source_files =['GPUImage/Classes/CustomFilter/*.{m,h}']
cf.resource_bundles ={
'GPUImage' => ['GPUImage/Assets/**/*.png']
}
end
# s.subspec 'Color' do |co|
# co.dependency 'GPUImage/FilterCore'
# co.dependency 'GPUImage/Image'
#
# co.public_header_files = 'GPUImage/Classes/Filter/Colors/**/*.{h}'
# co.source_files = 'GPUImage/Classes/Filter/Colors/*.{m,h}'
# end
#
# s.subspec 'Effect' do |ef|
# ef.dependency 'GPUImage/FilterCore'
# ef.dependency 'GPUImage/Image'
#
# ef.public_header_files = 'GPUImage/Classes/Filter/Effects/**/*.{h}'
# ef.source_files = 'GPUImage/Classes/Filter/Effects/*.{m,h}'
# end
# s.subspec 'Image' do |im|
# im.dependency 'GPUImage/FilterCore'
## im.dependency 'GPUImage/Color'
## im.dependency 'GPUImage/Blends'
# im.public_header_files = 'GPUImage/Classes/Filter/Images/**/*.{h}'
# im.source_files = 'GPUImage/Classes/Filter/Images/*.{m,h}'
# end
s.resource_bundles = {
'GPUImage' => ['GPUImage/Assets/origin/*.png']
}
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
|
Gem::Specification.new do |s|
s.name = 'lita-espn-fantasy-football'
s.version = '0.3.2'
s.authors = ['Kevin Reedy', 'Miles Evenson']
s.email = ['kevinreedy@gmail.com', 'miles.evenson@gmail.com']
s.description = 'Lita handler for ESPN Fantasy Football'
s.summary = <<-EOF
This Lita handler is used to scrape data from ESPN's Fantasy Football Site.
Right now, it is very limited, so PRs are very welcome!
EOF
s.homepage = 'https://github.com/kevinreedy/lita-espn-fantasy-football'
s.license = 'Apache-2.0'
s.metadata = { 'lita_plugin_type' => 'handler' }
s.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR)
s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) }
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.require_paths = ['lib']
s.add_runtime_dependency 'lita', '~> 4.7'
s.add_runtime_dependency 'nokogiri', '~> 1.8'
s.add_runtime_dependency 'terminal-table', '~> 1.8'
s.add_development_dependency 'bundler', '~> 1.14'
s.add_development_dependency 'pry-byebug', '~> 3.5'
s.add_development_dependency 'rake', '~> 12.0'
s.add_development_dependency 'rack-test', '~> 0.7'
s.add_development_dependency 'rspec', '~> 3.6'
s.add_development_dependency 'simplecov', '~> 0.9'
s.add_development_dependency 'coveralls', '~> 0.8'
s.add_development_dependency 'lita-console', '~> 0.0'
s.add_development_dependency 'rubocop', '~> 0.49'
end
version bump
Gem::Specification.new do |s|
s.name = 'lita-espn-fantasy-football'
s.version = '0.3.3'
s.authors = ['Kevin Reedy', 'Miles Evenson']
s.email = ['kevinreedy@gmail.com', 'miles.evenson@gmail.com']
s.description = 'Lita handler for ESPN Fantasy Football'
s.summary = <<-EOF
This Lita handler is used to scrape data from ESPN's Fantasy Football Site.
Right now, it is very limited, so PRs are very welcome!
EOF
s.homepage = 'https://github.com/kevinreedy/lita-espn-fantasy-football'
s.license = 'Apache-2.0'
s.metadata = { 'lita_plugin_type' => 'handler' }
s.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR)
s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) }
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.require_paths = ['lib']
s.add_runtime_dependency 'lita', '~> 4.7'
s.add_runtime_dependency 'nokogiri', '~> 1.8'
s.add_runtime_dependency 'terminal-table', '~> 1.8'
s.add_development_dependency 'bundler', '~> 1.14'
s.add_development_dependency 'pry-byebug', '~> 3.5'
s.add_development_dependency 'rake', '~> 12.0'
s.add_development_dependency 'rack-test', '~> 0.7'
s.add_development_dependency 'rspec', '~> 3.6'
s.add_development_dependency 'simplecov', '~> 0.9'
s.add_development_dependency 'coveralls', '~> 0.8'
s.add_development_dependency 'lita-console', '~> 0.0'
s.add_development_dependency 'rubocop', '~> 0.49'
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'active_record/connection_adapters/mysql2_adapter'
require_relative '../lib/gallery_lib'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
# :nodoc:
module JupyterGallery
# :nodoc:
class Application < Rails::Application
# Preload the Gallery configuration
Config::Integrations::Rails::Railtie.preload
# Load configuration from extensions.
# Extension config files override default settings files but
# are overridden by local settings files.
config_files = [
Rails.root.join('config', 'settings.yml').to_s,
Rails.root.join('config', 'settings', "#{Rails.env}.yml").to_s,
Rails.root.join('config', 'environments', "#{Rails.env}.yml").to_s
]
GalleryLib.extensions.each do |name, info|
next unless info[:config]
puts "Loading extension config: #{name}.yml" # rubocop: disable Rails/Output
config_files << info[:config].to_s
end
config_files += [
Rails.root.join('config', 'settings.local.yml').to_s,
Rails.root.join('config', 'settings', "#{Rails.env}.local.yml").to_s,
Rails.root.join('config', 'environments', "#{Rails.env}.local.yml").to_s
]
GalleryConfig.reload_from_files(*config_files)
# Some versions of MariaDB default to utf8mb4 encoding. That makes the
# max varchar that can be unique-indexed 190 instead of 255.
db_config = Rails.configuration.database_configuration[Rails.env]
conn = Mysql2::Client.new(db_config)
results = conn.query("show variables like 'character_set_server'", as: :array)
if results.first && results.first[1] == 'utf8mb4'
ActiveRecord::ConnectionAdapters::Mysql2Adapter::NATIVE_DATABASE_TYPES[:string][:limit] = 190
end
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.generators do |g|
g.template_engine :slim
end
config.middleware.insert_before 0, 'Rack::Cors' do
allow do
origins '*'
resource '/preferences', header: :any, methods: %i[post options]
resource '/environments', header: :any, methods: %i[post options patch get]
resource '/notebooks/*/metadata', headers: :any, methods: %i[get options]
resource '/notebooks/*/diff', headers: :any, methods: %i[post options patch get]
resource '/notebooks/*/download', headers: :any, methods: %i[get]
resource '/nb/*/uuid', headers: :any, methods: %i[get]
resource '/change_requests/*/download', headers: :any, methods: %i[get]
resource '/stages', headers: :any, methods: %i[post options]
resource '/integration/*', headers: :any, methods: %i[get]
resource '/executions', headers: :any, methods: %i[post]
end
GalleryConfig.dig(:extensions, :cors)&.each do |cors|
allow do
origins cors.origins
cors.resources.each do |r|
resource r.pattern, headers: r.headers.to_sym, methods: r.method_list.map(&:to_sym)
end
end
end
end
config.encoding = 'utf-8'
# Set up extension system
GalleryConfig.directories.extensions.each do |dir|
config.eager_load_paths += Dir[File.join(dir, '*')]
end
config.eager_load_paths << Rails.root.join('lib', 'extension_points')
end
end
Allow CORS for these
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'active_record/connection_adapters/mysql2_adapter'
require_relative '../lib/gallery_lib'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
# :nodoc:
module JupyterGallery
# :nodoc:
class Application < Rails::Application
# Preload the Gallery configuration
Config::Integrations::Rails::Railtie.preload
# Load configuration from extensions.
# Extension config files override default settings files but
# are overridden by local settings files.
config_files = [
Rails.root.join('config', 'settings.yml').to_s,
Rails.root.join('config', 'settings', "#{Rails.env}.yml").to_s,
Rails.root.join('config', 'environments', "#{Rails.env}.yml").to_s
]
GalleryLib.extensions.each do |name, info|
next unless info[:config]
puts "Loading extension config: #{name}.yml" # rubocop: disable Rails/Output
config_files << info[:config].to_s
end
config_files += [
Rails.root.join('config', 'settings.local.yml').to_s,
Rails.root.join('config', 'settings', "#{Rails.env}.local.yml").to_s,
Rails.root.join('config', 'environments', "#{Rails.env}.local.yml").to_s
]
GalleryConfig.reload_from_files(*config_files)
# Some versions of MariaDB default to utf8mb4 encoding. That makes the
# max varchar that can be unique-indexed 190 instead of 255.
db_config = Rails.configuration.database_configuration[Rails.env]
conn = Mysql2::Client.new(db_config)
results = conn.query("show variables like 'character_set_server'", as: :array)
if results.first && results.first[1] == 'utf8mb4'
ActiveRecord::ConnectionAdapters::Mysql2Adapter::NATIVE_DATABASE_TYPES[:string][:limit] = 190
end
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.generators do |g|
g.template_engine :slim
end
config.middleware.insert_before 0, 'Rack::Cors' do
allow do
origins '*'
resource '/preferences', header: :any, methods: %i[post options]
resource '/environments', header: :any, methods: %i[post options patch get]
resource '/notebooks/stars', headers: :any, methods: %i[get]
resource '/notebooks/recently_executed', headers: :any, methods: %i[get]
resource '/notebooks/*/metadata', headers: :any, methods: %i[get options]
resource '/notebooks/*/diff', headers: :any, methods: %i[post options patch get]
resource '/notebooks/*/download', headers: :any, methods: %i[get]
resource '/nb/*/uuid', headers: :any, methods: %i[get]
resource '/change_requests/*/download', headers: :any, methods: %i[get]
resource '/stages', headers: :any, methods: %i[post options]
resource '/integration/*', headers: :any, methods: %i[get]
resource '/executions', headers: :any, methods: %i[post]
end
GalleryConfig.dig(:extensions, :cors)&.each do |cors|
allow do
origins cors.origins
cors.resources.each do |r|
resource r.pattern, headers: r.headers.to_sym, methods: r.method_list.map(&:to_sym)
end
end
end
end
config.encoding = 'utf-8'
# Set up extension system
GalleryConfig.directories.extensions.each do |dir|
config.eager_load_paths += Dir[File.join(dir, '*')]
end
config.eager_load_paths << Rails.root.join('lib', 'extension_points')
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Course: Assessment: Submissions: Manually Graded Assessments' do
let(:instance) { Instance.default }
with_tenant(:instance) do
let(:course) { create(:course) }
let(:assessment) do
create(:assessment, :published_with_mrq_question, course: course)
end
let(:mrq_questions) { assessment.reload.questions.map(&:specific) }
before { login_as(user, scope: :user) }
let(:student) { create(:course_student, course: course).user }
let(:submission) { create(:submission, assessment: assessment, creator: student) }
let(:programming_assessment) do
create(:assessment, :published_with_programming_question, course: course)
end
let(:programming_assessment_submission) do
create(:submission, assessment: programming_assessment, creator: student)
end
let(:multiple_programming_assessment) do
# Creates a manually-graded assessment with 3 programming questions:
# 1. auto_gradable programming question (with test-cases)
# 2. auto_gradable programming question (only evaluation test-cases)
# 3. Non auto_gradable programming question (no test-cases)
assessment = create(:assessment, :published_with_programming_question, course: course)
create(:course_assessment_question_programming,
template_package: true, template_package_deferred: false, assessment: assessment,
evaluation_test_case_count: 1)
create(:course_assessment_question_programming,
template_package: true, template_package_deferred: false, assessment: assessment)
assessment.reload
end
let(:multiple_programming_submission) do
create(:submission, assessment: multiple_programming_assessment, creator: student)
end
context 'As a Course Student' do
let(:user) { student }
scenario 'I can save my submission' do
submission
visit edit_course_assessment_submission_path(course, assessment, submission)
option = assessment.questions.first.actable.options.first.option
check option
click_button I18n.t('course.assessment.submission.submissions.buttons.save')
expect(current_path).to eq(
edit_course_assessment_submission_path(course, assessment, submission)
)
expect(page).to have_checked_field(option)
end
scenario 'I can run code only on programming questions with private and public test cases' do
multiple_programming_submission
visit edit_course_assessment_submission_path(course, multiple_programming_assessment,
multiple_programming_submission)
# The Run Code button is only shown for the first question
expect(page).to have_selector('.btn.submit-answer', count: 1)
end
scenario 'I can reset my answer to a programming question', js: true do
assessment.tabbed_view = true
assessment.save!
programming_question = programming_assessment.questions.first
programming_answer = create(:course_assessment_answer_programming,
assessment: programming_assessment,
question: programming_question,
creator: student,
file_count: 1)
programming_submission = programming_answer.acting_as.submission
# Modify programming file content
file = programming_answer.files.first
file.content = 'foooo'
file.save
# Reset answer
visit edit_course_assessment_submission_path(course, programming_assessment,
programming_submission)
expect(page).to have_selector('.btn.reset-answer', count: 1)
page.accept_alert I18n.t('course.assessment.answer.reset_answer.warning') do
click_link I18n.t('course.assessment.answer.reset_answer.button')
end
wait_for_ajax
# Check that answer has been reset to template files
expect(programming_answer.reload.files.first.content).
to eq(programming_question.specific.template_files.first.content)
# Check that ACE Editor has initialised correctly
expect(page).to have_css('.ace_editor')
end
scenario 'I can finalise my submission only once' do
submission
visit edit_course_assessment_submission_path(course, assessment, submission)
click_button I18n.t('course.assessment.submission.submissions.buttons.finalise')
expect(current_path).to eq(
edit_course_assessment_submission_path(course, assessment, submission)
)
expect(submission.reload).to be_submitted
expect(page).
not_to have_button(I18n.t('course.assessment.submission.submissions.buttons.save'))
visit edit_course_assessment_submission_path(course, assessment, submission)
expect(page).
not_to have_button(I18n.t('course.assessment.submission.submissions.buttons.finalise'))
expect(page).not_to have_selector('div.submission_answers_grade')
end
scenario 'I can create, update and delete comment on answers', js: true do
assessment.questions.attempt(submission).each(&:save!)
visit edit_course_assessment_submission_path(course, assessment, submission)
comment_answer = submission.answers.first
comment_topic = comment_answer.discussion_topic
# Make a first comment
answer_selector = content_tag_selector(comment_answer)
comment_post_text = 'test comment'
fill_in_summernote answer_selector, comment_post_text
within find(answer_selector) do
find('.reply-comment').click
end
wait_for_ajax
comment_post = comment_topic.reload.posts.last
expect(comment_post.text).to have_tag('*', text: comment_post_text)
expect(comment_post.parent).to eq(nil)
expect(find(content_tag_selector(comment_answer))).
to have_selector('.answer-comment-form')
# Reply to the first comment
comment_reply_text = 'test reply'
fill_in_summernote answer_selector, comment_reply_text
within find(answer_selector) do
find('.reply-comment').click
end
wait_for_ajax
comment_reply = comment_topic.reload.posts.select { |post| post.id != comment_post.id }.last
expect(comment_reply.text).to have_tag('*', text: comment_reply_text)
expect(comment_reply.parent).to eq(comment_post)
expect(find(content_tag_selector(comment_answer))).
to have_selector('.answer-comment-form')
# Edit the last comment made
find(content_tag_selector(comment_reply)).find('.edit').click
updated_post_text = 'updated comment'
edit_form_selector = '.edit-discussion-post-form'
fill_in_summernote edit_form_selector, updated_post_text
within find(answer_selector).find('.edit-discussion-post-form') do
click_button I18n.t('javascript.course.discussion.post.submit')
end
wait_for_ajax
comment_reply = comment_reply.reload
expect(comment_reply.text).to have_tag('*', text: updated_post_text)
# Delete the reply
within find(content_tag_selector(comment_reply)) do
find('.delete').click
end
wait_for_ajax
expect(page).not_to have_content_tag_for(comment_reply)
expect(comment_topic.reload.posts.count).to eq(1)
# Should still be able to reply when last comment is deleted
comment_reply_text = 'another reply'
fill_in_summernote answer_selector, comment_reply_text
within find(answer_selector) do
find('.reply-comment').click
end
wait_for_ajax
expect(comment_topic.reload.posts.count).to eq(2)
end
end
context 'As a Course Staff' do
let(:user) { create(:course_teaching_assistant, course: course).user }
scenario "I can grade the student's work" do
mrq_questions.each { |q| q.attempt(submission).save! }
submission.finalise!
submission.save!
# Check that there is NO late submission warning.
late_submission_text = I18n.t('course.assessment.submission.submissions.progress.'\
'late_submission_warning')
visit edit_course_assessment_submission_path(course, assessment, submission)
# Submission progress panel
expect(page).not_to have_selector('div.alert.alert-danger', text: late_submission_text)
# Statistics panel
expect(page).not_to have_selector('td.text-danger')
# Create a late submission
assessment.end_at = Time.zone.now - 1.day
assessment.save!
# Refresh and check for the late submission warning.
visit edit_course_assessment_submission_path(course, assessment, submission)
# Submission progress panel
expect(page).to have_selector('div.alert.alert-danger', text: late_submission_text)
# Statistics panel
expect(page).to have_selector('td.text-danger')
# Create an extra question after submission is submitted, user should still be able to
# grade the submission in this case.
create(:course_assessment_question_multiple_response, assessment: assessment)
visit edit_course_assessment_submission_path(course, assessment, submission)
no_answer_text = I18n.t('course.assessment.submission.submissions.no_answer')
expect(page).to have_selector('div.alert', text: no_answer_text)
expect(page).to have_button(I18n.t('course.assessment.submission.submissions.buttons.save'))
click_link I18n.t('course.assessment.submission.submissions.buttons.evaluate_answers')
wait_for_job
# Publish the submission with empty answer grade
click_button I18n.t('course.assessment.submission.submissions.buttons.publish')
expect(page).to have_selector('div.alert-danger')
expect(page).
to have_button(I18n.t('course.assessment.submission.submissions.buttons.publish'))
fill_in find('input.form-control.grade')[:name], with: 0
click_button I18n.t('course.assessment.submission.submissions.buttons.publish')
expect(current_path).
to eq(edit_course_assessment_submission_path(course, assessment, submission))
expect(submission.reload.published?).to be(true)
end
scenario 'I can run code on autograded programming questions' do
multiple_programming_submission
visit edit_course_assessment_submission_path(course, multiple_programming_assessment,
multiple_programming_submission)
# The Run Code button is only shown for the auto_gradable? questions
expect(page).to have_selector('.btn.submit-answer', count: 2)
end
end
end
end
Add test to check that grades are updated from javascript logic
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Course: Assessment: Submissions: Manually Graded Assessments' do
let(:instance) { Instance.default }
with_tenant(:instance) do
let(:course) { create(:course) }
let(:assessment) do
create(:assessment, :published_with_mrq_question, course: course)
end
let(:mrq_questions) { assessment.reload.questions.map(&:specific) }
before { login_as(user, scope: :user) }
let(:student) { create(:course_student, course: course).user }
let(:submission) { create(:submission, assessment: assessment, creator: student) }
let(:programming_assessment) do
create(:assessment, :published_with_programming_question, course: course)
end
let(:programming_assessment_submission) do
create(:submission, assessment: programming_assessment, creator: student)
end
let(:multiple_programming_assessment) do
# Creates a manually-graded assessment with 3 programming questions:
# 1. auto_gradable programming question (with test-cases)
# 2. auto_gradable programming question (only evaluation test-cases)
# 3. Non auto_gradable programming question (no test-cases)
assessment = create(:assessment, :published_with_programming_question, course: course)
create(:course_assessment_question_programming,
template_package: true, template_package_deferred: false, assessment: assessment,
evaluation_test_case_count: 1)
create(:course_assessment_question_programming,
template_package: true, template_package_deferred: false, assessment: assessment)
assessment.reload
end
let(:multiple_programming_submission) do
create(:submission, assessment: multiple_programming_assessment, creator: student)
end
context 'As a Course Student' do
let(:user) { student }
scenario 'I can save my submission' do
submission
visit edit_course_assessment_submission_path(course, assessment, submission)
option = assessment.questions.first.actable.options.first.option
check option
click_button I18n.t('course.assessment.submission.submissions.buttons.save')
expect(current_path).to eq(
edit_course_assessment_submission_path(course, assessment, submission)
)
expect(page).to have_checked_field(option)
end
scenario 'I can run code only on programming questions with private and public test cases' do
multiple_programming_submission
visit edit_course_assessment_submission_path(course, multiple_programming_assessment,
multiple_programming_submission)
# The Run Code button is only shown for the first question
expect(page).to have_selector('.btn.submit-answer', count: 1)
end
scenario 'I can reset my answer to a programming question', js: true do
assessment.tabbed_view = true
assessment.save!
programming_question = programming_assessment.questions.first
programming_answer = create(:course_assessment_answer_programming,
assessment: programming_assessment,
question: programming_question,
creator: student,
file_count: 1)
programming_submission = programming_answer.acting_as.submission
# Modify programming file content
file = programming_answer.files.first
file.content = 'foooo'
file.save
# Reset answer
visit edit_course_assessment_submission_path(course, programming_assessment,
programming_submission)
expect(page).to have_selector('.btn.reset-answer', count: 1)
page.accept_alert I18n.t('course.assessment.answer.reset_answer.warning') do
click_link I18n.t('course.assessment.answer.reset_answer.button')
end
wait_for_ajax
# Check that answer has been reset to template files
expect(programming_answer.reload.files.first.content).
to eq(programming_question.specific.template_files.first.content)
# Check that ACE Editor has initialised correctly
expect(page).to have_css('.ace_editor')
end
scenario 'I can finalise my submission only once' do
submission
visit edit_course_assessment_submission_path(course, assessment, submission)
click_button I18n.t('course.assessment.submission.submissions.buttons.finalise')
expect(current_path).to eq(
edit_course_assessment_submission_path(course, assessment, submission)
)
expect(submission.reload).to be_submitted
expect(page).
not_to have_button(I18n.t('course.assessment.submission.submissions.buttons.save'))
visit edit_course_assessment_submission_path(course, assessment, submission)
expect(page).
not_to have_button(I18n.t('course.assessment.submission.submissions.buttons.finalise'))
expect(page).not_to have_selector('div.submission_answers_grade')
end
scenario 'I can create, update and delete comment on answers', js: true do
assessment.questions.attempt(submission).each(&:save!)
visit edit_course_assessment_submission_path(course, assessment, submission)
comment_answer = submission.answers.first
comment_topic = comment_answer.discussion_topic
# Make a first comment
answer_selector = content_tag_selector(comment_answer)
comment_post_text = 'test comment'
fill_in_summernote answer_selector, comment_post_text
within find(answer_selector) do
find('.reply-comment').click
end
wait_for_ajax
comment_post = comment_topic.reload.posts.last
expect(comment_post.text).to have_tag('*', text: comment_post_text)
expect(comment_post.parent).to eq(nil)
expect(find(content_tag_selector(comment_answer))).
to have_selector('.answer-comment-form')
# Reply to the first comment
comment_reply_text = 'test reply'
fill_in_summernote answer_selector, comment_reply_text
within find(answer_selector) do
find('.reply-comment').click
end
wait_for_ajax
comment_reply = comment_topic.reload.posts.select { |post| post.id != comment_post.id }.last
expect(comment_reply.text).to have_tag('*', text: comment_reply_text)
expect(comment_reply.parent).to eq(comment_post)
expect(find(content_tag_selector(comment_answer))).
to have_selector('.answer-comment-form')
# Edit the last comment made
find(content_tag_selector(comment_reply)).find('.edit').click
updated_post_text = 'updated comment'
edit_form_selector = '.edit-discussion-post-form'
fill_in_summernote edit_form_selector, updated_post_text
within find(answer_selector).find('.edit-discussion-post-form') do
click_button I18n.t('javascript.course.discussion.post.submit')
end
wait_for_ajax
comment_reply = comment_reply.reload
expect(comment_reply.text).to have_tag('*', text: updated_post_text)
# Delete the reply
within find(content_tag_selector(comment_reply)) do
find('.delete').click
end
wait_for_ajax
expect(page).not_to have_content_tag_for(comment_reply)
expect(comment_topic.reload.posts.count).to eq(1)
# Should still be able to reply when last comment is deleted
comment_reply_text = 'another reply'
fill_in_summernote answer_selector, comment_reply_text
within find(answer_selector) do
find('.reply-comment').click
end
wait_for_ajax
expect(comment_topic.reload.posts.count).to eq(2)
end
end
context 'As a Course Staff' do
let(:user) { create(:course_teaching_assistant, course: course).user }
scenario "I can grade the student's work", js: true do
mrq_questions.each { |q| q.attempt(submission).save! }
submission.finalise!
submission.save!
# Check that there is NO late submission warning.
late_submission_text = I18n.t('course.assessment.submission.submissions.progress.'\
'late_submission_warning')
visit edit_course_assessment_submission_path(course, assessment, submission)
# Submission progress panel
expect(page).not_to have_selector('div.alert.alert-danger', text: late_submission_text)
# Statistics panel
expect(page).not_to have_selector('td.text-danger')
# Create a late submission
assessment.end_at = Time.zone.now - 1.day
assessment.save!
# Refresh and check for the late submission warning.
visit edit_course_assessment_submission_path(course, assessment, submission)
# Submission progress panel
expect(page).to have_selector('div.alert.alert-danger', text: late_submission_text)
# Statistics panel
expect(page).to have_selector('td.text-danger')
# Create an extra question after submission is submitted, user should still be able to
# grade the submission in this case.
create(:course_assessment_question_multiple_response, assessment: assessment)
visit edit_course_assessment_submission_path(course, assessment, submission)
no_answer_text = I18n.t('course.assessment.submission.submissions.no_answer')
expect(page).to have_selector('div.alert', text: no_answer_text)
expect(page).to have_button(I18n.t('course.assessment.submission.submissions.buttons.save'))
click_link I18n.t('course.assessment.submission.submissions.buttons.evaluate_answers')
wait_for_job
# Publish the submission with empty answer grade
click_button I18n.t('course.assessment.submission.submissions.buttons.publish')
expect(page).to have_selector('div.alert-danger')
expect(page).
to have_button(I18n.t('course.assessment.submission.submissions.buttons.publish'))
fill_in find('input.form-control.grade')[:name], with: 0
click_button I18n.t('course.assessment.submission.submissions.buttons.publish')
expect(current_path).
to eq(edit_course_assessment_submission_path(course, assessment, submission))
expect(submission.reload.published?).to be(true)
# Update grade and check if grade fields are updated
fill_in find('input.form-control.grade')[:name], with: 1
expect(page.all('.submission-statistics-total-grade', text: '1').count).to eq(2)
end
scenario 'I can run code on autograded programming questions' do
multiple_programming_submission
visit edit_course_assessment_submission_path(course, multiple_programming_assessment,
multiple_programming_submission)
# The Run Code button is only shown for the auto_gradable? questions
expect(page).to have_selector('.btn.submit-answer', count: 2)
end
end
end
end
|
require File.expand_path('../boot', __FILE__)
# require 'rails/all'
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"
require "sprockets/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
# Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
Bundler.require(:default, :assets, Rails.env)
end
module Microsites2
class Application < Rails::Application
# Paperclip::Railtie.insert
#
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W( #{Rails.root}/app/sweepers )
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [ :password, :password_confirmation, :password_confirm ]
config.assets.paths << Rails.root.join("app", "assets", "flash")
config.assets.precompile += [ 'cities.css', 'manager.css', 'organizer.css', 'print.css', 'resume.css', 'm.css', 'spec_runner.css' ]
config.assets.precompile += [ 'm.js', 'spec_runner.js', 'manager.js' ]
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
# config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
precompiling assets rails.js
require File.expand_path('../boot', __FILE__)
# require 'rails/all'
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"
require "sprockets/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
# Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
Bundler.require(:default, :assets, Rails.env)
end
module Microsites2
class Application < Rails::Application
# Paperclip::Railtie.insert
#
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W( #{Rails.root}/app/sweepers )
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [ :password, :password_confirmation, :password_confirm ]
config.assets.paths << Rails.root.join("app", "assets", "flash")
config.assets.precompile += [ 'cities.css', 'manager.css', 'organizer.css', 'print.css', 'resume.css', 'm.css', 'spec_runner.css' ]
config.assets.precompile += [ 'm.js', 'spec_runner.js', 'manager.js', 'rails.js' ]
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
# config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
|
Extract common VCR spec asserts
Extract common VCR spec asserts
module AwsRefresherSpecCommon
def assert_common
assert_table_counts
assert_ems
assert_specific_flavor
assert_specific_az
assert_specific_floating_ip
assert_specific_floating_ip_for_cloud_network
assert_specific_key_pair
assert_specific_cloud_network
assert_specific_security_group
assert_specific_security_group_on_cloud_network
assert_specific_template
assert_specific_shared_template
assert_specific_vm_powered_on
assert_specific_vm_powered_off
assert_specific_vm_on_cloud_network
assert_specific_vm_on_cloud_network_public_ip
assert_specific_vm_in_other_region
assert_specific_load_balancers
assert_specific_load_balancer_listeners
assert_specific_load_balancer_health_checks
assert_specific_orchestration_template
assert_specific_orchestration_stack
assert_relationship_tree
end
def expected_table_counts
{
:auth_private_key => 12,
:availability_zone => 5,
:cloud_network => 5,
:cloud_subnet => 10,
:custom_attribute => 0,
:disk => 15,
:ext_management_system => 2,
:firewall_rule => 100,
:flavor => 56,
:floating_ip => 17,
:guest_device => 0,
:hardware => 56,
:miq_queue => 59,
:miq_template => 20,
:network => 28,
:network_port => 42,
:network_router => 0,
:operating_system => 0,
:orchestration_stack => 6,
:orchestration_stack_output => 1,
:orchestration_stack_parameter => 15,
:orchestration_stack_resource => 50,
:orchestration_template => 5,
:relationship => 38,
:security_group => 38,
:snapshot => 0,
:system_service => 0,
:vm => 36,
:vm_or_template => 56
}
end
def assert_table_counts
actual = {
:auth_private_key => AuthPrivateKey.count,
:ext_management_system => ExtManagementSystem.count,
:flavor => Flavor.count,
:availability_zone => AvailabilityZone.count,
:vm_or_template => VmOrTemplate.count,
:vm => Vm.count,
:miq_template => MiqTemplate.count,
:disk => Disk.count,
:guest_device => GuestDevice.count,
:hardware => Hardware.count,
:network => Network.count,
:operating_system => OperatingSystem.count,
:snapshot => Snapshot.count,
:system_service => SystemService.count,
:relationship => Relationship.count,
:miq_queue => MiqQueue.count,
:orchestration_template => OrchestrationTemplate.count,
:orchestration_stack => OrchestrationStack.count,
:orchestration_stack_parameter => OrchestrationStackParameter.count,
:orchestration_stack_output => OrchestrationStackOutput.count,
:orchestration_stack_resource => OrchestrationStackResource.count,
:security_group => SecurityGroup.count,
:firewall_rule => FirewallRule.count,
:network_port => NetworkPort.count,
:cloud_network => CloudNetwork.count,
:floating_ip => FloatingIp.count,
:network_router => NetworkRouter.count,
:cloud_subnet => CloudSubnet.count,
:custom_attribute => CustomAttribute.count
}
expect(actual).to eq expected_table_counts
end
def assert_ems
expect(@ems).to have_attributes(
:api_version => nil, # TODO: Should be 3.0
:uid_ems => nil
)
expect(@ems.flavors.size).to eql(expected_table_counts[:flavor])
expect(@ems.availability_zones.size).to eql(expected_table_counts[:availability_zone])
expect(@ems.vms_and_templates.size).to eql(expected_table_counts[:vm_or_template])
expect(@ems.security_groups.size).to eql(expected_table_counts[:security_group])
expect(@ems.network_ports.size).to eql(expected_table_counts[:network_port])
expect(@ems.cloud_networks.size).to eql(expected_table_counts[:cloud_network])
expect(@ems.floating_ips.size).to eql(expected_table_counts[:floating_ip])
expect(@ems.network_routers.size).to eql(expected_table_counts[:network_router])
expect(@ems.cloud_subnets.size).to eql(expected_table_counts[:cloud_subnet])
expect(@ems.miq_templates.size).to eq(expected_table_counts[:miq_template])
expect(@ems.orchestration_stacks.size).to eql(expected_table_counts[:orchestration_stack])
expect(@ems.direct_orchestration_stacks.size).to eql(4)
end
def assert_specific_flavor
@flavor = ManageIQ::Providers::Amazon::CloudManager::Flavor.where(:name => "t1.micro").first
expect(@flavor).to have_attributes(
:name => "t1.micro",
:description => "T1 Micro",
:enabled => true,
:cpus => 1,
:cpu_cores => 1,
:memory => 0.613.gigabytes.to_i,
:supports_32_bit => true,
:supports_64_bit => true,
:supports_hvm => false,
:supports_paravirtual => true,
:block_storage_based_only => true,
:ephemeral_disk_size => 0,
:ephemeral_disk_count => 0
)
expect(@flavor.ext_management_system).to eq(@ems)
end
def assert_specific_az
@az = ManageIQ::Providers::Amazon::CloudManager::AvailabilityZone.where(:name => "us-east-1e").first
expect(@az).to have_attributes(
:name => "us-east-1e",
)
end
def assert_specific_floating_ip
@ip = ManageIQ::Providers::Amazon::NetworkManager::FloatingIp.where(:address => "54.221.202.53").first
expect(@ip).to have_attributes(
:address => "54.221.202.53",
:fixed_ip_address => "10.170.73.43",
:ems_ref => "54.221.202.53",
:cloud_network_only => false
)
end
def assert_specific_floating_ip_for_cloud_network
@ip1 = ManageIQ::Providers::Amazon::NetworkManager::FloatingIp.where(:address => "54.208.119.197").first
expect(@ip1).to have_attributes(
:address => "54.208.119.197",
:fixed_ip_address => "10.0.0.254",
:ems_ref => "eipalloc-ce53d7a0",
:cloud_network_only => true
)
@ip2 = ManageIQ::Providers::Amazon::NetworkManager::FloatingIp.where(:address => "52.207.210.230").first
expect(@ip2).to have_attributes(
:address => "52.207.210.230",
:fixed_ip_address => "10.0.0.122",
:ems_ref => "52.207.210.230",
:cloud_network_only => true
)
end
def assert_specific_key_pair
@kp = ManageIQ::Providers::Amazon::CloudManager::AuthKeyPair.where(:name => "EmsRefreshSpec-KeyPair").first
expect(@kp).to have_attributes(
:name => "EmsRefreshSpec-KeyPair",
:fingerprint => "49:9f:3f:a4:26:48:39:94:26:06:dd:25:73:e5:da:9b:4b:1b:6c:93"
)
end
def assert_specific_cloud_network
@cn = CloudNetwork.where(:name => "EmsRefreshSpec-VPC").first
expect(@cn).to have_attributes(
:name => "EmsRefreshSpec-VPC",
:ems_ref => "vpc-ff49ff91",
:cidr => "10.0.0.0/16",
:status => "inactive",
:enabled => true
)
expect(@cn.cloud_subnets.size).to eq(2)
@subnet = @cn.cloud_subnets.where(:name => "EmsRefreshSpec-Subnet1").first
expect(@subnet).to have_attributes(
:name => "EmsRefreshSpec-Subnet1",
:ems_ref => "subnet-f849ff96",
:cidr => "10.0.0.0/24"
)
expect(@subnet.availability_zone)
.to eq(ManageIQ::Providers::Amazon::CloudManager::AvailabilityZone.where(:name => "us-east-1e").first)
subnet2 = @cn.cloud_subnets.where(:name => "EmsRefreshSpec-Subnet2").first
expect(subnet2).to have_attributes(
:name => "EmsRefreshSpec-Subnet2",
:ems_ref => "subnet-16c70477",
:cidr => "10.0.1.0/24"
)
expect(subnet2.availability_zone)
.to eq(ManageIQ::Providers::Amazon::CloudManager::AvailabilityZone.where(:name => "us-east-1d").first)
end
def assert_specific_security_group
@sg = ManageIQ::Providers::Amazon::NetworkManager::SecurityGroup.where(:name => "EmsRefreshSpec-SecurityGroup1").first
expect(@sg).to have_attributes(
:name => "EmsRefreshSpec-SecurityGroup1",
:description => "EmsRefreshSpec-SecurityGroup1",
:ems_ref => "sg-038e8a69"
)
expected_firewall_rules = [
{:host_protocol => "ICMP", :direction => "inbound", :port => -1, :end_port => -1, :source_ip_range => "0.0.0.0/0", :source_security_group_id => nil},
{:host_protocol => "ICMP", :direction => "inbound", :port => -1, :end_port => -1, :source_ip_range => nil, :source_security_group_id => @sg.id},
{:host_protocol => "ICMP", :direction => "inbound", :port => 0, :end_port => -1, :source_ip_range => "1.2.3.4/30", :source_security_group_id => nil},
{:host_protocol => "TCP", :direction => "inbound", :port => 0, :end_port => 65535, :source_ip_range => "0.0.0.0/0", :source_security_group_id => nil},
{:host_protocol => "TCP", :direction => "inbound", :port => 1, :end_port => 2, :source_ip_range => "1.2.3.4/30", :source_security_group_id => nil},
{:host_protocol => "TCP", :direction => "inbound", :port => 3, :end_port => 4, :source_ip_range => nil, :source_security_group_id => @sg.id},
{:host_protocol => "TCP", :direction => "inbound", :port => 80, :end_port => 80, :source_ip_range => "0.0.0.0/0", :source_security_group_id => nil},
{:host_protocol => "TCP", :direction => "inbound", :port => 80, :end_port => 80, :source_ip_range => "1.2.3.4/30", :source_security_group_id => nil},
{:host_protocol => "TCP", :direction => "inbound", :port => 80, :end_port => 80, :source_ip_range => nil, :source_security_group_id => @sg.id},
{:host_protocol => "UDP", :direction => "inbound", :port => 0, :end_port => 65535, :source_ip_range => "0.0.0.0/0", :source_security_group_id => nil},
{:host_protocol => "UDP", :direction => "inbound", :port => 1, :end_port => 2, :source_ip_range => "1.2.3.4/30", :source_security_group_id => nil},
{:host_protocol => "UDP", :direction => "inbound", :port => 3, :end_port => 4, :source_ip_range => nil, :source_security_group_id => @sg.id}
]
expect(@sg.firewall_rules.size).to eq(12)
@sg.firewall_rules
.order(:host_protocol, :direction, :port, :end_port, :source_ip_range, :source_security_group_id)
.zip(expected_firewall_rules)
.each do |actual, expected|
expect(actual).to have_attributes(expected)
end
end
def assert_specific_security_group_on_cloud_network
@sg_on_cn = ManageIQ::Providers::Amazon::NetworkManager::SecurityGroup.where(:name => "EmsRefreshSpec-SecurityGroup-VPC").first
expect(@sg_on_cn).to have_attributes(
:name => "EmsRefreshSpec-SecurityGroup-VPC",
:description => "EmsRefreshSpec-SecurityGroup-VPC",
:ems_ref => "sg-80f755ef"
)
expect(@sg_on_cn.cloud_network).to eq(@cn)
end
def assert_specific_template
@template = ManageIQ::Providers::Amazon::CloudManager::Template.where(:name => "EmsRefreshSpec-Image").first
expect(@template).to have_attributes(
:template => true,
:ems_ref => "ami-5769193e",
:ems_ref_obj => nil,
:uid_ems => "ami-5769193e",
:vendor => "amazon",
:power_state => "never",
:location => "200278856672/EmsRefreshSpec-Image",
:tools_status => nil,
:boot_time => nil,
:standby_action => nil,
:connection_state => nil,
:cpu_affinity => nil,
:memory_reserve => nil,
:memory_reserve_expand => nil,
:memory_limit => nil,
:memory_shares => nil,
:memory_shares_level => nil,
:cpu_reserve => nil,
:cpu_reserve_expand => nil,
:cpu_limit => nil,
:cpu_shares => nil,
:cpu_shares_level => nil
)
expect(@template.ext_management_system).to eq(@ems)
expect(@template.operating_system).to be_nil # TODO: This should probably not be nil
expect(@template.custom_attributes.size).to eq(0)
expect(@template.snapshots.size).to eq(0)
expect(@template.hardware).to have_attributes(
:guest_os => "linux",
:guest_os_full_name => nil,
:bios => nil,
:annotation => nil,
:cpu_sockets => 1, # wtf
:memory_mb => nil,
:disk_capacity => nil,
:bitness => 64,
:virtualization_type => "paravirtual",
:root_device_type => "ebs"
)
expect(@template.hardware.disks.size).to eq(0)
expect(@template.hardware.guest_devices.size).to eq(0)
expect(@template.hardware.nics.size).to eq(0)
expect(@template.hardware.networks.size).to eq(0)
end
def assert_specific_shared_template
# TODO: Share an EmsRefreshSpec specific template
t = ManageIQ::Providers::Amazon::CloudManager::Template.where(:ems_ref => "ami-5769193e").first
expect(t).not_to be_nil
end
def assert_specific_vm_powered_on
v = ManageIQ::Providers::Amazon::CloudManager::Vm.where(
:name => "EmsRefreshSpec-PoweredOn-Basic3",
:raw_power_state => "running").first
expect(v).to have_attributes(
:template => false,
:ems_ref => "i-680071e9",
:ems_ref_obj => nil,
:uid_ems => "i-680071e9",
:vendor => "amazon",
:power_state => "on",
:location => "ec2-54-221-202-53.compute-1.amazonaws.com",
:tools_status => nil,
:boot_time => "2016-08-30 06:20:24.000000000 +0000",
:standby_action => nil,
:connection_state => nil,
:cpu_affinity => nil,
:memory_reserve => nil,
:memory_reserve_expand => nil,
:memory_limit => nil,
:memory_shares => nil,
:memory_shares_level => nil,
:cpu_reserve => nil,
:cpu_reserve_expand => nil,
:cpu_limit => nil,
:cpu_shares => nil,
:cpu_shares_level => nil
)
expect(v.ext_management_system).to eq(@ems)
expect(v.availability_zone).to eq(@az)
expect(v.floating_ip).to eq(@ip)
expect(v.network_ports.first.floating_ips.count).to eq(1)
expect(v.network_ports.first.floating_ips).to eq([@ip])
expect(v.network_ports.first.floating_ip_addresses).to eq([@ip.address])
expect(v.network_ports.first.fixed_ip_addresses).to eq([@ip.fixed_ip_address])
expect(v.network_ports.first.ipaddresses).to eq([@ip.fixed_ip_address, @ip.address])
expect(v.ipaddresses).to eq([@ip.fixed_ip_address, @ip.address])
expect(v.flavor).to eq(@flavor)
expect(v.key_pairs).to eq([@kp])
expect(v.cloud_network).to be_nil
expect(v.cloud_subnet).to be_nil
sg_2 = ManageIQ::Providers::Amazon::NetworkManager::SecurityGroup
.where(:name => "EmsRefreshSpec-SecurityGroup2").first
expect(v.security_groups)
.to match_array [sg_2, @sg]
expect(v.operating_system).to be_nil # TODO: This should probably not be nil
expect(v.custom_attributes.size).to eq(0)
expect(v.snapshots.size).to eq(0)
expect(v.hardware).to have_attributes(
:guest_os => "linux",
:guest_os_full_name => nil,
:bios => nil,
:annotation => nil,
:cpu_sockets => 1,
:memory_mb => 627,
:disk_capacity => 0, # TODO: Change to a flavor that has disks
:bitness => 64,
:virtualization_type => "paravirtual"
)
expect(v.hardware.disks.size).to eq(0) # TODO: Change to a flavor that has disks
expect(v.hardware.guest_devices.size).to eq(0)
expect(v.hardware.nics.size).to eq(0)
expect(v.hardware.networks.size).to eq(2)
network = v.hardware.networks.where(:description => "public").first
expect(network).to have_attributes(
:description => "public",
:ipaddress => @ip.address,
:hostname => "ec2-54-221-202-53.compute-1.amazonaws.com"
)
network = v.hardware.networks.where(:description => "private").first
expect(network).to have_attributes(
:description => "private",
:ipaddress => "10.170.73.43",
:hostname => "ip-10-170-73-43.ec2.internal"
)
expect(v.load_balancers.collect(&:name)).to match_array ["EmsRefreshSpec-LoadBalancer"]
expect(v.load_balancer_health_checks.collect(&:ems_ref)).to match_array ["EmsRefreshSpec-LoadBalancer"]
expect(v.load_balancer_listeners.collect(&:ems_ref)).to match_array ["EmsRefreshSpec-LoadBalancer__HTTP__80__HTTP__80__"]
expect(v.load_balancer_health_check_states).to match_array ["OutOfService"]
healt_check_states_with_reason = [
"Status: OutOfService, Status Reason: Instance has failed at least the UnhealthyThreshold number of health checks consecutively."
]
expect(v.load_balancer_health_check_states_with_reason).to match_array healt_check_states_with_reason
v.with_relationship_type("genealogy") do
expect(v.parent).to eq(@template)
end
end
def assert_specific_vm_powered_off
v = ManageIQ::Providers::Amazon::CloudManager::Vm.where(
:name => "EmsRefreshSpec-PoweredOff",
:raw_power_state => "stopped").first
expect(v).to have_attributes(
:template => false,
:ems_ref => "i-6eeb97ef",
:ems_ref_obj => nil,
:uid_ems => "i-6eeb97ef",
:vendor => "amazon",
:power_state => "off",
:location => "unknown",
:tools_status => nil,
:boot_time => "2016-01-08T15:09:18.000",
:standby_action => nil,
:connection_state => nil,
:cpu_affinity => nil,
:memory_reserve => nil,
:memory_reserve_expand => nil,
:memory_limit => nil,
:memory_shares => nil,
:memory_shares_level => nil,
:cpu_reserve => nil,
:cpu_reserve_expand => nil,
:cpu_limit => nil,
:cpu_shares => nil,
:cpu_shares_level => nil
)
expect(v.ext_management_system).to eq(@ems)
expect(v.availability_zone)
.to eq(ManageIQ::Providers::Amazon::CloudManager::AvailabilityZone.find_by_name("us-east-1e"))
expect(v.floating_ip).to be_nil
expect(v.key_pairs).to eq([@kp])
expect(v.cloud_network).to be_nil
expect(v.cloud_subnet).to be_nil
expect(v.security_groups).to eq([@sg])
expect(v.operating_system).to be_nil # TODO: This should probably not be nil
expect(v.custom_attributes.size).to eq(0)
expect(v.snapshots.size).to eq(0)
expect(v.hardware).to have_attributes(
:config_version => nil,
:virtual_hw_version => nil,
:guest_os => "linux",
:cpu_sockets => 1,
:bios => nil,
:bios_location => nil,
:time_sync => nil,
:annotation => nil,
:memory_mb => 627,
:host_id => nil,
:cpu_speed => nil,
:cpu_type => nil,
:size_on_disk => nil,
:manufacturer => "",
:model => "",
:number_of_nics => nil,
:cpu_usage => nil,
:memory_usage => nil,
:cpu_cores_per_socket => 1,
:cpu_total_cores => 1,
:vmotion_enabled => nil,
:disk_free_space => nil,
:disk_capacity => 0,
:guest_os_full_name => nil,
:memory_console => nil,
:bitness => 64,
:virtualization_type => "paravirtual",
:root_device_type => "ebs",
)
expect(v.hardware.disks.size).to eq(0) # TODO: Change to a flavor that has disks
expect(v.hardware.guest_devices.size).to eq(0)
expect(v.hardware.nics.size).to eq(0)
expect(v.hardware.networks.size).to eq(0)
v.with_relationship_type("genealogy") do
expect(v.parent).to eq(@template)
end
end
def assert_specific_vm_on_cloud_network
v = ManageIQ::Providers::Amazon::CloudManager::Vm.where(:name => "EmsRefreshSpec-PoweredOn-VPC").first
expect(v).to have_attributes(
:template => false,
:ems_ref => "i-8b5739f2",
:ems_ref_obj => nil,
:uid_ems => "i-8b5739f2",
:vendor => "amazon",
:power_state => "on",
:location => "unknown",
:tools_status => nil,
:boot_time => "2016-08-30 07:14:39.000000000 +0000",
:standby_action => nil,
:connection_state => nil,
:cpu_affinity => nil,
:memory_reserve => nil,
:memory_reserve_expand => nil,
:memory_limit => nil,
:memory_shares => nil,
:memory_shares_level => nil,
:cpu_reserve => nil,
:cpu_reserve_expand => nil,
:cpu_limit => nil,
:cpu_shares => nil,
:cpu_shares_level => nil
)
expect(v.cloud_networks.first).to eq(@cn)
expect(v.cloud_subnets.first).to eq(@subnet)
expect(v.security_groups).to eq([@sg_on_cn])
expect(v.floating_ip).to eq(@ip1)
expect(v.floating_ips).to eq([@ip1])
expect(v.network_ports.first.floating_ips.count).to eq(1)
expect(v.network_ports.first.floating_ips).to eq([@ip1])
expect(v.network_ports.first.floating_ip_addresses).to eq([@ip1.address])
expect(v.network_ports.first.fixed_ip_addresses).to eq([@ip1.fixed_ip_address, '10.0.0.208'])
expect(v.network_ports.first.ipaddresses).to eq([@ip1.fixed_ip_address, '10.0.0.208', @ip1.address])
expect(v.ipaddresses).to eq([@ip1.fixed_ip_address, '10.0.0.208', @ip1.address])
expect(v.load_balancers.collect(&:name)).to match_array ["EmSRefreshSpecVPCELB", "EmSRefreshSpecVPCELB2"]
expect(v.load_balancer_health_checks.collect(&:ems_ref)).to match_array ["EmSRefreshSpecVPCELB", "EmSRefreshSpecVPCELB2"]
listeners = [
"EmSRefreshSpecVPCELB2__TCP__2222__TCP__22__", "EmSRefreshSpecVPCELB__HTTP__80__HTTP__80__",
"EmSRefreshSpecVPCELB__TCP__22__TCP__22__"
]
expect(v.load_balancer_listeners.collect(&:ems_ref)).to match_array listeners
expect(v.load_balancer_health_check_states).to match_array ["OutOfService", "OutOfService"]
healt_check_states_with_reason = [
"Status: OutOfService, Status Reason: Instance has failed at least the UnhealthyThreshold number of health checks consecutively.",
"Status: OutOfService, Status Reason: Instance has failed at least the UnhealthyThreshold number of health checks consecutively."
]
expect(v.load_balancer_health_check_states_with_reason).to match_array healt_check_states_with_reason
end
def assert_specific_vm_on_cloud_network_public_ip
v = ManageIQ::Providers::Amazon::CloudManager::Vm.where(:name => "EmsRefreshSpec-PoweredOn-VPC1").first
expect(v).to have_attributes(
:template => false,
:ems_ref => "i-c72af2f6",
:ems_ref_obj => nil,
:uid_ems => "i-c72af2f6",
:vendor => "amazon",
:power_state => "on",
:location => "unknown",
:tools_status => nil,
:boot_time => "2016-08-30 07:17:58.000000000 +0000",
:standby_action => nil,
:connection_state => nil,
:cpu_affinity => nil,
:memory_reserve => nil,
:memory_reserve_expand => nil,
:memory_limit => nil,
:memory_shares => nil,
:memory_shares_level => nil,
:cpu_reserve => nil,
:cpu_reserve_expand => nil,
:cpu_limit => nil,
:cpu_shares => nil,
:cpu_shares_level => nil
)
expect(v.cloud_networks.first).to eq(@cn)
expect(v.cloud_subnets.first).to eq(@subnet)
expect(v.security_groups).to eq([@sg_on_cn])
expect(v.floating_ip).to eq(@ip2)
expect(v.floating_ips).to eq([@ip2])
expect(v.network_ports.first.floating_ips.count).to eq(1)
expect(v.network_ports.first.floating_ips).to eq([@ip2])
expect(v.network_ports.first.floating_ip_addresses).to eq([@ip2.address])
expect(v.network_ports.first.fixed_ip_addresses).to eq([@ip2.fixed_ip_address])
expect(v.network_ports.first.ipaddresses).to eq([@ip2.fixed_ip_address, @ip2.address])
expect(v.ipaddresses).to eq([@ip2.fixed_ip_address, @ip2.address])
end
def assert_specific_load_balancers
@elb_non_vpc = ManageIQ::Providers::Amazon::NetworkManager::LoadBalancer.where(
:name => "EmsRefreshSpec-LoadBalancer").first
expect(@elb_non_vpc).to have_attributes(
"ems_ref" => "EmsRefreshSpec-LoadBalancer",
"name" => "EmsRefreshSpec-LoadBalancer",
"description" => nil,
"cloud_tenant_id" => nil,
"type" => "ManageIQ::Providers::Amazon::NetworkManager::LoadBalancer"
)
expect(@elb_non_vpc.ext_management_system).to eq(@ems.network_manager)
@elb = ManageIQ::Providers::Amazon::NetworkManager::LoadBalancer.where(
:name => "EmSRefreshSpecVPCELB").first
expect(@elb).to have_attributes(
"ems_ref" => "EmSRefreshSpecVPCELB",
"name" => "EmSRefreshSpecVPCELB",
"description" => nil,
"cloud_tenant_id" => nil,
"type" => "ManageIQ::Providers::Amazon::NetworkManager::LoadBalancer"
)
expect(@elb.ext_management_system).to eq(@ems.network_manager)
# TODO(lsmola)
# expect(@elb.availability_zones).to eq(@az)
# expect(@elb.cloud_subnets).to eq(..)
# expect(@elb.network_ports).to eq(..)
@elb2 = ManageIQ::Providers::Amazon::NetworkManager::LoadBalancer.where(
:name => "EmSRefreshSpecVPCELB2").first
expect(@elb2).to have_attributes(
"ems_ref" => "EmSRefreshSpecVPCELB2",
"name" => "EmSRefreshSpecVPCELB2",
"description" => nil,
"cloud_tenant_id" => nil,
"type" => "ManageIQ::Providers::Amazon::NetworkManager::LoadBalancer"
)
expect(@elb2.ext_management_system).to eq(@ems.network_manager)
expect(@elb.vms.count).to eq 2
expect(@elb.load_balancer_pool_members.count).to eq 2
expect(@elb.load_balancer_pool_members.first.ext_management_system).to eq @ems.network_manager
expect(@elb.vms.first.ext_management_system).to eq @ems
expect(@elb.vms.collect(&:name)).to match_array ["EmsRefreshSpec-PoweredOn-VPC", "VMstate-8"]
expect(@elb.vms).to match_array @elb2.vms
expect(@elb.load_balancer_pool_members).to match_array @elb2.load_balancer_pool_members
expect(@elb_non_vpc.load_balancer_pool_members.count).to eq 1
expect(@elb_non_vpc.vms.first.name).to eq "EmsRefreshSpec-PoweredOn-Basic3"
end
def assert_specific_load_balancer_listeners
expect(@elb_non_vpc.load_balancer_listeners.count).to eq 1
expect(@elb.load_balancer_listeners.count).to eq 2
expect(@elb2.load_balancer_listeners.count).to eq 1
@listener_non_vpc = @elb_non_vpc.load_balancer_listeners
.where(:ems_ref => "EmsRefreshSpec-LoadBalancer__HTTP__80__HTTP__80__").first
expect(@listener_non_vpc).to have_attributes(
"ems_ref" => "EmsRefreshSpec-LoadBalancer__HTTP__80__HTTP__80__",
"name" => nil,
"description" => nil,
"load_balancer_protocol" => "HTTP",
"load_balancer_port_range" => 80...81,
"instance_protocol" => "HTTP",
"instance_port_range" => 80...81,
"cloud_tenant_id" => nil,
"type" => "ManageIQ::Providers::Amazon::NetworkManager::LoadBalancerListener"
)
expect(@listener_non_vpc.ext_management_system).to eq(@ems.network_manager)
listener_1 = @elb.load_balancer_listeners
.where(:ems_ref => "EmSRefreshSpecVPCELB__TCP__22__TCP__22__").first
expect(listener_1).to have_attributes(
"ems_ref" => "EmSRefreshSpecVPCELB__TCP__22__TCP__22__",
"name" => nil,
"description" => nil,
"load_balancer_protocol" => "TCP",
"load_balancer_port_range" => 22...23,
"instance_protocol" => "TCP",
"instance_port_range" => 22...23,
"cloud_tenant_id" => nil,
"type" => "ManageIQ::Providers::Amazon::NetworkManager::LoadBalancerListener"
)
expect(listener_1.ext_management_system).to eq(@ems.network_manager)
@listener_2 = @elb.load_balancer_listeners
.where(:ems_ref => "EmSRefreshSpecVPCELB__HTTP__80__HTTP__80__").first
expect(@listener_2).to have_attributes(
"ems_ref" => "EmSRefreshSpecVPCELB__HTTP__80__HTTP__80__",
"name" => nil,
"description" => nil,
"load_balancer_protocol" => "HTTP",
"load_balancer_port_range" => 80...81,
"instance_protocol" => "HTTP",
"instance_port_range" => 80...81,
"cloud_tenant_id" => nil,
"type" => "ManageIQ::Providers::Amazon::NetworkManager::LoadBalancerListener"
)
expect(@listener_2.ext_management_system).to eq(@ems.network_manager)
@listener_3 = @elb2.load_balancer_listeners.first
expect(@listener_3).to have_attributes(
"ems_ref" => "EmSRefreshSpecVPCELB2__TCP__2222__TCP__22__",
"name" => nil,
"description" => nil,
"load_balancer_protocol" => "TCP",
"load_balancer_port_range" => 2222...2223,
"instance_protocol" => "TCP",
"instance_port_range" => 22...23,
"cloud_tenant_id" => nil,
"type" => "ManageIQ::Providers::Amazon::NetworkManager::LoadBalancerListener"
)
expect(@listener_3.ext_management_system).to eq(@ems.network_manager)
end
def assert_specific_load_balancer_health_checks
expect(@elb_non_vpc.load_balancer_health_checks.count).to eq 1
health_check_non_vpc = @elb_non_vpc.load_balancer_health_checks.first
expect(health_check_non_vpc).to have_attributes(
"ems_ref" => "EmsRefreshSpec-LoadBalancer",
"name" => nil,
"protocol" => "TCP",
"port" => 22,
"url_path" => "",
"interval" => 30,
"timeout" => 5,
"healthy_threshold" => 10,
"unhealthy_threshold" => 2,
"cloud_tenant_id" => nil,
"type" => "ManageIQ::Providers::Amazon::NetworkManager::LoadBalancerHealthCheck"
)
expect(health_check_non_vpc.load_balancer_listener).to eq nil
expect(@elb.load_balancer_health_checks.count).to eq 1
health_check_1 = @elb.load_balancer_health_checks.first
expect(health_check_1).to have_attributes(
"ems_ref" => "EmSRefreshSpecVPCELB",
"name" => nil,
"protocol" => "HTTP",
"port" => 80,
"url_path" => "index.html",
"interval" => 30,
"timeout" => 5,
"healthy_threshold" => 10,
"unhealthy_threshold" => 2,
"cloud_tenant_id" => nil,
"type" => "ManageIQ::Providers::Amazon::NetworkManager::LoadBalancerHealthCheck"
)
expect(@elb2.load_balancer_health_checks.count).to eq 1
health_check_2 = @elb2.load_balancer_health_checks.first
expect(health_check_2).to have_attributes(
"ems_ref" => "EmSRefreshSpecVPCELB2",
"name" => nil,
"protocol" => "TCP",
"port" => 22,
"url_path" => "",
"interval" => 30,
"timeout" => 5,
"healthy_threshold" => 10,
"unhealthy_threshold" => 2,
"cloud_tenant_id" => nil,
"type" => "ManageIQ::Providers::Amazon::NetworkManager::LoadBalancerHealthCheck"
)
expect(health_check_1.load_balancer_pool_members.count).to eq 2
expect(health_check_1.load_balancer_pool_members).to match_array health_check_2.load_balancer_pool_members
expect(health_check_1.vms).to match_array health_check_2.vms
end
def assert_specific_orchestration_template
@orch_template = OrchestrationTemplateCfn.where(:md5 => "1c67b49b780587c4e2756ba029a8844b").first
expect(@orch_template.description).to start_with("AWS CloudFormation Sample Template WordPress_Simple:")
expect(@orch_template.content).to start_with("{\n \"AWSTemplateFormatVersion\" : \"2010-09-09\",")
expect(@orch_template).to have_attributes(:draft => false, :orderable => false)
end
def assert_specific_orchestration_stack
stack = ManageIQ::Providers::Amazon::CloudManager::OrchestrationStack.where(
:name => "EmsRefreshSpecStack").first
expect(stack.status_reason)
.to eq("The following resource(s) failed to create: [OutBoundHTTPNetworkAclEntry, IPAddress, Route, "\
"InboundSSHNetworkAclEntry, WebServerWaitCondition, InboundResponsePortsNetworkAclEntry, "\
"OutBoundHTTPSNetworkAclEntry, InboundHTTPNetworkAclEntry]. ")
@orch_stack = ManageIQ::Providers::Amazon::CloudManager::OrchestrationStack.where(
:name => "EmsRefreshSpecStack-WebServerInstance-110TKGO3S0A6W").first
expect(@orch_stack).to have_attributes(
:status => "CREATE_COMPLETE",
:ems_ref => "arn:aws:cloudformation:us-east-1:200278856672:stack/EmsRefreshSpecStack-WebServerInstance-110TKGO3S0A6W/72cb3f90-5fb9-11e6-ab2c-50d501eed2b3",
)
expect(@orch_stack.description).to start_with("AWS CloudFormation Sample Template WordPress_Simple:")
assert_specific_orchestration_stack_parameters
assert_specific_orchestration_stack_resources
assert_specific_orchestration_stack_outputs
assert_specific_orchestration_stack_associations
end
def assert_specific_orchestration_stack_parameters
parameters = @orch_stack.parameters.order("ems_ref")
expect(parameters.size).to eq(2)
# assert one of the parameter models
expect(parameters[1]).to have_attributes(
:name => "InstanceType",
:value => "t1.micro"
)
end
def assert_specific_orchestration_stack_resources
resources = @orch_stack.resources.order("ems_ref")
expect(resources.size).to eq(2)
# assert one of the resource models
expect(resources[1]).to have_attributes(
:name => "WebServer",
:logical_resource => "WebServer",
:physical_resource => "i-d7754a49",
:resource_category => "AWS::EC2::Instance",
:resource_status => "CREATE_COMPLETE",
:resource_status_reason => nil,
)
end
def assert_specific_orchestration_stack_outputs
outputs = @orch_stack.outputs
expect(outputs.size).to eq(1)
expect(outputs[0]).to have_attributes(
:key => "WebsiteURL",
:value => "http://ec2-23-23-39-34.compute-1.amazonaws.com/wordpress",
:description => "WordPress Website"
)
end
def assert_specific_orchestration_stack_associations
# orchestration stack belongs to a provider
expect(@orch_stack.ext_management_system).to eq(@ems)
# orchestration stack belongs to an orchestration template
expect(@orch_stack.orchestration_template).to eq(@orch_template)
# orchestration stack can be nested
parent_stack = OrchestrationStack.where(:name => "EmsRefreshSpecStack").first
expect(@orch_stack.parent).to eq(parent_stack)
# orchestration stack can have vms
vm = Vm.where(:name => "i-d7754a49").first
# TODO(lsmola) deployment of the VCR nested Orchestration Stack is broken, I need to fix the templates
# expect(vm.orchestration_stack).to eq(@orch_stack)
# orchestration stack can have security groups
sg = SecurityGroup.where(
:name => "EmsRefreshSpecStack-WebServerInstance-110TKGO3S0A6W-WebServerSecurityGroup-K60KWXZHGJDE").first
expect(sg.orchestration_stack).to eq(@orch_stack)
# orchestration stack can have cloud networks
vpc = CloudNetwork.where(:name => "vpc-08d9b36f").first
expect(vpc.orchestration_stack).to eq(parent_stack)
end
def assert_specific_vm_in_other_region
v = ManageIQ::Providers::Amazon::CloudManager::Vm.where(:name => "EmsRefreshSpec-PoweredOn-OtherRegion").first
expect(v).to be_nil
end
def assert_relationship_tree
expect(@ems.descendants_arranged).to match_relationship_tree({})
end
end
|
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
#require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
APP_SLUG = 'business-finance-support-finder'
module BusinessSupportFinder
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
# config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.assets.prefix = 'businesssupportfinder' # this has to match the path configured in puppet and deploy scripts.
end
end
Disable Rask::Cache
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
#require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
APP_SLUG = 'business-finance-support-finder'
module BusinessSupportFinder
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
# config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.assets.prefix = 'businesssupportfinder' # this has to match the path configured in puppet and deploy scripts.
# Disable Rack::Cache
config.action_dispatch.rack_cache = nil
end
end
|
require 'spec_helper_min'
require 'support/helpers'
require 'helpers/feature_flag_helper'
describe Carto::Api::Public::DataObservatoryController do
include_context 'users helper'
include HelperMethods
include FeatureFlagHelper
before(:all) do
@master = @user1.api_key
@not_granted_token = @user1.api_keys.create_regular_key!(name: 'not_do', grants: [{ type: 'apis', apis: [] }]).token
do_grants = [{ type: 'apis', apis: ['do'] }]
@granted_token = @user1.api_keys.create_regular_key!(name: 'do', grants: do_grants).token
@headers = { 'CONTENT_TYPE' => 'application/json' }
populate_do_metadata
@feature_flag = FactoryGirl.create(:feature_flag, name: 'do-instant-licensing', restricted: true)
Carto::FeatureFlagsUser.create(user_id: @user1.id, feature_flag_id: @feature_flag.id)
end
after(:all) do
Carto::User.find_by_username('do-metadata').destroy
@feature_flag.destroy
end
before(:each) do
host! "#{@user1.username}.localhost.lan"
end
shared_examples 'an endpoint validating a DO API key' do
before(:all) do
@params ||= {}
end
it 'returns 401 if the API key is wrong' do
get_json endpoint_url(@params.merge(api_key: 'wrong')), @headers do |response|
expect(response.status).to eq(401)
end
end
it 'returns 403 when using a regular API key without DO grant' do
get_json endpoint_url(@params.merge(api_key: @not_granted_token)), @headers do |response|
expect(response.status).to eq(403)
end
end
it 'returns 200 when using the master API key' do
get_json endpoint_url(@params.merge(api_key: @master)), @headers do |response|
expect(response.status).to eq(200)
end
end
it 'returns 200 when using a regular API key with DO grant' do
get_json endpoint_url(@params.merge(api_key: @granted_token)), @headers do |response|
expect(response.status).to eq(200)
end
end
end
def endpoint_url(params = {})
send(@url_helper, params)
end
describe 'token' do
before(:all) do
@url_helper = 'api_v4_do_token_url'
@expected_body = [{ 'access_token' => 'tokenuco' }]
end
before(:each) do
Cartodb::Central.any_instance.stubs(:get_do_token).returns(@expected_body.to_json)
end
after(:each) do
Cartodb::Central.any_instance.unstub(:get_do_token)
end
it_behaves_like 'an endpoint validating a DO API key'
it 'calls Central to request the token' do
Cartodb::Central.any_instance.expects(:get_do_token).with(@user1.username).once.returns(@expected_body.to_json)
get_json endpoint_url(api_key: @master), @headers
end
it 'returns 200 with an access token' do
get_json endpoint_url(api_key: @master), @headers do |response|
expect(response.status).to eq(200)
expect(response.body).to eq @expected_body
end
end
it 'returns 500 with an explicit message if the central call fails' do
central_response = OpenStruct.new(code: 500, body: { errors: ['boom'] }.to_json)
central_error = CartoDB::CentralCommunicationFailure.new(central_response)
Cartodb::Central.any_instance.stubs(:get_do_token).raises(central_error)
get_json endpoint_url(api_key: @master), @headers do |response|
expect(response.status).to eq(500)
expect(response.body).to eq(errors: ["boom"])
end
end
end
describe 'subscriptions' do
before(:all) do
@url_helper = 'api_v4_do_subscriptions_show_url'
next_year = Time.now + 1.year
dataset1 = { dataset_id: 'carto.zzz.table1', expires_at: next_year }
dataset2 = { dataset_id: 'carto.abc.table2', expires_at: next_year }
dataset3 = { dataset_id: 'opendata.tal.table3', expires_at: next_year }
dataset4 = { dataset_id: 'carto.abc.expired', expires_at: Time.now - 1.day }
bq_datasets = [dataset1, dataset2, dataset3, dataset4]
@redis_key = "do:#{@user1.username}:datasets"
$users_metadata.hset(@redis_key, 'bq', bq_datasets.to_json)
end
after(:all) do
$users_metadata.del(@redis_key)
end
it_behaves_like 'an endpoint validating a DO API key'
it 'returns 200 with the non expired subscriptions' do
expected_dataset = { project: 'carto', dataset: 'abc', table: 'table2', id: 'carto.abc.table2', type: 'dataset' }
get_json endpoint_url(api_key: @master), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 3
expect(datasets.first).to eq expected_dataset
end
end
it 'returns 200 with an empty array if the user does not have datasets' do
host! "#{@user2.username}.localhost.lan"
get_json endpoint_url(api_key: @user2.api_key), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 0
end
end
it 'returns 500 if the stored metadata is wrong' do
host! "#{@user2.username}.localhost.lan"
redis_key = "do:#{@user2.username}:datasets"
wrong_datasets = [{ dataset_id: 'wrong', expires_at: 'wrong' }]
$users_metadata.hset(redis_key, 'bq', wrong_datasets.to_json)
get_json endpoint_url(api_key: @user2.api_key), @headers do |response|
expect(response.status).to eq(500)
expect(response.body).to eq(errors: "no time information in \"wrong\"")
end
$users_metadata.del(redis_key)
end
context 'ordering' do
it 'orders by id ascending by default' do
get_json endpoint_url(api_key: @master), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 3
expect(datasets[0][:id]).to eq 'carto.abc.table2'
expect(datasets[1][:id]).to eq 'carto.zzz.table1'
end
end
it 'orders by id descending' do
get_json endpoint_url(api_key: @master, order_direction: 'desc'), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 3
expect(datasets[0][:id]).to eq 'opendata.tal.table3'
expect(datasets[1][:id]).to eq 'carto.zzz.table1'
end
end
it 'orders by project descending' do
params = { api_key: @master, order: 'project', order_direction: 'desc' }
get_json endpoint_url(params), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 3
expect(datasets[0][:id]).to eq 'opendata.tal.table3'
end
end
it 'orders by dataset ascending' do
params = { api_key: @master, order: 'dataset', order_direction: 'asc' }
get_json endpoint_url(params), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 3
expect(datasets[0][:id]).to eq 'carto.abc.table2'
expect(datasets[1][:id]).to eq 'opendata.tal.table3'
end
end
it 'orders by table descending' do
params = { api_key: @master, order: 'table', order_direction: 'desc' }
get_json endpoint_url(params), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 3
expect(datasets[0][:id]).to eq 'opendata.tal.table3'
expect(datasets[1][:id]).to eq 'carto.abc.table2'
end
end
end
end
describe 'subscription_info' do
before(:all) do
@url_helper = 'api_v4_do_subscription_info_url'
@params = { id: 'carto.abc.dataset1', type: 'dataset' }
end
it_behaves_like 'an endpoint validating a DO API key'
it 'returns 400 if the id param is not valid' do
get_json endpoint_url(api_key: @master, id: 'wrong'), @headers do |response|
expect(response.status).to eq(400)
expect(response.body).to eq(errors: "Wrong 'id' parameter value.", errors_cause: nil)
end
end
it 'returns 400 if the type param is not valid' do
get_json endpoint_url(api_key: @master, id: 'carto.abc.dataset1', type: 'wrong'), @headers do |response|
expect(response.status).to eq(400)
expected_response = {
errors: "Wrong 'type' parameter value. Valid values are one of dataset, geography",
errors_cause: nil
}
expect(response.body).to eq expected_response
end
end
it 'returns 404 if the metadata user does not exist' do
Carto::User.find_by_username('do-metadata').destroy
get_json endpoint_url(api_key: @master, id: 'carto.abc.dataset1', type: 'dataset'), @headers do |response|
expect(response.status).to eq(404)
expect(response.body).to eq(errors: 'No Data Observatory metadata found', errors_cause: nil)
end
populate_do_metadata
end
it 'returns 404 if the dataset metadata does not exist' do
get_json endpoint_url(api_key: @master, id: 'carto.abc.inexistent', type: 'dataset'), @headers do |response|
expect(response.status).to eq(404)
expect(response.body).to eq(errors: 'No metadata found for carto.abc.inexistent', errors_cause: nil)
end
end
it 'returns 200 with the metadata for a dataset' do
get_json endpoint_url(api_key: @master, id: 'carto.abc.dataset1', type: 'dataset'), @headers do |response|
expect(response.status).to eq(200)
expected_response = {
estimated_delivery_days: 0.0,
id: 'carto.abc.dataset1',
licenses: 'licenses',
licenses_link: 'licenses_link',
rights: 'rights',
subscription_list_price: 100.0,
tos: 'tos',
tos_link: 'tos_link',
type: 'dataset'
}
expect(response.body).to eq expected_response
end
end
it 'returns 200 with the metadata for a geography' do
get_json endpoint_url(api_key: @master, id: 'carto.abc.geography1', type: 'geography'), @headers do |response|
expect(response.status).to eq(200)
expected_response = {
estimated_delivery_days: 3.0,
id: 'carto.abc.geography1',
licenses: 'licenses',
licenses_link: 'licenses_link',
rights: 'rights',
subscription_list_price: 90.0,
tos: 'tos',
tos_link: 'tos_link',
type: 'geography'
}
expect(response.body).to eq expected_response
end
end
end
describe 'subscribe' do
before(:all) do
@url_helper = 'api_v4_do_subscriptions_create_url'
@payload = { id: 'carto.abc.dataset1', type: 'dataset' }
end
it 'returns 400 if the id param is not valid' do
post_json endpoint_url(api_key: @master), id: 'wrong' do |response|
expect(response.status).to eq(400)
expect(response.body).to eq(errors: "Wrong 'id' parameter value.", errors_cause: nil)
end
end
it 'returns 400 if the type param is not valid' do
post_json endpoint_url(api_key: @master), id: 'carto.abc.dataset1', type: 'wrong' do |response|
expect(response.status).to eq(400)
expected_response = {
errors: "Wrong 'type' parameter value. Valid values are one of dataset, geography",
errors_cause: nil
}
expect(response.body).to eq expected_response
end
end
it 'returns 404 if the metadata user does not exist' do
Carto::User.find_by_username('do-metadata').destroy
post_json endpoint_url(api_key: @master), @payload do |response|
expect(response.status).to eq(404)
expect(response.body).to eq(errors: "No Data Observatory metadata found", errors_cause: nil)
end
populate_do_metadata
end
it 'returns 404 if the dataset metadata does not exist' do
post_json endpoint_url(api_key: @master), id: 'carto.abc.inexistent', type: 'dataset' do |response|
expect(response.status).to eq(404)
expect(response.body).to eq(errors: "No metadata found for carto.abc.inexistent", errors_cause: nil)
end
end
it 'returns 500 with an explicit message if the central call fails' do
central_response = OpenStruct.new(code: 500, body: { errors: ['boom'] }.to_json)
central_error = CartoDB::CentralCommunicationFailure.new(central_response)
Carto::DoLicensingService.expects(:new).with(@user1.username).once.raises(central_error)
post_json endpoint_url(api_key: @master), @payload do |response|
expect(response.status).to eq(500)
expect(response.body).to eq(errors: ["boom"])
end
end
it 'sends request emails if the dataset metadata is incomplete' do
mailer_mock = stub(:deliver_now)
dataset_id = 'carto.abc.incomplete'
DataObservatoryMailer.expects(:user_request).with(@carto_user1, dataset_id).once.returns(mailer_mock)
DataObservatoryMailer.expects(:carto_request).with(@carto_user1, dataset_id, 0.0).once.returns(mailer_mock)
post_json endpoint_url(api_key: @master), id: dataset_id, type: 'dataset' do |response|
expect(response.status).to eq(200)
end
end
it 'sends request emails if instant licensing is not enabled for the user' do
mailer_mock = stub(:deliver_now)
dataset_id = @payload[:id]
DataObservatoryMailer.expects(:user_request).with(@carto_user1, dataset_id).once.returns(mailer_mock)
DataObservatoryMailer.expects(:carto_request).with(@carto_user1, dataset_id, 0.0).once.returns(mailer_mock)
with_feature_flag @user1, 'do-instant-licensing', false do
post_json endpoint_url(api_key: @master), @payload do |response|
expect(response.status).to eq(200)
end
end
end
it 'sends request emails if the delivery time is not 0' do
mailer_mock = stub(:deliver_now)
dataset_id = 'carto.abc.geography1'
DataObservatoryMailer.expects(:user_request).with(@carto_user1, dataset_id).once.returns(mailer_mock)
DataObservatoryMailer.expects(:carto_request).with(@carto_user1, dataset_id, 3.0).once.returns(mailer_mock)
Carto::DoLicensingService.expects(:new).never
Delorean.time_travel_to '2018/01/01 00:00:00' do
post_json endpoint_url(api_key: @master), id: 'carto.abc.geography1', type: 'geography' do |response|
expect(response.status).to eq(200)
expected_response = {
estimated_delivery_days: 3.0,
id: 'carto.abc.geography1',
licenses: 'licenses',
licenses_link: 'licenses_link',
rights: 'rights',
subscription_list_price: 90.0,
tos: 'tos',
tos_link: 'tos_link',
type: 'geography'
}
expect(response.body).to eq expected_response
end
end
end
it 'returns 200 with the dataset metadata and calls the DoLicensingService with the expected params' do
expected_params = [{
dataset_id: 'carto.abc.dataset1',
available_in: ['bq'],
price: 100.0,
expires_at: Time.parse('2019/01/01 00:00:00')
}]
mock_service = mock
mock_service.expects(:subscribe).with(expected_params).once
Carto::DoLicensingService.expects(:new).with(@user1.username).once.returns(mock_service)
Delorean.time_travel_to '2018/01/01 00:00:00' do
post_json endpoint_url(api_key: @master), @payload do |response|
expect(response.status).to eq(200)
expected_response = {
estimated_delivery_days: 0.0,
id: 'carto.abc.dataset1',
licenses: 'licenses',
licenses_link: 'licenses_link',
rights: 'rights',
subscription_list_price: 100.0,
tos: 'tos',
tos_link: 'tos_link',
type: 'dataset'
}
expect(response.body).to eq expected_response
end
end
end
end
describe 'unsubscribe' do
before(:all) do
@url_helper = 'api_v4_do_subscriptions_destroy_url'
@params = { api_key: @master, id: 'carto.abc.dataset1' }
end
it 'returns 400 if the id param is not valid' do
delete_json endpoint_url(@params.merge(id: 'wrong')) do |response|
expect(response.status).to eq(400)
expect(response.body).to eq(errors: "Wrong 'id' parameter value.", errors_cause: nil)
end
end
it 'returns 204 calls the DoLicensingService with the expected params' do
mock_service = mock
mock_service.expects(:unsubscribe).with('carto.abc.dataset1').once
Carto::DoLicensingService.expects(:new).with(@user1.username).once.returns(mock_service)
delete_json endpoint_url(@params) do |response|
expect(response.status).to eq(204)
end
end
end
def populate_do_metadata
metadata_user = FactoryGirl.create(:user, username: 'do-metadata')
db_seed = %{
CREATE TABLE datasets(id text, estimated_delivery_days numeric, subscription_list_price numeric, tos text,
tos_link text, licenses text, licenses_link text, rights text, available_in text[]);
INSERT INTO datasets VALUES ('carto.abc.dataset1', 0.0, 100.0, 'tos', 'tos_link', 'licenses', 'licenses_link',
'rights', '{bq}');
INSERT INTO datasets VALUES ('carto.abc.incomplete', 0.0, 100.0, 'tos', 'tos_link', 'licenses', 'licenses_link',
'rights', NULL);
CREATE TABLE geographies(id text, estimated_delivery_days numeric, subscription_list_price numeric, tos text,
tos_link text, licenses text, licenses_link text, rights text, available_in text[]);
INSERT INTO geographies VALUES ('carto.abc.geography1', 3.0, 90.0, 'tos', 'tos_link', 'licenses', 'licenses_link',
'rights', '{bq}');
}
metadata_user.in_database.run(db_seed)
end
end
fix tests
require 'spec_helper_min'
require 'support/helpers'
require 'helpers/feature_flag_helper'
describe Carto::Api::Public::DataObservatoryController do
include_context 'users helper'
include HelperMethods
include FeatureFlagHelper
before(:all) do
@master = @user1.api_key
@not_granted_token = @user1.api_keys.create_regular_key!(name: 'not_do', grants: [{ type: 'apis', apis: [] }]).token
do_grants = [{ type: 'apis', apis: ['do'] }]
@granted_token = @user1.api_keys.create_regular_key!(name: 'do', grants: do_grants).token
@headers = { 'CONTENT_TYPE' => 'application/json' }
populate_do_metadata
@feature_flag = FactoryGirl.create(:feature_flag, name: 'do-instant-licensing', restricted: true)
Carto::FeatureFlagsUser.create(user_id: @user1.id, feature_flag_id: @feature_flag.id)
end
after(:all) do
Carto::User.find_by_username('do-metadata').destroy
@feature_flag.destroy
end
before(:each) do
host! "#{@user1.username}.localhost.lan"
end
shared_examples 'an endpoint validating a DO API key' do
before(:all) do
@params ||= {}
end
it 'returns 401 if the API key is wrong' do
get_json endpoint_url(@params.merge(api_key: 'wrong')), @headers do |response|
expect(response.status).to eq(401)
end
end
it 'returns 403 when using a regular API key without DO grant' do
get_json endpoint_url(@params.merge(api_key: @not_granted_token)), @headers do |response|
expect(response.status).to eq(403)
end
end
it 'returns 200 when using the master API key' do
get_json endpoint_url(@params.merge(api_key: @master)), @headers do |response|
expect(response.status).to eq(200)
end
end
it 'returns 200 when using a regular API key with DO grant' do
get_json endpoint_url(@params.merge(api_key: @granted_token)), @headers do |response|
expect(response.status).to eq(200)
end
end
end
def endpoint_url(params = {})
send(@url_helper, params)
end
describe 'token' do
before(:all) do
@url_helper = 'api_v4_do_token_url'
@expected_body = [{ 'access_token' => 'tokenuco' }]
end
before(:each) do
Cartodb::Central.any_instance.stubs(:get_do_token).returns(@expected_body.to_json)
end
after(:each) do
Cartodb::Central.any_instance.unstub(:get_do_token)
end
it_behaves_like 'an endpoint validating a DO API key'
it 'calls Central to request the token' do
Cartodb::Central.any_instance.expects(:get_do_token).with(@user1.username).once.returns(@expected_body.to_json)
get_json endpoint_url(api_key: @master), @headers
end
it 'returns 200 with an access token' do
get_json endpoint_url(api_key: @master), @headers do |response|
expect(response.status).to eq(200)
expect(response.body).to eq @expected_body
end
end
it 'returns 500 with an explicit message if the central call fails' do
central_response = OpenStruct.new(code: 500, body: { errors: ['boom'] }.to_json)
central_error = CartoDB::CentralCommunicationFailure.new(central_response)
Cartodb::Central.any_instance.stubs(:get_do_token).raises(central_error)
get_json endpoint_url(api_key: @master), @headers do |response|
expect(response.status).to eq(500)
expect(response.body).to eq(errors: ["boom"])
end
end
end
describe 'subscriptions' do
before(:all) do
@url_helper = 'api_v4_do_subscriptions_show_url'
next_year = Time.now + 1.year
dataset1 = { dataset_id: 'carto.zzz.table1', expires_at: next_year }
dataset2 = { dataset_id: 'carto.abc.table2', expires_at: next_year }
dataset3 = { dataset_id: 'opendata.tal.table3', expires_at: next_year }
dataset4 = { dataset_id: 'carto.abc.expired', expires_at: Time.now - 1.day }
bq_datasets = [dataset1, dataset2, dataset3, dataset4]
@redis_key = "do:#{@user1.username}:datasets"
$users_metadata.hset(@redis_key, 'bq', bq_datasets.to_json)
end
after(:all) do
$users_metadata.del(@redis_key)
end
it_behaves_like 'an endpoint validating a DO API key'
it 'returns 200 with the non expired subscriptions' do
expected_dataset = { project: 'carto', dataset: 'abc', table: 'table2', id: 'carto.abc.table2', type: 'dataset' }
get_json endpoint_url(api_key: @master), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 3
expect(datasets.first).to eq expected_dataset
end
end
it 'returns 200 with an empty array if the user does not have datasets' do
host! "#{@user2.username}.localhost.lan"
get_json endpoint_url(api_key: @user2.api_key), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 0
end
end
it 'returns 500 if the stored metadata is wrong' do
host! "#{@user2.username}.localhost.lan"
redis_key = "do:#{@user2.username}:datasets"
wrong_datasets = [{ dataset_id: 'wrong', expires_at: 'wrong' }]
$users_metadata.hset(redis_key, 'bq', wrong_datasets.to_json)
get_json endpoint_url(api_key: @user2.api_key), @headers do |response|
expect(response.status).to eq(500)
expect(response.body).to eq(errors: "no time information in \"wrong\"")
end
$users_metadata.del(redis_key)
end
context 'ordering' do
it 'orders by id ascending by default' do
get_json endpoint_url(api_key: @master), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 3
expect(datasets[0][:id]).to eq 'carto.abc.table2'
expect(datasets[1][:id]).to eq 'carto.zzz.table1'
end
end
it 'orders by id descending' do
get_json endpoint_url(api_key: @master, order_direction: 'desc'), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 3
expect(datasets[0][:id]).to eq 'opendata.tal.table3'
expect(datasets[1][:id]).to eq 'carto.zzz.table1'
end
end
it 'orders by project descending' do
params = { api_key: @master, order: 'project', order_direction: 'desc' }
get_json endpoint_url(params), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 3
expect(datasets[0][:id]).to eq 'opendata.tal.table3'
end
end
it 'orders by dataset ascending' do
params = { api_key: @master, order: 'dataset', order_direction: 'asc' }
get_json endpoint_url(params), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 3
expect(datasets[0][:id]).to eq 'carto.abc.table2'
expect(datasets[1][:id]).to eq 'opendata.tal.table3'
end
end
it 'orders by table descending' do
params = { api_key: @master, order: 'table', order_direction: 'desc' }
get_json endpoint_url(params), @headers do |response|
expect(response.status).to eq(200)
datasets = response.body[:subscriptions]
expect(datasets.count).to eq 3
expect(datasets[0][:id]).to eq 'opendata.tal.table3'
expect(datasets[1][:id]).to eq 'carto.abc.table2'
end
end
end
end
describe 'subscription_info' do
before(:all) do
@url_helper = 'api_v4_do_subscription_info_url'
@params = { id: 'carto.abc.dataset1', type: 'dataset' }
end
it_behaves_like 'an endpoint validating a DO API key'
it 'returns 400 if the id param is not valid' do
get_json endpoint_url(api_key: @master, id: 'wrong'), @headers do |response|
expect(response.status).to eq(400)
expect(response.body).to eq(errors: "Wrong 'id' parameter value.", errors_cause: nil)
end
end
it 'returns 400 if the type param is not valid' do
get_json endpoint_url(api_key: @master, id: 'carto.abc.dataset1', type: 'wrong'), @headers do |response|
expect(response.status).to eq(400)
expected_response = {
errors: "Wrong 'type' parameter value. Valid values are one of dataset, geography",
errors_cause: nil
}
expect(response.body).to eq expected_response
end
end
it 'returns 404 if the metadata user does not exist' do
Carto::User.find_by_username('do-metadata').destroy
get_json endpoint_url(api_key: @master, id: 'carto.abc.dataset1', type: 'dataset'), @headers do |response|
expect(response.status).to eq(404)
expect(response.body).to eq(errors: 'No Data Observatory metadata found', errors_cause: nil)
end
populate_do_metadata
end
it 'returns 404 if the dataset metadata does not exist' do
get_json endpoint_url(api_key: @master, id: 'carto.abc.inexistent', type: 'dataset'), @headers do |response|
expect(response.status).to eq(404)
expect(response.body).to eq(errors: 'No metadata found for carto.abc.inexistent', errors_cause: nil)
end
end
it 'returns 200 with the metadata for a dataset' do
get_json endpoint_url(api_key: @master, id: 'carto.abc.dataset1', type: 'dataset'), @headers do |response|
expect(response.status).to eq(200)
expected_response = {
estimated_delivery_days: 0.0,
id: 'carto.abc.dataset1',
licenses: 'licenses',
licenses_link: 'licenses_link',
rights: 'rights',
subscription_list_price: 100.0,
tos: 'tos',
tos_link: 'tos_link',
type: 'dataset'
}
expect(response.body).to eq expected_response
end
end
it 'returns 200 with the metadata for a geography' do
get_json endpoint_url(api_key: @master, id: 'carto.abc.geography1', type: 'geography'), @headers do |response|
expect(response.status).to eq(200)
expected_response = {
estimated_delivery_days: 3.0,
id: 'carto.abc.geography1',
licenses: 'licenses',
licenses_link: 'licenses_link',
rights: 'rights',
subscription_list_price: 90.0,
tos: 'tos',
tos_link: 'tos_link',
type: 'geography'
}
expect(response.body).to eq expected_response
end
end
end
describe 'subscribe' do
before(:all) do
@url_helper = 'api_v4_do_subscriptions_create_url'
@payload = { id: 'carto.abc.dataset1', type: 'dataset' }
end
it 'returns 400 if the id param is not valid' do
post_json endpoint_url(api_key: @master), id: 'wrong' do |response|
expect(response.status).to eq(400)
expect(response.body).to eq(errors: "Wrong 'id' parameter value.", errors_cause: nil)
end
end
it 'returns 400 if the type param is not valid' do
post_json endpoint_url(api_key: @master), id: 'carto.abc.dataset1', type: 'wrong' do |response|
expect(response.status).to eq(400)
expected_response = {
errors: "Wrong 'type' parameter value. Valid values are one of dataset, geography",
errors_cause: nil
}
expect(response.body).to eq expected_response
end
end
it 'returns 404 if the metadata user does not exist' do
Carto::User.find_by_username('do-metadata').destroy
post_json endpoint_url(api_key: @master), @payload do |response|
expect(response.status).to eq(404)
expect(response.body).to eq(errors: "No Data Observatory metadata found", errors_cause: nil)
end
populate_do_metadata
end
it 'returns 404 if the dataset metadata does not exist' do
post_json endpoint_url(api_key: @master), id: 'carto.abc.inexistent', type: 'dataset' do |response|
expect(response.status).to eq(404)
expect(response.body).to eq(errors: "No metadata found for carto.abc.inexistent", errors_cause: nil)
end
end
it 'returns 500 with an explicit message if the central call fails' do
central_response = OpenStruct.new(code: 500, body: { errors: ['boom'] }.to_json)
central_error = CartoDB::CentralCommunicationFailure.new(central_response)
Carto::DoLicensingService.expects(:new).with(@user1.username).once.raises(central_error)
post_json endpoint_url(api_key: @master), @payload do |response|
expect(response.status).to eq(500)
expect(response.body).to eq(errors: ["boom"])
end
end
it 'sends request emails if the dataset metadata is incomplete' do
mailer_mock = stub(:deliver_now)
dataset_id = 'carto.abc.incomplete'
dataset_name = 'Incomplete dataset'
DataObservatoryMailer.expects(:user_request).with(@carto_user1, dataset_id, dataset_name).once
.returns(mailer_mock)
DataObservatoryMailer.expects(:carto_request).with(@carto_user1, dataset_id, 0.0).once.returns(mailer_mock)
post_json endpoint_url(api_key: @master), id: dataset_id, type: 'dataset' do |response|
expect(response.status).to eq(200)
end
end
it 'sends request emails if instant licensing is not enabled for the user' do
mailer_mock = stub(:deliver_now)
dataset_id = @payload[:id]
dataset_name = 'CARTO dataset 1'
DataObservatoryMailer.expects(:user_request).with(@carto_user1, dataset_id, dataset_name).once
.returns(mailer_mock)
DataObservatoryMailer.expects(:carto_request).with(@carto_user1, dataset_id, 0.0).once.returns(mailer_mock)
with_feature_flag @user1, 'do-instant-licensing', false do
post_json endpoint_url(api_key: @master), @payload do |response|
expect(response.status).to eq(200)
end
end
end
it 'sends request emails if the delivery time is not 0' do
mailer_mock = stub(:deliver_now)
dataset_id = 'carto.abc.geography1'
dataset_name = 'CARTO geography 1'
DataObservatoryMailer.expects(:user_request).with(@carto_user1, dataset_id, dataset_name).once.returns(mailer_mock)
DataObservatoryMailer.expects(:carto_request).with(@carto_user1, dataset_id, 3.0).once.returns(mailer_mock)
Carto::DoLicensingService.expects(:new).never
Delorean.time_travel_to '2018/01/01 00:00:00' do
post_json endpoint_url(api_key: @master), id: 'carto.abc.geography1', type: 'geography' do |response|
expect(response.status).to eq(200)
expected_response = {
estimated_delivery_days: 3.0,
id: 'carto.abc.geography1',
licenses: 'licenses',
licenses_link: 'licenses_link',
rights: 'rights',
subscription_list_price: 90.0,
tos: 'tos',
tos_link: 'tos_link',
type: 'geography'
}
expect(response.body).to eq expected_response
end
end
end
it 'returns 200 with the dataset metadata and calls the DoLicensingService with the expected params' do
expected_params = [{
dataset_id: 'carto.abc.dataset1',
available_in: ['bq'],
price: 100.0,
expires_at: Time.parse('2019/01/01 00:00:00')
}]
mock_service = mock
mock_service.expects(:subscribe).with(expected_params).once
Carto::DoLicensingService.expects(:new).with(@user1.username).once.returns(mock_service)
Delorean.time_travel_to '2018/01/01 00:00:00' do
post_json endpoint_url(api_key: @master), @payload do |response|
expect(response.status).to eq(200)
expected_response = {
estimated_delivery_days: 0.0,
id: 'carto.abc.dataset1',
licenses: 'licenses',
licenses_link: 'licenses_link',
rights: 'rights',
subscription_list_price: 100.0,
tos: 'tos',
tos_link: 'tos_link',
type: 'dataset'
}
expect(response.body).to eq expected_response
end
end
end
end
describe 'unsubscribe' do
before(:all) do
@url_helper = 'api_v4_do_subscriptions_destroy_url'
@params = { api_key: @master, id: 'carto.abc.dataset1' }
end
it 'returns 400 if the id param is not valid' do
delete_json endpoint_url(@params.merge(id: 'wrong')) do |response|
expect(response.status).to eq(400)
expect(response.body).to eq(errors: "Wrong 'id' parameter value.", errors_cause: nil)
end
end
it 'returns 204 calls the DoLicensingService with the expected params' do
mock_service = mock
mock_service.expects(:unsubscribe).with('carto.abc.dataset1').once
Carto::DoLicensingService.expects(:new).with(@user1.username).once.returns(mock_service)
delete_json endpoint_url(@params) do |response|
expect(response.status).to eq(204)
end
end
end
def populate_do_metadata
metadata_user = FactoryGirl.create(:user, username: 'do-metadata')
db_seed = %{
CREATE TABLE datasets(id text, estimated_delivery_days numeric, subscription_list_price numeric, tos text,
tos_link text, licenses text, licenses_link text, rights text, available_in text[],
name text);
INSERT INTO datasets VALUES ('carto.abc.dataset1', 0.0, 100.0, 'tos', 'tos_link', 'licenses', 'licenses_link',
'rights', '{bq}', 'CARTO dataset 1');
INSERT INTO datasets VALUES ('carto.abc.incomplete', 0.0, 100.0, 'tos', 'tos_link', 'licenses', 'licenses_link',
'rights', NULL, 'Incomplete dataset');
CREATE TABLE geographies(id text, estimated_delivery_days numeric, subscription_list_price numeric, tos text,
tos_link text, licenses text, licenses_link text, rights text, available_in text[],
name text);
INSERT INTO geographies VALUES ('carto.abc.geography1', 3.0, 90.0, 'tos', 'tos_link', 'licenses', 'licenses_link',
'rights', '{bq}', 'CARTO geography 1');
}
metadata_user.in_database.run(db_seed)
end
end
|
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Giona
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.time_zone = 'Europe/Stockholm'
config.middleware.insert_before 0, Rack::Cors, :debug => true, :logger => Rails.logger do #TODO tighten up
allow do
origins '*'
resource '*',
:headers => :any,
:expose => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
:methods => [:get, :post, :options, :delete, :put]
end
end
end
end
whitelist console from in vagrant.
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Giona
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.time_zone = 'Europe/Stockholm'
config.web_console.whitelisted_ips = '10.0.2.2'
config.middleware.insert_before 0, Rack::Cors, :debug => true, :logger => Rails.logger do #TODO tighten up
allow do
origins '*'
resource '*',
:headers => :any,
:expose => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
:methods => [:get, :post, :options, :delete, :put]
end
end
end
end |
require File.expand_path('../boot', __FILE__)
require 'rails'
require 'action_controller/railtie'
unless Rails.env.maintenance?
require 'rails/test_unit/railtie'
require 'action_mailer/railtie'
require 'active_record/railtie'
end
Bundler.require(:default, Rails.env) if defined?(Bundler)
$rubygems_config = YAML.load_file("config/rubygems.yml")[Rails.env].symbolize_keys
HOST = $rubygems_config[:host]
# DO NOT EDIT THIS LINE DIRECTLY
# Instead, run: bundle exec rake gemcutter:rubygems:update VERSION=[version number] RAILS_ENV=[staging|production] S3_KEY=[key] S3_SECRET=[secret]
RUBYGEMS_VERSION = "1.8.17"
module Gemcutter
class Application < Rails::Application
config.time_zone = "UTC"
config.encoding = "utf-8"
config.middleware.use "Hostess"
config.middleware.insert_after "Hostess", "Redirector" if $rubygems_config[:redirector]
unless Rails.env.maintenance?
config.action_mailer.default_url_options = { :host => HOST }
config.action_mailer.delivery_method = $rubygems_config[:delivery_method]
config.active_record.include_root_in_json = false
end
config.after_initialize do
Hostess.local = $rubygems_config[:local_storage]
end
config.plugins = [:dynamic_form]
config.plugins << :heroku_asset_cacher if $rubygems_config[:asset_cacher]
config.autoload_paths << "./app/jobs"
end
end
Update site to show 1.8.21
require File.expand_path('../boot', __FILE__)
require 'rails'
require 'action_controller/railtie'
unless Rails.env.maintenance?
require 'rails/test_unit/railtie'
require 'action_mailer/railtie'
require 'active_record/railtie'
end
Bundler.require(:default, Rails.env) if defined?(Bundler)
$rubygems_config = YAML.load_file("config/rubygems.yml")[Rails.env].symbolize_keys
HOST = $rubygems_config[:host]
# DO NOT EDIT THIS LINE DIRECTLY
# Instead, run: bundle exec rake gemcutter:rubygems:update VERSION=[version number] RAILS_ENV=[staging|production] S3_KEY=[key] S3_SECRET=[secret]
RUBYGEMS_VERSION = "1.8.21"
module Gemcutter
class Application < Rails::Application
config.time_zone = "UTC"
config.encoding = "utf-8"
config.middleware.use "Hostess"
config.middleware.insert_after "Hostess", "Redirector" if $rubygems_config[:redirector]
unless Rails.env.maintenance?
config.action_mailer.default_url_options = { :host => HOST }
config.action_mailer.delivery_method = $rubygems_config[:delivery_method]
config.active_record.include_root_in_json = false
end
config.after_initialize do
Hostess.local = $rubygems_config[:local_storage]
end
config.plugins = [:dynamic_form]
config.plugins << :heroku_asset_cacher if $rubygems_config[:asset_cacher]
config.autoload_paths << "./app/jobs"
end
end
|
require 'pathname'
require 'dotenv'
module ConfigRoot
# make these methods also callable directly
# see for discussion on extend self vs module_function:
# https://github.com/bbatsov/ruby-style-guide/issues/556
extend self
# The app's configuration root directory
# @return [Pathname] path to configuration root
def config_root
Pathname.new(ENV["OOD_APP_CONFIG"] || "/etc/ood/config/apps/dashboard")
end
# Load the dotenv local files first, then the /etc dotenv files and
# the .env and .env.production or .env.development files.
#
# Doing this in two separate loads means OOD_APP_CONFIG can be specified in
# the .env.local file, which will specify where to look for the /etc dotenv
# files. The default for OOD_APP_CONFIG is /etc/ood/config/apps/myjobs and
# both .env and .env.production will be searched for there.
def load_dotenv_files
# .env.local first, so it can override OOD_APP_CONFIG
Dotenv.load(*dotenv_local_files) unless dotenv_local_files.empty?
# load the rest of the dotenv files
Dotenv.load(*dotenv_files)
end
private
# The environment
# @return [String] "development", "test", or "production"
def rails_env
ENV['RAILS_ENV'] || "development"
end
# The app's root directory
# @return [Pathname] path to configuration root
def app_root
Pathname.new(File.expand_path("../../", __FILE__))
end
def dotenv_local_files
[
app_root.join(".env.#{rails_env}.local"),
(app_root.join(".env.local") unless rails_env == "test"),
].compact
end
def dotenv_files
[
config_root.join(".env.#{rails_env}"),
app_root.join(".env.#{rails_env}"),
config_root.join(".env"),
app_root.join(".env")
].compact
end
end
rename OOD_APP_CONFIG to OOD_APP_CONFIG_ROOT
require 'pathname'
require 'dotenv'
module ConfigRoot
# make these methods also callable directly
# see for discussion on extend self vs module_function:
# https://github.com/bbatsov/ruby-style-guide/issues/556
extend self
# The app's configuration root directory
# @return [Pathname] path to configuration root
def config_root
Pathname.new(ENV["OOD_APP_CONFIG_ROOT"] || "/etc/ood/config/apps/dashboard")
end
# Load the dotenv local files first, then the /etc dotenv files and
# the .env and .env.production or .env.development files.
#
# Doing this in two separate loads means OOD_APP_CONFIG_ROOT can be specified in
# the .env.local file, which will specify where to look for the /etc dotenv
# files. The default for OOD_APP_CONFIG_ROOT is /etc/ood/config/apps/myjobs and
# both .env and .env.production will be searched for there.
def load_dotenv_files
# .env.local first, so it can override OOD_APP_CONFIG_ROOT
Dotenv.load(*dotenv_local_files) unless dotenv_local_files.empty?
# load the rest of the dotenv files
Dotenv.load(*dotenv_files)
end
private
# The environment
# @return [String] "development", "test", or "production"
def rails_env
ENV['RAILS_ENV'] || "development"
end
# The app's root directory
# @return [Pathname] path to configuration root
def app_root
Pathname.new(File.expand_path("../../", __FILE__))
end
def dotenv_local_files
[
app_root.join(".env.#{rails_env}.local"),
(app_root.join(".env.local") unless rails_env == "test"),
].compact
end
def dotenv_files
[
config_root.join(".env.#{rails_env}"),
app_root.join(".env.#{rails_env}"),
config_root.join(".env"),
app_root.join(".env")
].compact
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Gocongress
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# action_mailer's default_url_options should not be confused with
# ActionController#default_url_options(). Unlike in ActionController, we
# can only set static values here, and we can only use what's available
# during initialization. Specifically, this means that we cannot specify
# a deafult year, as we do in ActionController. -Jared 2012-01-18
config.action_mailer.default_url_options = { :host => "www.gocongress.org" }
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/lib)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable the asset pipeline
config.assets.enabled = true
# We don't want Heroku to try to initialize our models during assets:precompile
# because on Heroku Cedar, the database is not available during slug compilation.
# http://stackoverflow.com/questions/8622297/heroku-cedar-assetsprecompile-has-beef-with-attr-protected
# http://guides.rubyonrails.org/asset_pipeline.html
config.assets.initialize_on_precompile = false
end
end
remove potentially defunct comments
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Gocongress
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# action_mailer's default_url_options should not be confused with
# ActionController#default_url_options(). Unlike in ActionController, we
# can only set static values here, and we can only use what's available
# during initialization. Specifically, this means that we cannot specify
# a deafult year, as we do in ActionController. -Jared 2012-01-18
config.action_mailer.default_url_options = { :host => "www.gocongress.org" }
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/lib)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable the asset pipeline
config.assets.enabled = true
# We don't want Heroku to try to initialize our models during assets:precompile
# because on Heroku Cedar, the database is not available during slug compilation.
# http://stackoverflow.com/questions/8622297/heroku-cedar-assetsprecompile-has-beef-with-attr-protected
# http://guides.rubyonrails.org/asset_pipeline.html
config.assets.initialize_on_precompile = false
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Metamaps
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enable the asset pipeline
config.assets.initialize_on_precompile = false
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '2.0'
end
end
asset precompiling simpler in rails 4
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(:default, Rails.env)
module Metamaps
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enable the asset pipeline
config.assets.initialize_on_precompile = false
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '2.0'
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'flickraw'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Collection
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Rakismet setting
config.rakismet.key = ''
config.rakismet.url = 'http://api.records.nsw.gov.au'
#Flickr setting
FlickRaw.api_key=""
FlickRaw.shared_secret=""
Mime::Type.register "application/mods+xml", :mods
Mime::Type.register "application/x-eac_cpf+xml", :eac_cpf
Mime::Type.register "application/x-oai_dc+xml", :oai_dc
Mime::Type.register "application/x-rdf_zotero+xml", :rdf_zotero
Mime::Type.register "application/xml", :xml
end
end
Add proxy setting for flickr
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'flickraw'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Collection
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Rakismet setting
config.rakismet.key = ''
config.rakismet.url = 'http://api.records.nsw.gov.au'
#Flickr setting
FlickRaw.api_key=""
FlickRaw.shared_secret=""
FlickRaw.proxy=""
Mime::Type.register "application/mods+xml", :mods
Mime::Type.register "application/x-eac_cpf+xml", :eac_cpf
Mime::Type.register "application/x-oai_dc+xml", :oai_dc
Mime::Type.register "application/x-rdf_zotero+xml", :rdf_zotero
Mime::Type.register "application/xml", :xml
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module QuickSearch
class Engine < ::Rails::Engine
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'Eastern Time (US & Canada)'
# 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
config.middleware.use Rack::SslEnforcer, :only => /\/appstats\/?.*/, only_environments: ['production']
end
end
remove application.rb
|
require File.expand_path("../boot", __FILE__)
# Pick the frameworks you want:
require "active_model/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module MontrealRb
class Application < Rails::Application
config.time_zone = "America/Montreal"
config.i18n.default_locale = :en
config.i18n.available_locales = %i(en fr)
config.i18n.enforce_available_locales = true
config.active_record.raise_in_transactional_callbacks = true
config.to_prepare do
Administrate::ApplicationController.helper MontrealRb::Application.helpers
end
end
end
OCD Freackout avoided
require File.expand_path("../boot", __FILE__)
# Pick the frameworks you want:
require "active_model/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module MontrealRb
class Application < Rails::Application
config.time_zone = "America/Montreal"
config.i18n.default_locale = :en
config.i18n.available_locales = %i(en fr)
config.i18n.enforce_available_locales = true
config.active_record.raise_in_transactional_callbacks = true
config.to_prepare do
Administrate::ApplicationController.helper MontrealRb::Application.helpers
end
end
end
|
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Coruscope
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
config.autoload_paths += Dir["#{config.root}/lib/**/"]
end
end
add assets to precompilation
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Coruscope
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
config.autoload_paths += Dir["#{config.root}/lib/**/"]
config.assets.precompile += %w{coruscope.js coruscope.css}
end
end
|
added CVS/SVN users recon module
=begin
Arachni
Copyright (c) 2010 Tasos "Zapotek" Laskos <tasos.laskos@gmail.com>
This is free software; you can copy and distribute and modify
this program under the term of the GPL v2.0 License
(See LICENSE file for details)
=end
module Arachni
module Modules
#
# CVS/SVN users recon module.
#
# Scans every page for CVS/SVN users.
#
# @author: morpheuslaw <msidagni@nopsec.com>
# @version: 0.1
#
class CvsSvnUsers < Arachni::Module::Base
def initialize( page )
@page = page
end
def run
regexps = [
/\$Author: (.*) \$/,
/\$Locker: (.*) \$/,
/\$Header: .* (.*) (Exp )?\$/,
/\$Id: .* (.*) (Exp )?\$/
]
matches = regexps.map {
|regexp|
@page.html.scan( regexp )
}.flatten.reject{ |match| !match || match =~ /Exp/ }.map{ |match| match.strip }.uniq
matches.each {
|match|
log_match(
:regexp => regexps.to_s,
:match => match,
:element => Vulnerability::Element::BODY
)
}
end
def self.info
{
:name => 'CVS/SVN users',
:description => %q{Scans every page for CVS/SVN users.},
:author => 'morpheuslaw <msidagni@nopsec.com>',
:version => '0.1',
:targets => { 'Generic' => 'all' },
:vulnerability => {
:name => %q{CVS/SVN user disclosure.},
:description => %q{An CVS or SVN user is disclosed in the body of the HTML page.},
:cwe => '200',
:severity => Vulnerability::Severity::LOW,
:cvssv2 => '0',
:remedy_guidance => %q{Remove all CVS and SVN users from the body of the HTML page.},
:remedy_code => '',
}
}
end
end
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module SeattlerbOrg
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable the asset pipeline
config.assets.enabled = true
config.assets.initialize_on_precompile = false
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# carryforwad from v 2.3.3
config.time_zone = 'UTC'
end
end
class ActiveRecord::Base
class << self
alias habtm has_and_belongs_to_many
end
end
Turn off mass assignment protection, turn on strong parameters.
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module SeattlerbOrg
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable the asset pipeline
config.assets.enabled = true
config.assets.initialize_on_precompile = false
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# carryforwad from v 2.3.3
config.time_zone = 'UTC'
config.active_record.whitelist_attributes = false
end
end
ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)
class ActiveRecord::Base
class << self
alias habtm has_and_belongs_to_many
end
end
|
require_relative 'boot'
require 'csv'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module CloudBenchmarking
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.autoload_paths += %W(
#{Rails.root}/app/jobs
)
# Handle exceptions (e.g. 404 not found) in routes.rb
config.exceptions_app = self.routes
# Add fonts in vendor directory to assets pipeline
config.assets.paths << "#{Rails.root}/vendor/assets/fonts"
# config.assets.precompile += %w( *.ttf *.eot *.svg *.woff *.png *.gif *.jpg )
config.assets.precompile << %r{.(?:svg|eot|woff|ttf|png|gif|jpg)}
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'CET' # CET := Central European Time
# 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
# Suppress assets log in development
config.quiet_assets = true
### CloudBenchmarking settings
ENV['UPDATE_SYSTEM_CRONTAB'] ||= 'true'
# Default authentication
config.default_email = 'seal@uzh.ch' # NOTE: MUST match with lib/capistrano/tasks/user.rake
config.default_password = 'demo'
# Schedule failed threshold (after x consecutive unsuccessful executions)
config.execution_failed_threshold = 3
# Timeout
config.default_running_timeout = 24 # Hours after a running benchmark will be terminated
config.failure_timeout = 15.minutes # Minutes after which the instances will be terminated on failure
# VMs
config.vm_benchmark_dir = '/usr/local/cloud-benchmark'
config.vm_start_runner = 'start_runner.sh'
config.vm_start_postprocessing = 'stop_and_postprocess_runner.sh'
config.vm_error_log_file = 'cwb_runner_stderr.log' # Only covers the cwb runner scripts.
# String of supported providers that Vagrant uses as directory name (should be the same as used with vagrant up)
config.supported_providers = %w(aws google azure softlayer)
# Main paths
config.storage = File.join(Rails.root, 'storage', Rails.env)
config.log = File.join(Rails.root, 'log')
config.templates = File.join(Rails.root, 'lib', 'templates')
# Benchmark definition
config.vagrantfile_example = File.join(config.templates, 'erb', 'Vagrantfile_example.erb')
config.vagrantfile = File.join(config.templates, 'erb', 'Vagrantfile.erb')
# Benchmark execution
config.benchmark_executions = File.join(config.storage, 'benchmark_executions')
# Benchmark schedule
config.benchmark_schedule_template = File.join(config.templates, 'erb', 'whenever_schedule.rb.erb')
config.benchmark_schedule = File.join(config.storage, 'benchmark_schedules', 'whenever_schedule.rb')
config.benchmark_schedule_log = File.join(config.log, 'benchmark_schedule.log')
end
end
Upgrade Rails defaults to 5.2
Changes: `config/initializers/new_framework_defaults_5_2.rb`
Noticable:
Add default protection from forgery to ActionController::Base instead of in
ApplicationController.
```ruby
Rails.application.config.action_controller.default_protect_from_forgery = true
```
Store boolean values are in sqlite3 databases as 1 and 0 instead of 't' and
'f' after migrating old data.
```ruby
Rails.application.config.active_record.sqlite3.represent_boolean_as_integer = true
```
```
DEPRECATION WARNING: Leaving `ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer`
set to false is deprecated. SQLite databases have used 't' and 'f' to serialize
boolean values and must have old data converted to 1 and 0 (its native boolean
serialization) before setting this flag to true. Conversion can be accomplished
by setting up a rake task which runs
ExampleModel.where("boolean_column = 't'").update_all(boolean_column: 1)
ExampleModel.where("boolean_column = 'f'").update_all(boolean_column: 0)
```
require_relative 'boot'
require 'csv'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module CloudBenchmarking
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.autoload_paths += %W(
#{Rails.root}/app/jobs
)
# Handle exceptions (e.g. 404 not found) in routes.rb
config.exceptions_app = self.routes
# Add fonts in vendor directory to assets pipeline
config.assets.paths << "#{Rails.root}/vendor/assets/fonts"
# config.assets.precompile += %w( *.ttf *.eot *.svg *.woff *.png *.gif *.jpg )
config.assets.precompile << %r{.(?:svg|eot|woff|ttf|png|gif|jpg)}
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'CET' # CET := Central European Time
# 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
# Suppress assets log in development
config.quiet_assets = true
### CloudBenchmarking settings
ENV['UPDATE_SYSTEM_CRONTAB'] ||= 'true'
# Default authentication
config.default_email = 'seal@uzh.ch' # NOTE: MUST match with lib/capistrano/tasks/user.rake
config.default_password = 'demo'
# Schedule failed threshold (after x consecutive unsuccessful executions)
config.execution_failed_threshold = 3
# Timeout
config.default_running_timeout = 24 # Hours after a running benchmark will be terminated
config.failure_timeout = 15.minutes # Minutes after which the instances will be terminated on failure
# VMs
config.vm_benchmark_dir = '/usr/local/cloud-benchmark'
config.vm_start_runner = 'start_runner.sh'
config.vm_start_postprocessing = 'stop_and_postprocess_runner.sh'
config.vm_error_log_file = 'cwb_runner_stderr.log' # Only covers the cwb runner scripts.
# String of supported providers that Vagrant uses as directory name (should be the same as used with vagrant up)
config.supported_providers = %w(aws google azure softlayer)
# Main paths
config.storage = File.join(Rails.root, 'storage', Rails.env)
config.log = File.join(Rails.root, 'log')
config.templates = File.join(Rails.root, 'lib', 'templates')
# Benchmark definition
config.vagrantfile_example = File.join(config.templates, 'erb', 'Vagrantfile_example.erb')
config.vagrantfile = File.join(config.templates, 'erb', 'Vagrantfile.erb')
# Benchmark execution
config.benchmark_executions = File.join(config.storage, 'benchmark_executions')
# Benchmark schedule
config.benchmark_schedule_template = File.join(config.templates, 'erb', 'whenever_schedule.rb.erb')
config.benchmark_schedule = File.join(config.storage, 'benchmark_schedules', 'whenever_schedule.rb')
config.benchmark_schedule_log = File.join(config.log, 'benchmark_schedule.log')
end
end
|
require File.expand_path('../boot', __FILE__)
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'sprockets/railtie'
Bundler.require(:default, Rails.env)
module OpenFarm
class Application < Rails::Application
I18n.enforce_available_locales = false
config.i18n.fallbacks = [:en]
config.assets.initialize_on_precompile = false
# Include all JS files, also those in subdolfer or javascripts assets folder
# includes for exmaple applicant.js. JS isn't the problem so the catch all works.
config.assets.precompile += %w(*.js)
# Replace %w( *.css *.js *.css.scss) with complex regexp avoiding SCSS partials compilation
config.assets.precompile += [/^[^_]\w+\.(css|css.scss)$/]
#Adding active_admin JS and CSS to the precompilation list
config.assets.precompile += %w( active_admin.css active_admin.js active_admin/print.css )
config.middleware.insert_before 'ActionDispatch::Static', 'Rack::Cors' do
allow do
origins '*'
resource '/api/*',
headers: :any,
methods: [:get, :post, :delete, :put, :patch, :options, :head],
credentials: false, # No cookies.
max_age: 0
end
end
config.middleware.use Rack::Attack
end
end
Shush Hound
require File.expand_path('../boot', __FILE__)
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'sprockets/railtie'
Bundler.require(:default, Rails.env)
module OpenFarm
class Application < Rails::Application
I18n.enforce_available_locales = false
config.i18n.fallbacks = [:en]
config.assets.initialize_on_precompile = false
# Include all JS files, also those in subdolfer or javascripts assets folder
# includes for exmaple applicant.js. JS isn't the problem so the catch all works.
config.assets.precompile += %w(*.js)
# Replace %w( *.css *.js *.css.scss) with complex regexp avoiding SCSS partials compilation
config.assets.precompile += [/^[^_]\w+\.(css|css.scss)$/]
# Adding active_admin JS and CSS to the precompilation list
config.assets.precompile += %w( active_admin.css active_admin.js active_admin/print.css )
config.middleware.insert_before 'ActionDispatch::Static', 'Rack::Cors' do
allow do
origins '*'
resource '/api/*',
headers: :any,
methods: [:get, :post, :delete, :put, :patch, :options, :head],
credentials: false, # No cookies.
max_age: 0
end
end
config.middleware.use Rack::Attack
end
end
|
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Edgar
class Application < Rails::Application
# don't generate RSpec tests for views and helpers
config.generators do |g|
g.test_framework :rspec, fixture: true
g.fixture_replacement :factory_girl, dir: 'spec/factories'
g.view_specs false
g.helper_specs false
end
config.autoload_paths += %W(#{config.root}/lib #{config.root}/lib/extras)
config.time_zone = 'Paris'
config.i18n.default_locale = :fr
config.i18n.locale = :fr
config.encoding = "utf-8"
config.filter_parameters += [:password, :password_confirmation]
config.active_support.escape_html_entities_in_json = true
config.active_record.whitelist_attributes = true
config.assets.initialize_on_precompile = false
config.to_prepare do
Devise::RegistrationsController.layout "onepage"
Devise::SessionsController.layout "simple"
Devise::PasswordsController.layout "simple"
end
end
end
Try to add back production setup
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Edgar
class Application < Rails::Application
# don't generate RSpec tests for views and helpers
config.generators do |g|
g.test_framework :rspec, fixture: true
g.fixture_replacement :factory_girl, dir: 'spec/factories'
g.view_specs false
g.helper_specs false
end
config.autoload_paths += %W(#{config.root}/lib #{config.root}/lib/extras)
config.time_zone = 'Paris'
config.i18n.default_locale = :fr
config.i18n.locale = :fr
config.encoding = "utf-8"
config.filter_parameters += [:password, :password_confirmation]
config.active_support.escape_html_entities_in_json = true
config.active_record.whitelist_attributes = true
config.assets.enabled = true
config.assets.version = '1.5'
config.assets.initialize_on_precompile = false
config.to_prepare do
Devise::RegistrationsController.layout "onepage"
Devise::SessionsController.layout "simple"
Devise::PasswordsController.layout "simple"
end
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# FIXME this silences the warnings about Rails 2.3-style plugins under
# vendor/plugins, which are deprecated. Hiding those warnings makes it easier
# to work for now, but we should really look at putting those plugins away.
ActiveSupport::Deprecation.silenced = true
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Noosfero
class Application < Rails::Application
require 'noosfero/plugin'
# Adds custom attributes to the Set of allowed html attributes for the #sanitize helper
config.action_view.sanitized_allowed_attributes = 'align', 'border', 'alt', 'vspace', 'hspace', 'width', 'heigth', 'value', 'type', 'data', 'style', 'target', 'codebase', 'archive', 'classid', 'code', 'flashvars', 'scrolling', 'frameborder', 'controls', 'autoplay', 'colspan', 'rowspan'
# Adds custom tags to the Set of allowed html tags for the #sanitize helper
config.action_view.sanitized_allowed_tags = 'object', 'embed', 'param', 'table', 'tr', 'th', 'td', 'applet', 'comment', 'iframe', 'audio', 'video', 'source'
config.action_controller.include_all_helpers = false
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W( #{Rails.root.join('app', 'sweepers')} )
config.autoload_paths += Dir["#{config.root}/lib/**/"]
config.autoload_paths += Dir["#{config.root}/app/controllers/**/"]
config.autoload_paths += %W( #{Rails.root.join('test', 'mocks', Rails.env)} )
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# Sweepers are observers
# don't load the sweepers while loading the database
ignore_rake_commands = %w[
db:schema:load
gems:install
clobber
noosfero:translations:compile
makemo
]
if $PROGRAM_NAME =~ /rake$/ && (ignore_rake_commands.include?(ARGV.first))
Noosfero::Plugin.should_load = false
else
config.active_record.observers = :article_sweeper, :role_assignment_sweeper, :friendship_sweeper, :category_sweeper, :block_sweeper
end
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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 = nil
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
ActiveSupport::JSON::Encoding.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Straight support for assets from a rails 2 pattern
# See also config/initializers/assets.rb
config.assets.paths =
Dir.glob("{base,config/}plugins/*/{assets,public}/{,javascripts,stylesheets}") +
Dir.glob("public/{,javascripts,stylesheets}") +
# no precedence over core
Dir.glob("public/{designs/themes,user_themes}/*/{,javascripts,stylesheets}")
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.sass.preferred_syntax = :scss
config.sass.cache = true
config.sass.line_comments = false
def noosfero_session_secret
require 'fileutils'
target_dir = File.join(File.dirname(__FILE__), '../tmp')
FileUtils.mkdir_p(target_dir)
file = File.join(target_dir, 'session.secret')
if !File.exists?(file)
secret = (1..128).map { %w[0 1 2 3 4 5 6 7 8 9 a b c d e f][rand(16)] }.join('')
File.open(file, 'w') do |f|
f.puts secret
end
end
File.read(file).strip
end
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.secret_token = noosfero_session_secret
config.action_dispatch.session = {
:key => '_noosfero_session',
}
config.paths['db/migrate'] += Dir.glob "#{Rails.root}/{baseplugins,config/plugins/*}/db/migrate"
config.i18n.load_path += Dir.glob "#{Rails.root}/{baseplugins,config/plugins/*}/locales/*.{rb,yml}"
Noosfero::Plugin.setup(config)
end
end
Set default timezone as needed by rails 3.2
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# FIXME this silences the warnings about Rails 2.3-style plugins under
# vendor/plugins, which are deprecated. Hiding those warnings makes it easier
# to work for now, but we should really look at putting those plugins away.
ActiveSupport::Deprecation.silenced = true
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Noosfero
class Application < Rails::Application
require 'noosfero/plugin'
# Adds custom attributes to the Set of allowed html attributes for the #sanitize helper
config.action_view.sanitized_allowed_attributes = 'align', 'border', 'alt', 'vspace', 'hspace', 'width', 'heigth', 'value', 'type', 'data', 'style', 'target', 'codebase', 'archive', 'classid', 'code', 'flashvars', 'scrolling', 'frameborder', 'controls', 'autoplay', 'colspan', 'rowspan'
# Adds custom tags to the Set of allowed html tags for the #sanitize helper
config.action_view.sanitized_allowed_tags = 'object', 'embed', 'param', 'table', 'tr', 'th', 'td', 'applet', 'comment', 'iframe', 'audio', 'video', 'source'
config.action_controller.include_all_helpers = false
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W( #{Rails.root.join('app', 'sweepers')} )
config.autoload_paths += Dir["#{config.root}/lib/**/"]
config.autoload_paths += Dir["#{config.root}/app/controllers/**/"]
config.autoload_paths += %W( #{Rails.root.join('test', 'mocks', Rails.env)} )
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# Sweepers are observers
# don't load the sweepers while loading the database
ignore_rake_commands = %w[
db:schema:load
gems:install
clobber
noosfero:translations:compile
makemo
]
if $PROGRAM_NAME =~ /rake$/ && (ignore_rake_commands.include?(ARGV.first))
Noosfero::Plugin.should_load = false
else
config.active_record.observers = :article_sweeper, :role_assignment_sweeper, :friendship_sweeper, :category_sweeper, :block_sweeper
end
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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 = nil
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
ActiveSupport::JSON::Encoding.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Straight support for assets from a rails 2 pattern
# See also config/initializers/assets.rb
config.assets.paths =
Dir.glob("{base,config/}plugins/*/{assets,public}/{,javascripts,stylesheets}") +
Dir.glob("public/{,javascripts,stylesheets}") +
# no precedence over core
Dir.glob("public/{designs/themes,user_themes}/*/{,javascripts,stylesheets}")
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.sass.preferred_syntax = :scss
config.sass.cache = true
config.sass.line_comments = false
def noosfero_session_secret
require 'fileutils'
target_dir = File.join(File.dirname(__FILE__), '../tmp')
FileUtils.mkdir_p(target_dir)
file = File.join(target_dir, 'session.secret')
if !File.exists?(file)
secret = (1..128).map { %w[0 1 2 3 4 5 6 7 8 9 a b c d e f][rand(16)] }.join('')
File.open(file, 'w') do |f|
f.puts secret
end
end
File.read(file).strip
end
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.secret_token = noosfero_session_secret
config.action_dispatch.session = {
:key => '_noosfero_session',
}
config.time_zone = File.read('/etc/timezone').split("\n").first
config.active_record.default_timezone = config.time_zone
config.paths['db/migrate'] += Dir.glob "#{Rails.root}/{baseplugins,config/plugins/*}/db/migrate"
config.i18n.load_path += Dir.glob "#{Rails.root}/{baseplugins,config/plugins/*}/locales/*.{rb,yml}"
Noosfero::Plugin.setup(config)
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'securerandom'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Theoj
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
config.sass.preferred_syntax = :sass
config.i18n.enforce_available_locales = true
end
end
local version of web components
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'securerandom'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Theoj
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
config.sass.preferred_syntax = :sass
Rails.application.config.assets.precompile << "webcomponentsjs/webcomponents.js"
config.i18n.enforce_available_locales = true
end
end
|
require_relative 'boot'
require 'rails'
# Pick the frameworks you want:
require 'active_model/railtie'
require 'active_job/railtie'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'action_view/railtie'
require 'action_cable/engine'
require 'sprockets/railtie'
# require 'rails/test_unit/railtie'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Prometheus20
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.generators do |g|
g.test_framework :rspec, fixture: true
g.fixture_replacement :factory_girl
g.helper false
end
# TODO: extract to initializer
# fallback for empty translations
config.i18n.fallbacks = true
# TODO: extract to initializer
if Rails.env.production?
config.middleware.use ExceptionNotification::Rack,
email: {
email_prefix: '[ERROR] ',
sender_address: %('Sisyphus 2.0 Error' <prometheus-noreply@altlinux.org>),
exception_recipients: %w(igor.zubkov@gmail.com)
}
config.middleware.use Rack::ForceDomain, 'packages.altlinux.org'
end
end
end
Document config.i18n.fallbacks
require_relative 'boot'
require 'rails'
# Pick the frameworks you want:
require 'active_model/railtie'
require 'active_job/railtie'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'action_view/railtie'
require 'action_cable/engine'
require 'sprockets/railtie'
# require 'rails/test_unit/railtie'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Prometheus20
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.generators do |g|
g.test_framework :rspec, fixture: true
g.fixture_replacement :factory_girl
g.helper false
end
# http://batsov.com/articles/2012/09/12/setting-up-fallback-locale-s-in-rails-3/
# Fallback for empty translations
config.i18n.fallbacks = true
# TODO: extract to initializer
if Rails.env.production?
config.middleware.use ExceptionNotification::Rack,
email: {
email_prefix: '[ERROR] ',
sender_address: %('Sisyphus 2.0 Error' <prometheus-noreply@altlinux.org>),
exception_recipients: %w(igor.zubkov@gmail.com)
}
config.middleware.use Rack::ForceDomain, 'packages.altlinux.org'
end
end
end
|
require File.expand_path('../boot', __FILE__)
require 'action_controller/railtie'
require 'rails/test_unit/railtie'
require 'sprockets/railtie'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SignInWithTwitter
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# Do not swallow errors in after_commit/after_rollback callbacks.
# config.active_record.raise_in_transactional_callbacks = true
end
end
minor updates
require File.expand_path('../boot', __FILE__)
require 'action_controller/railtie'
require 'rails/test_unit/railtie'
require 'sprockets/railtie'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SearchTwitter
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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 = :en
# Do not swallow errors in after_commit/after_rollback callbacks.
# config.active_record.raise_in_transactional_callbacks = true
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
APP_ROOT = File.expand_path('../..', __FILE__)
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
# Short-hand for the three execution modes.
PRODUCTION = (::Rails.env == 'production')
DEVELOPMENT = (::Rails.env == 'development')
TESTING = (::Rails.env == 'test')
# Should be one of [:normal, :silent]
# :silent turns off event logging and email notifications
class RunLevel
@@runlevel = :normal
def self.normal()
@@runlevel = :normal
end
def self.silent()
@@runlevel = :silent
end
def self.is_normal?()
@@runlevel == :normal
end
end
# RUN_LEVEL = :normal # :silent
def import_constants(file)
file = File.join(File.dirname(__FILE__), file)
if File.exists?(file)
Module.new do
class_eval File.read(file, :encoding => 'utf-8')
for const in constants
unless Object.const_defined?(const)
Object.const_set(const, const_get(const))
end
end
end
end
end
import_constants('consts-site.rb')
import_constants('consts.rb')
module MushroomObserver
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(
#{::Rails.root.to_s}/app/classes
#{::Rails.root.to_s}/app/extensions
)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Make Active Record use UTC instead of local time. This is critical if we
# want to sync up remote servers. It causes Rails to store dates in UTC and
# convert from UTC to whatever we've set the timezone to when reading them
# back in. It shouldn't actually make any difference how the database is
# configured. It takes dates as a string, stores them however it chooses,
# performing whatever conversions it deems fit, then returns them back to us
# in exactly the same format we gave them to it. (NOTE: only the first line
# should be necessary, but for whatever reason, Rails is failing to do the
# other configs on some platforms.)
config.time_zone = SERVER_TIME_ZONE
if config.time_zone.nil?
raise 'TZ environment variable must be set. Run "rake -D time" for a list of tasks for finding appropriate time zone names.'
end
# 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# This instructs ActionView how to mark form fields which have an error.
# I just change the CSS class to "has_error", which gives it a red border.
# This is superior to the default, which encapsulates the field in a div,
# because that throws the layout off. Just changing the border, while less
# conspicuous, has no effect on the layout. This is not a hack, this is
# just a standard configuration many rails apps take advantage of.
config.action_view.field_error_proc = Proc.new { |html_tag, instance|
html_tag.sub(/(<\w+)/, '\1 class="has_error"').html_safe
}
# Configure SMTP settings for ActionMailer.
config.action_mailer.smtp_settings = MAIL_CONFIG
# Minimal asset configuration.
config.assets.enabled = true
config.assets.version = '1.0'
end
end
# The original version of this method tries to copy the inheritance column,
# but since we don't use inheritance columns, it throws a ton of deprecation
# warnings. I copied the original version here minus the inheritance stuff.
# I suspect this will go away when we upgrade to rails 3.2.
# -Jason 20140727 (acts_as_versioned_jw version 3.2.3)
require 'acts_as_versioned'
module ActiveRecord
module Acts
module Versioned
module Behaviors
def clone_versioned_model(orig_model, new_model)
self.class.versioned_columns.each do |col|
next unless orig_model.has_attribute?(col.name)
define_method(new_model, col.name.to_sym)
new_model.send("#{col.name.to_sym}=", orig_model.send(col.name))
end
end
end
end
end
end
Unset I18n.enforce_available_locales to silence deprecation warning.
require File.expand_path('../boot', __FILE__)
require 'rails/all'
APP_ROOT = File.expand_path('../..', __FILE__)
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
# Short-hand for the three execution modes.
PRODUCTION = (::Rails.env == 'production')
DEVELOPMENT = (::Rails.env == 'development')
TESTING = (::Rails.env == 'test')
# Should be one of [:normal, :silent]
# :silent turns off event logging and email notifications
class RunLevel
@@runlevel = :normal
def self.normal()
@@runlevel = :normal
end
def self.silent()
@@runlevel = :silent
end
def self.is_normal?()
@@runlevel == :normal
end
end
# RUN_LEVEL = :normal # :silent
def import_constants(file)
file = File.join(File.dirname(__FILE__), file)
if File.exists?(file)
Module.new do
class_eval File.read(file, :encoding => 'utf-8')
for const in constants
unless Object.const_defined?(const)
Object.const_set(const, const_get(const))
end
end
end
end
end
import_constants('consts-site.rb')
import_constants('consts.rb')
module MushroomObserver
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(
#{::Rails.root.to_s}/app/classes
#{::Rails.root.to_s}/app/extensions
)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Make Active Record use UTC instead of local time. This is critical if we
# want to sync up remote servers. It causes Rails to store dates in UTC and
# convert from UTC to whatever we've set the timezone to when reading them
# back in. It shouldn't actually make any difference how the database is
# configured. It takes dates as a string, stores them however it chooses,
# performing whatever conversions it deems fit, then returns them back to us
# in exactly the same format we gave them to it. (NOTE: only the first line
# should be necessary, but for whatever reason, Rails is failing to do the
# other configs on some platforms.)
config.time_zone = SERVER_TIME_ZONE
if config.time_zone.nil?
raise 'TZ environment variable must be set. Run "rake -D time" for a list of tasks for finding appropriate time zone names.'
end
# 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
config.i18n.enforce_available_locales = false
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# This instructs ActionView how to mark form fields which have an error.
# I just change the CSS class to "has_error", which gives it a red border.
# This is superior to the default, which encapsulates the field in a div,
# because that throws the layout off. Just changing the border, while less
# conspicuous, has no effect on the layout. This is not a hack, this is
# just a standard configuration many rails apps take advantage of.
config.action_view.field_error_proc = Proc.new { |html_tag, instance|
html_tag.sub(/(<\w+)/, '\1 class="has_error"').html_safe
}
# Configure SMTP settings for ActionMailer.
config.action_mailer.smtp_settings = MAIL_CONFIG
# Minimal asset configuration.
config.assets.enabled = true
config.assets.version = '1.0'
end
end
# The original version of this method tries to copy the inheritance column,
# but since we don't use inheritance columns, it throws a ton of deprecation
# warnings. I copied the original version here minus the inheritance stuff.
# I suspect this will go away when we upgrade to rails 3.2.
# -Jason 20140727 (acts_as_versioned_jw version 3.2.3)
require 'acts_as_versioned'
module ActiveRecord
module Acts
module Versioned
module Behaviors
def clone_versioned_model(orig_model, new_model)
self.class.versioned_columns.each do |col|
next unless orig_model.has_attribute?(col.name)
define_method(new_model, col.name.to_sym)
new_model.send("#{col.name.to_sym}=", orig_model.send(col.name))
end
end
end
end
end
end
|
# Apache 2.0 License
#
# Copyright (c) 2016 Sebastian Katzer, appPlant GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
opt! :help do
<<-USAGE
#{ISS::LOGO}
usage: iss [options...]
Options:
-e, --environment The environment to run the server with
-h, --host The host to bind the local server on
Defaults to: 0.0.0.0
-p, --port The port number to start the local server on
Defaults to: 1974
-r, --routes Print out all defined routes
-t, --timeout Receive timeout before socket will be closed
Defaults to: 1 (sec)
-h, --help This help text
-v, --version Show version number
USAGE
end
opt! :version do
"iss v#{ISS::VERSION} - #{OS.sysname} #{OS.bits(:binary)}-Bit (#{OS.machine})"
end
opt! :routes do
routes.join("\n")
end
opt :environment, 'development' do |env|
ENV['SHELF_ENV'] = env
end
opt :port, 1974 do |port|
set :port, port.to_i
end
opt :host, 'localhost' do |host|
set :host, host
end
opt :timeout, 1 do |timeout|
set :timeout, timeout.to_i
end
Specify type of opts
# Apache 2.0 License
#
# Copyright (c) 2016 Sebastian Katzer, appPlant GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
opt! :help do
<<-USAGE
#{ISS::LOGO}
usage: iss [options...]
Options:
-e, --environment The environment to run the server with
-h, --host The host to bind the local server on
Defaults to: 0.0.0.0
-p, --port The port number to start the local server on
Defaults to: 1974
-r, --routes Print out all defined routes
-t, --timeout Receive timeout before socket will be closed
Defaults to: 1 (sec)
-h, --help This help text
-v, --version Show version number
USAGE
end
opt! :version do
"iss v#{ISS::VERSION} - #{OS.sysname} #{OS.bits(:binary)}-Bit (#{OS.machine})"
end
opt! :routes do
routes.join("\n")
end
opt :environment, 'development' do |env|
ENV['SHELF_ENV'] = env
end
opt :port, :int, 1974 do |port|
set :port, port
end
opt :host, 'localhost' do |host|
set :host, host
end
opt :timeout, :int, 1 do |timeout|
set :timeout, timeout
end
|
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module EcotoneWeb
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
end
end
Change default to match dummy app
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module EcotoneWeb
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Reading
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
config.time_zone = 'Eastern Time (US & Canada)'
# 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
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
Added PDFKit as middleware
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Reading
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
config.time_zone = 'Eastern Time (US & Canada)'
# 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
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# Used to add .pdf to end of urls to generate a PDF
config.middleware.use PDFKit::Middleware, :print_media_type => true
end
end
|
require_relative 'boot'
require "rails"
[
"active_record/railtie",
#"active_storage/engine",
"action_controller/railtie",
"action_view/railtie",
"action_mailer/railtie",
"active_job/railtie",
"action_cable/engine",
#"action_mailbox/engine",
#"action_text/engine",
"rails/test_unit/railtie",
"sprockets/railtie" # Disable this after migrating to Webpacker
].each do |railtie|
begin
require railtie
rescue LoadError
end
end
require_relative "../lib/open_food_network/i18n_config"
require_relative '../lib/spree/core/environment'
require_relative '../lib/spree/core/mail_interceptor'
require_relative "../lib/session_cookie_upgrader"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Openfoodnetwork
class Application < Rails::Application
config.middleware.insert_before(
ActionDispatch::Cookies,
SessionCookieUpgrader, {
old_key: "_session_id",
new_key: "_ofn_session_id",
domain: ".#{ENV['SITE_URL'].gsub(/^(www\.)|^(app\.)|^(staging\.)|^(stg\.)/, '')}"
}
) if Rails.env.staging? || Rails.env.production?
config.after_initialize do
# We need this here because the test env file loads before the Spree engine is loaded
Spree::Core::Engine.routes.default_url_options[:host] = ENV["SITE_URL"] if Rails.env == 'test'
end
# We reload the routes here
# so that the appended/prepended routes are available to the application.
config.after_initialize do
Rails.application.routes_reloader.reload!
end
initializer "spree.environment", before: :load_config_initializers do |app|
app.config.spree = Spree::Core::Environment.new
Spree::Config = app.config.spree.preferences # legacy access
end
initializer "spree.register.payment_methods" do |app|
app.config.spree.payment_methods = [
Spree::Gateway::Bogus,
Spree::Gateway::BogusSimple,
Spree::PaymentMethod::Check
]
end
initializer "spree.mail.settings" do |_app|
Spree::Core::MailSettings.init
Mail.register_interceptor(Spree::Core::MailInterceptor)
end
# filter sensitive information during logging
initializer "spree.params.filter" do |app|
app.config.filter_parameters += [
:password,
:password_confirmation,
:number,
:verification_value
]
end
# Settings dependent on locale
#
# We need to set this config before the promo environment gets loaded and
# after the spree environment gets loaded...
# This is because Spree uses `Spree::Config` while evaluating classes :scream:
#
# https://github.com/spree/spree/blob/2-0-stable/core/app/models/spree/calculator/per_item.rb#L6
#
# TODO: move back to spree initializer once we upgrade to a more recent version
# of Spree
initializer 'ofn.spree_locale_settings', before: 'spree.promo.environment' do |app|
Spree::Config['checkout_zone'] = ENV['CHECKOUT_ZONE']
Spree::Config['currency'] = ENV['CURRENCY']
end
# Register Spree calculators
Rails.application.reloader.to_prepare do
app = Openfoodnetwork::Application
app.config.spree.calculators.shipping_methods = [
Calculator::FlatPercentItemTotal,
Calculator::FlatRate,
Calculator::FlexiRate,
Calculator::PerItem,
Calculator::PriceSack,
Calculator::Weight
]
app.config.spree.calculators.add_class('enterprise_fees')
app.config.spree.calculators.enterprise_fees = [
Calculator::FlatPercentPerItem,
Calculator::FlatRate,
Calculator::FlexiRate,
Calculator::PerItem,
Calculator::PriceSack,
Calculator::Weight
]
app.config.spree.calculators.add_class('payment_methods')
app.config.spree.calculators.payment_methods = [
Calculator::FlatPercentItemTotal,
Calculator::FlatRate,
Calculator::FlexiRate,
Calculator::PerItem,
Calculator::PriceSack
]
app.config.spree.calculators.add_class('tax_rates')
app.config.spree.calculators.tax_rates = [
Calculator::DefaultTax
]
end
# Register Spree payment methods
initializer "spree.gateway.payment_methods", :after => "spree.register.payment_methods" do |app|
app.config.spree.payment_methods << Spree::Gateway::StripeConnect
app.config.spree.payment_methods << Spree::Gateway::StripeSCA
app.config.spree.payment_methods << Spree::Gateway::PayPalExpress
end
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(
#{config.root}/app/models/concerns
#{config.root}/app/presenters
#{config.root}/app/jobs
)
initializer "ofn.reports" do |app|
module ::Reporting; end
loader = Zeitwerk::Loader.new
loader.push_dir("#{Rails.root}/lib/reporting", namespace: ::Reporting)
loader.enable_reloading
loader.setup
loader.eager_load
if Rails.env.development?
require 'listen'
Listen.to("lib/reporting") { loader.reload }.start
end
end
config.paths["config/routes.rb"] = %w(
config/routes/api.rb
config/routes.rb
config/routes/admin.rb
config/routes/spree.rb
).map { |relative_path| Rails.root.join(relative_path) }
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = ENV["TIMEZONE"]
# 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 = OpenFoodNetwork::I18nConfig.default_locale
config.i18n.available_locales = OpenFoodNetwork::I18nConfig.available_locales
I18n.locale = config.i18n.locale = config.i18n.default_locale
# Setting this to true causes a performance regression in Rails 3.2.17
# When we're on a version with the fix below, we can set it to true
# https://github.com/svenfuchs/i18n/issues/230
I18n.config.enforce_available_locales = false
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.2'
config.sass.load_paths += [
"#{Gem.loaded_specs['foundation-rails'].full_gem_path}/vendor/assets/stylesheets/foundation/components",
"#{Gem.loaded_specs['foundation-rails'].full_gem_path}/vendor/assets/stylesheets/foundation/"
]
# css and js files other than application.* are not precompiled by default
# Instead, they must be explicitly included below
# http://stackoverflow.com/questions/8012434/what-is-the-purpose-of-config-assets-precompile
config.assets.initialize_on_precompile = true
config.assets.precompile += ['iehack.js']
config.assets.precompile += ['admin/all.css', 'admin/*.js', 'admin/**/*.js']
config.assets.precompile += ['web/all.css', 'web/all.js']
config.assets.precompile += ['darkswarm/all.css', 'darkswarm/all.js']
config.assets.precompile += ['mail/all.css']
config.assets.precompile += ['shared/*']
config.assets.precompile += ['qz/*']
config.assets.precompile += ['*.jpg', '*.jpeg', '*.png', '*.gif' '*.svg']
config.active_support.escape_html_entities_in_json = true
config.active_job.queue_adapter = :sidekiq
config.action_controller.include_all_helpers = false
config.generators.template_engine = :haml
config.autoloader = :zeitwerk
config.action_view.form_with_generates_ids = true
end
end
Set default_url_options explicitly in all environments
require_relative 'boot'
require "rails"
[
"active_record/railtie",
#"active_storage/engine",
"action_controller/railtie",
"action_view/railtie",
"action_mailer/railtie",
"active_job/railtie",
"action_cable/engine",
#"action_mailbox/engine",
#"action_text/engine",
"rails/test_unit/railtie",
"sprockets/railtie" # Disable this after migrating to Webpacker
].each do |railtie|
begin
require railtie
rescue LoadError
end
end
require_relative "../lib/open_food_network/i18n_config"
require_relative '../lib/spree/core/environment'
require_relative '../lib/spree/core/mail_interceptor'
require_relative "../lib/session_cookie_upgrader"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Openfoodnetwork
class Application < Rails::Application
config.middleware.insert_before(
ActionDispatch::Cookies,
SessionCookieUpgrader, {
old_key: "_session_id",
new_key: "_ofn_session_id",
domain: ".#{ENV['SITE_URL'].gsub(/^(www\.)|^(app\.)|^(staging\.)|^(stg\.)/, '')}"
}
) if Rails.env.staging? || Rails.env.production?
config.after_initialize do
# We need this here because the test env file loads before the Spree engine is loaded
Spree::Core::Engine.routes.default_url_options[:host] = ENV["SITE_URL"] if Rails.env == 'test'
end
# We reload the routes here
# so that the appended/prepended routes are available to the application.
config.after_initialize do
Rails.application.routes_reloader.reload!
end
initializer "spree.environment", before: :load_config_initializers do |app|
app.config.spree = Spree::Core::Environment.new
Spree::Config = app.config.spree.preferences # legacy access
end
initializer "spree.register.payment_methods" do |app|
app.config.spree.payment_methods = [
Spree::Gateway::Bogus,
Spree::Gateway::BogusSimple,
Spree::PaymentMethod::Check
]
end
initializer "spree.mail.settings" do |_app|
Spree::Core::MailSettings.init
Mail.register_interceptor(Spree::Core::MailInterceptor)
end
# filter sensitive information during logging
initializer "spree.params.filter" do |app|
app.config.filter_parameters += [
:password,
:password_confirmation,
:number,
:verification_value
]
end
# Settings dependent on locale
#
# We need to set this config before the promo environment gets loaded and
# after the spree environment gets loaded...
# This is because Spree uses `Spree::Config` while evaluating classes :scream:
#
# https://github.com/spree/spree/blob/2-0-stable/core/app/models/spree/calculator/per_item.rb#L6
#
# TODO: move back to spree initializer once we upgrade to a more recent version
# of Spree
initializer 'ofn.spree_locale_settings', before: 'spree.promo.environment' do |app|
Spree::Config['checkout_zone'] = ENV['CHECKOUT_ZONE']
Spree::Config['currency'] = ENV['CURRENCY']
end
# Register Spree calculators
Rails.application.reloader.to_prepare do
app = Openfoodnetwork::Application
app.config.spree.calculators.shipping_methods = [
Calculator::FlatPercentItemTotal,
Calculator::FlatRate,
Calculator::FlexiRate,
Calculator::PerItem,
Calculator::PriceSack,
Calculator::Weight
]
app.config.spree.calculators.add_class('enterprise_fees')
app.config.spree.calculators.enterprise_fees = [
Calculator::FlatPercentPerItem,
Calculator::FlatRate,
Calculator::FlexiRate,
Calculator::PerItem,
Calculator::PriceSack,
Calculator::Weight
]
app.config.spree.calculators.add_class('payment_methods')
app.config.spree.calculators.payment_methods = [
Calculator::FlatPercentItemTotal,
Calculator::FlatRate,
Calculator::FlexiRate,
Calculator::PerItem,
Calculator::PriceSack
]
app.config.spree.calculators.add_class('tax_rates')
app.config.spree.calculators.tax_rates = [
Calculator::DefaultTax
]
end
# Register Spree payment methods
initializer "spree.gateway.payment_methods", :after => "spree.register.payment_methods" do |app|
app.config.spree.payment_methods << Spree::Gateway::StripeConnect
app.config.spree.payment_methods << Spree::Gateway::StripeSCA
app.config.spree.payment_methods << Spree::Gateway::PayPalExpress
end
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(
#{config.root}/app/models/concerns
#{config.root}/app/presenters
#{config.root}/app/jobs
)
initializer "ofn.reports" do |app|
module ::Reporting; end
loader = Zeitwerk::Loader.new
loader.push_dir("#{Rails.root}/lib/reporting", namespace: ::Reporting)
loader.enable_reloading
loader.setup
loader.eager_load
if Rails.env.development?
require 'listen'
Listen.to("lib/reporting") { loader.reload }.start
end
end
config.paths["config/routes.rb"] = %w(
config/routes/api.rb
config/routes.rb
config/routes/admin.rb
config/routes/spree.rb
).map { |relative_path| Rails.root.join(relative_path) }
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = ENV["TIMEZONE"]
# 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 = OpenFoodNetwork::I18nConfig.default_locale
config.i18n.available_locales = OpenFoodNetwork::I18nConfig.available_locales
I18n.locale = config.i18n.locale = config.i18n.default_locale
# Setting this to true causes a performance regression in Rails 3.2.17
# When we're on a version with the fix below, we can set it to true
# https://github.com/svenfuchs/i18n/issues/230
I18n.config.enforce_available_locales = false
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.2'
config.sass.load_paths += [
"#{Gem.loaded_specs['foundation-rails'].full_gem_path}/vendor/assets/stylesheets/foundation/components",
"#{Gem.loaded_specs['foundation-rails'].full_gem_path}/vendor/assets/stylesheets/foundation/"
]
# css and js files other than application.* are not precompiled by default
# Instead, they must be explicitly included below
# http://stackoverflow.com/questions/8012434/what-is-the-purpose-of-config-assets-precompile
config.assets.initialize_on_precompile = true
config.assets.precompile += ['iehack.js']
config.assets.precompile += ['admin/all.css', 'admin/*.js', 'admin/**/*.js']
config.assets.precompile += ['web/all.css', 'web/all.js']
config.assets.precompile += ['darkswarm/all.css', 'darkswarm/all.js']
config.assets.precompile += ['mail/all.css']
config.assets.precompile += ['shared/*']
config.assets.precompile += ['qz/*']
config.assets.precompile += ['*.jpg', '*.jpeg', '*.png', '*.gif' '*.svg']
config.active_support.escape_html_entities_in_json = true
config.active_job.queue_adapter = :sidekiq
config.action_controller.include_all_helpers = false
config.generators.template_engine = :haml
Rails.application.routes.default_url_options[:host] = ENV["SITE_URL"]
config.autoloader = :zeitwerk
config.action_view.form_with_generates_ids = true
end
end
|
require_relative "boot"
require "action_controller/railtie"
require "rails/test_unit/railtie"
require "sprockets/railtie"
require "action_mailer/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Frontend
class Application < Rails::Application
require "frontend"
config.load_defaults 6.0
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = "London"
# Custom directories with classes and modules you want to be autoloadable.
config.eager_load_paths += %W[#{config.root}/app/presenters #{config.root}/lib]
# 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 = :en
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Enable the asset pipeline
config.assets.enabled = true
config.assets.precompile += %w[
views/travel-advice.js
frontend.js
tour.js
application.css
application-ie6.css
application-ie7.css
application-ie8.css
print.css
]
# Path within public/ where assets are compiled to
config.assets.prefix = "/assets/frontend"
# allow overriding the asset host with an enironment variable, useful for
# when router is proxying to this app but asset proxying isn't set up.
config.asset_host = ENV["ASSET_HOST"]
# Paths used by helpers when generating links to assets
config.action_controller.assets_dir = Rails.root.join "public/frontend"
config.action_controller.javascripts_dir = Rails.root.join "public/frontend/javascripts"
config.action_controller.stylesheets_dir = Rails.root.join "public/frontend/stylesheets"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += %i[password postcode]
# Disable Rack::Cache
config.action_dispatch.rack_cache = nil
# Disable Content Negotiation
config.action_dispatch.ignore_accept_header = true
# Override Rails 4 default which restricts framing to SAMEORIGIN.
config.action_dispatch.default_headers = {
"X-Frame-Options" => "ALLOWALL",
}
config.action_controller.allow_forgery_protection = false
config.active_job.queue_adapter = :sidekiq
# 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.
end
end
Remove unnecessary configuration
This configuration doesn't seem to have any effect (hopefully not famous
last words), no other GOV.UK apps seem to have it. It seems to date back
9 years so I think it's just an artefact that was once needed but now
doesn't seem to do anything.
require_relative "boot"
require "action_controller/railtie"
require "rails/test_unit/railtie"
require "sprockets/railtie"
require "action_mailer/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Frontend
class Application < Rails::Application
require "frontend"
config.load_defaults 6.0
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = "London"
# Custom directories with classes and modules you want to be autoloadable.
config.eager_load_paths += %W[#{config.root}/app/presenters #{config.root}/lib]
# 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 = :en
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Enable the asset pipeline
config.assets.enabled = true
config.assets.precompile += %w[
views/travel-advice.js
frontend.js
tour.js
application.css
application-ie6.css
application-ie7.css
application-ie8.css
print.css
]
# Path within public/ where assets are compiled to
config.assets.prefix = "/assets/frontend"
# allow overriding the asset host with an enironment variable, useful for
# when router is proxying to this app but asset proxying isn't set up.
config.asset_host = ENV["ASSET_HOST"]
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += %i[password postcode]
# Disable Rack::Cache
config.action_dispatch.rack_cache = nil
# Disable Content Negotiation
config.action_dispatch.ignore_accept_header = true
# Override Rails 4 default which restricts framing to SAMEORIGIN.
config.action_dispatch.default_headers = {
"X-Frame-Options" => "ALLOWALL",
}
config.action_controller.allow_forgery_protection = false
config.active_job.queue_adapter = :sidekiq
# 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.
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module AlmReport
class Application < Rails::Application
require "/vagrant/config/initializers/bower_rails.rb"
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths << Rails.root.join('lib')
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
end
end
Remove manual (and absolute path require for bower_rails)
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module AlmReport
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths << Rails.root.join('lib')
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
config.assets.initialize_on_precompile = false
module Calagator
class Application < Rails::Application
#---[ Libraries ]-------------------------------------------------------
# Gems are packaged in "Gemfile", run `bundle` to install them.
# Standard libraries
require 'fileutils'
require 'net/http'
require 'net/https'
require 'open-uri'
require 'set'
require 'uri'
# Bundled libraries
$LOAD_PATH << Rails.root.join('vendor','gems','lucene_query-0.1','lib')
require 'lucene_query'
$LOAD_PATH << Rails.root.join('vendor','gems','mofo-0.2.8','lib')
require 'mofo'
# Load from "/lib"
$LOAD_PATH << Rails.root.join('lib')
### libraries
require 'metaclass'
require 'tag_model_extensions'
### monkeypatches
require 'ext/nil_strip_html'
require 'ext/object_logit'
require 'ext/time_today'
require 'ext/time_get_zone'
# Adds Array#paginate
require 'will_paginate/array'
#---[ Plugins ]---------------------------------------------------------
# Load these plugins first, or they won't work
config.plugins = [
:catch_cookie_exception,
:exception_notification,
]
#---[ Path -------------------------------------------------------------
config.autoload_paths += [
# App
Rails.root.join('app','mixins'),
Rails.root.join('app','observers'),
# Plugins
Rails.root.join('lib','catch_cookie_exception', 'lib'),
Rails.root.join('lib','exception_notification', 'lib'),
Rails.root.join('lib','has_many_polymorphs', 'lib'),
Rails.root.join('lib','gmaps_on_rails', 'lib'),
Rails.root.join('lib')
]
#---[ Rails ]-----------------------------------------------------------
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
config.active_record.observers = :cache_observer
# Deliver email using sendmail by default
config.action_mailer.delivery_method = :sendmail
config.action_mailer.sendmail_settings = { :arguments => '-i' }
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
config.i18n.enforce_available_locales = true
#---[ Caching ]---------------------------------------------------------
cache_path = Rails.root.join('tmp','cache',Rails.env)
config.cache_store = :file_store, cache_path
FileUtils.mkdir_p(cache_path)
#---[ Asset Pipeline ]--------------------------------------------------
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.assets.precompile += ["leaflet_google_layer.js"]
#---[ Secrets and settings ]--------------------------------------------
config.before_initialize do
# Read secrets
require 'secrets_reader'
::SECRETS = SecretsReader.read
# Read theme
require 'theme_reader'
::THEME_NAME = ThemeReader.read
Kernel.class_eval do
def theme_file(filename)
return Rails.root.join('themes',THEME_NAME,filename)
end
end
# Read theme settings
require 'settings_reader'
::SETTINGS = SettingsReader.read(
theme_file("settings.yml"), {
'timezone' => 'Pacific Time (US & Canada)',
}
)
# Set timezone for Rails
config.time_zone = SETTINGS.timezone
# Set cookie session
config.session_store :cookie_store, :key => SECRETS.session_name || "calagator"
config.secret_token = SECRETS.session_secret
# Activate search engine
require 'search_engine'
SearchEngine.kind = Rails.env.test? ? "sql" : SECRETS.search_engine
end
# Set timezone for OS
config.after_initialize do
ENV['TZ'] = Time.zone.tzinfo.identifier
end
end
end
fixed config placement in application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Calagator
class Application < Rails::Application
#---[ Libraries ]-------------------------------------------------------
# Gems are packaged in "Gemfile", run `bundle` to install them.
# Standard libraries
require 'fileutils'
require 'net/http'
require 'net/https'
require 'open-uri'
require 'set'
require 'uri'
# Bundled libraries
$LOAD_PATH << Rails.root.join('vendor','gems','lucene_query-0.1','lib')
require 'lucene_query'
$LOAD_PATH << Rails.root.join('vendor','gems','mofo-0.2.8','lib')
require 'mofo'
# Load from "/lib"
$LOAD_PATH << Rails.root.join('lib')
### libraries
require 'metaclass'
require 'tag_model_extensions'
### monkeypatches
require 'ext/nil_strip_html'
require 'ext/object_logit'
require 'ext/time_today'
require 'ext/time_get_zone'
# Adds Array#paginate
require 'will_paginate/array'
#---[ Plugins ]---------------------------------------------------------
config.assets.initialize_on_precompile = false
# Load these plugins first, or they won't work
config.plugins = [
:catch_cookie_exception,
:exception_notification,
]
#---[ Path -------------------------------------------------------------
config.autoload_paths += [
# App
Rails.root.join('app','mixins'),
Rails.root.join('app','observers'),
# Plugins
Rails.root.join('lib','catch_cookie_exception', 'lib'),
Rails.root.join('lib','exception_notification', 'lib'),
Rails.root.join('lib','has_many_polymorphs', 'lib'),
Rails.root.join('lib','gmaps_on_rails', 'lib'),
Rails.root.join('lib')
]
#---[ Rails ]-----------------------------------------------------------
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
config.active_record.observers = :cache_observer
# Deliver email using sendmail by default
config.action_mailer.delivery_method = :sendmail
config.action_mailer.sendmail_settings = { :arguments => '-i' }
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
config.i18n.enforce_available_locales = true
#---[ Caching ]---------------------------------------------------------
cache_path = Rails.root.join('tmp','cache',Rails.env)
config.cache_store = :file_store, cache_path
FileUtils.mkdir_p(cache_path)
#---[ Asset Pipeline ]--------------------------------------------------
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.assets.precompile += ["leaflet_google_layer.js"]
#---[ Secrets and settings ]--------------------------------------------
config.before_initialize do
# Read secrets
require 'secrets_reader'
::SECRETS = SecretsReader.read
# Read theme
require 'theme_reader'
::THEME_NAME = ThemeReader.read
Kernel.class_eval do
def theme_file(filename)
return Rails.root.join('themes',THEME_NAME,filename)
end
end
# Read theme settings
require 'settings_reader'
::SETTINGS = SettingsReader.read(
theme_file("settings.yml"), {
'timezone' => 'Pacific Time (US & Canada)',
}
)
# Set timezone for Rails
config.time_zone = SETTINGS.timezone
# Set cookie session
config.session_store :cookie_store, :key => SECRETS.session_name || "calagator"
config.secret_token = SECRETS.session_secret
# Activate search engine
require 'search_engine'
SearchEngine.kind = Rails.env.test? ? "sql" : SECRETS.search_engine
end
# Set timezone for OS
config.after_initialize do
ENV['TZ'] = Time.zone.tzinfo.identifier
end
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Littlegreenmen
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# Include generated in static assets to be served
config.assets.enabled = true
config.assets.path = Rails.root.join('doc')
end
end
Revert "Enable asset pipeline"
This reverts commit fa5bfa5f7a712cc8d62b98a252f4b2ac9eed5b64.
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Littlegreenmen
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# Include generated in static assets to be served
config.assets.path = Rails.root.join('doc')
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require_relative '../lib/mumuki/laboratory'
Bundler.require(*Rails.groups)
module Mumuki
class Application < Rails::Application
config.load_defaults 5.1
config.generators.stylesheets = false
config.generators.javascripts = false
config.generators.test_framework = :rspec
config.autoload_paths += %W(#{config.root}/plugins)
config.autoload_paths += %W(#{config.root}/app/helpers/concerns)
%w(evaluation exercise submission status).each do |it|
config.autoload_paths += %W(#{config.root}/app/models/#{it})
end
%w(submittable navigation).each do |it|
config.autoload_paths += %W(#{config.root}/app/models/concerns/#{it})
end
config.registration_notification_format = {only: [:id, :name, :email, :image_url]}
config.action_dispatch.perform_deep_munge = false
end
end
change autoload paths order
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require_relative '../lib/mumuki/laboratory'
Bundler.require(*Rails.groups)
module Mumuki
class Application < Rails::Application
config.load_defaults 5.1
config.generators.stylesheets = false
config.generators.javascripts = false
config.generators.test_framework = :rspec
config.autoload_paths += %W(#{config.root}/plugins)
config.autoload_paths += %W(#{config.root}/app/helpers/concerns)
%w(status evaluation exercise submission).each do |it|
config.autoload_paths += %W(#{config.root}/app/models/#{it})
end
%w(submittable navigation).each do |it|
config.autoload_paths += %W(#{config.root}/app/models/concerns/#{it})
end
config.registration_notification_format = {only: [:id, :name, :email, :image_url]}
config.action_dispatch.perform_deep_munge = false
end
end
|
require File.expand_path('../boot', __FILE__)
require "action_controller/railtie"
require "sprockets/railtie"
if defined?(Bundler)
Bundler.require(:default, Rails.env)
end
module AssetsContainer
class Application < Rails::Application
config.time_zone = 'Stockholm'
config.i18n.default_locale = :en
I18n.config.enforce_available_locales = true
config.encoding = "utf-8"
config.filter_parameters += [:password]
config.autoload_paths += %w( lib/**/ )
config.assets.enabled = true
config.assets.version = '1.0'
config.assets.precompile += %w(
*.png *.jpg *.jpeg *.gif *.eot *.svg *.ttf *.woff *.map
malmo.js
malmo.css
malmo_without_jquery.js
masthead_standalone.css
masthead_standalone.js
masthead_standalone_without_jquery.js
google_analytics.js
html5shiv-printshiv.js
legacy/ie8.css
icons.data.svg.css
icons.data.png.css
icons.fallback.css
portwise.css
)
config.assets.paths += [
Rails.root.join("assets", "icons").to_s,
Rails.root.join("vendor", "malmo_shared_assets", "stylesheets").to_s,
Rails.root.join("vendor", "malmo_shared_assets", "stylesheets", "shared").to_s,
Rails.root.join("vendor", "malmo_shared_assets", "stylesheets", "external").to_s,
Rails.root.join("vendor", "malmo_shared_assets", "stylesheets", "internal").to_s
]
end
end
require 'asset_utils'
AssetsContainer::Application.config.secret_token = 'Not_used_in_this_app_but_required_by_rails'
AssetsContainer::Application.config.secret_key_base = 'Not_used_in_this_app_but_required_by_rails'
Removed require for assets_utils
require File.expand_path('../boot', __FILE__)
require "action_controller/railtie"
require "sprockets/railtie"
if defined?(Bundler)
Bundler.require(:default, Rails.env)
end
module AssetsContainer
class Application < Rails::Application
config.time_zone = 'Stockholm'
config.i18n.default_locale = :en
I18n.config.enforce_available_locales = true
config.encoding = "utf-8"
config.filter_parameters += [:password]
config.autoload_paths += %w( lib/**/ )
config.assets.enabled = true
config.assets.version = '1.0'
config.assets.precompile += %w(
*.png *.jpg *.jpeg *.gif *.eot *.svg *.ttf *.woff *.map
malmo.js
malmo.css
malmo_without_jquery.js
masthead_standalone.css
masthead_standalone.js
masthead_standalone_without_jquery.js
google_analytics.js
html5shiv-printshiv.js
legacy/ie8.css
icons.data.svg.css
icons.data.png.css
icons.fallback.css
portwise.css
)
config.assets.paths += [
Rails.root.join("assets", "icons").to_s,
Rails.root.join("vendor", "malmo_shared_assets", "stylesheets").to_s,
Rails.root.join("vendor", "malmo_shared_assets", "stylesheets", "shared").to_s,
Rails.root.join("vendor", "malmo_shared_assets", "stylesheets", "external").to_s,
Rails.root.join("vendor", "malmo_shared_assets", "stylesheets", "internal").to_s
]
end
end
AssetsContainer::Application.config.secret_token = 'Not_used_in_this_app_but_required_by_rails'
AssetsContainer::Application.config.secret_key_base = 'Not_used_in_this_app_but_required_by_rails'
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
module Rnplay
class Application < Rails::Application
config.active_record.raise_in_transactional_callbacks = true
config.action_mailer.delivery_method = :postmark
config.action_mailer.postmark_settings = { :api_token => ENV['POSTMARK_KEY'] }
config.active_job.queue_adapter = :sidekiq
config.react.addons = true
config.react.jsx_transform_options = {
harmony: true
}
# If we do not use this then render json: .. will escape & in urls and break
# the app qr code action
config.active_support.escape_html_entities_in_json = false
config.assets.precompile += %w( editor_sprockets.js )
config.middleware.insert_before 0, "Rack::Cors", :debug => true, :logger => (-> { Rails.logger }) do
allow do
origins '*'
resource '/cors',
:headers => :any,
:methods => [:post],
:credentials => true,
:max_age => 0
resource '*',
:headers => :any,
:methods => [:get, :post, :delete, :put, :options, :head],
:max_age => 0
end
end
end
end
no harmony option for iojs
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
module Rnplay
class Application < Rails::Application
config.active_record.raise_in_transactional_callbacks = true
config.action_mailer.delivery_method = :postmark
config.action_mailer.postmark_settings = { :api_token => ENV['POSTMARK_KEY'] }
config.active_job.queue_adapter = :sidekiq
config.react.addons = true
# If we do not use this then render json: .. will escape & in urls and break
# the app qr code action
config.active_support.escape_html_entities_in_json = false
config.assets.precompile += %w( editor_sprockets.js )
config.middleware.insert_before 0, "Rack::Cors", :debug => true, :logger => (-> { Rails.logger }) do
allow do
origins '*'
resource '/cors',
:headers => :any,
:methods => [:post],
:credentials => true,
:max_age => 0
resource '*',
:headers => :any,
:methods => [:get, :post, :delete, :put, :options, :head],
:max_age => 0
end
end
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'socket'
require 'sprockets'
require 'resolv'
require 'uri'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
Bundler.require *Rails.groups(:assets => %w(development, test))
module ScholarSphere
class Application < Rails::Application
# Returns an array containing the vhost 'CoSign service' value and URL
def get_vhost_by_host
hostname = Socket.gethostname
vhost = Rails.application.config.hosts_vhosts_map[hostname] || "https://#{hostname}/"
service = URI.parse(vhost).host
port = URI.parse(vhost).port
service << "-#{port}" unless port == 443
return [service, vhost]
end
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.fits_path = 'fits.sh'
config.max_days_between_audits = 7
config.id_namespace = "scholarsphere"
config.application_name = "ScholarSphere"
config.persistent_hostpath = "http://scholarsphere.psu.edu/files/"
# turning on the new asset pipeline for handling javascript, css, and image files
config.assets.enabled = true
config.assets.paths << '#{Rails.root}/app/assets/javascripts'
config.assets.paths << '#{Rails.root}/app/assets/stylesheets'
config.assets.paths << '#{Rails.root}/app/assets/images'
config.assets.paths << '#{Rails.root}/lib/assets/javascripts'
config.assets.paths << '#{Rails.root}/lib/assets/stylesheets'
config.assets.paths << '#{Rails.root}/lib/assets/images'
config.assets.paths << '#{Rails.root}/vendor/assets/javascripts'
config.assets.paths << '#{Rails.root}/vendor/assets/images'
config.assets.paths << '#{Rails.root}/vendor/assets/fonts'
# email to send on contact form - probably need one for the production
# environment
config.contact_email = 'DLT-GAMMA-PROJECT@lists.psu.edu'
config.fits_to_desc_mapping = {
:file_title => :title,
:file_author => :creator,
:file_language => :language
}
# Map hostnames onto Google Analytics tracking IDs
config.ga_host_map = {
'scholarsphere-test.dlt.psu.edu' => 'UA-33252017-1',
'scholarsphere.psu.edu' => 'UA-33252017-2',
}
# Map hostnames onto vhosts
config.hosts_vhosts_map = {
'fedora1test' => 'https://scholarsphere-integration.dlt.psu.edu:8443/',
'fedora2test' => 'https://scholarsphere-test.dlt.psu.edu/',
'ss1stage' => 'https://scholarsphere-staging.dlt.psu.edu/',
'ss2stage' => 'https://scholarsphere-staging.dlt.psu.edu/',
'ss1prod' => 'https://scholarsphere.psu.edu/',
'ss2prod' => 'https://scholarsphere.psu.edu/'
}
config.resource_types = {
"Article"=>"Article",
"Multimedia"=>"Multimedia",
"Conference Proceeding"=> "Conference Proceeding",
"Data Set"=>"Data Set",
"Image"=>"Image",
"Thesis"=>"Thesis",
"Other"=>"Other"
}
config.public_permission_levels = {
"Choose Access"=>"none",
"View/Download" => "read"
}
config.permission_levels = {
"Choose Access"=>"none",
"View/Download" => "read",
"Edit" => "edit"
}
config.owner_permission_levels = {
"Edit" => "edit"
}
config.cc_licenses = {
'No license specified' => 'No license specified',
'Attribution 3.0 United States' => 'http://creativecommons.org/licenses/by/3.0/us/',
'Attribution-ShareAlike 3.0 United States' => 'http://creativecommons.org/licenses/by-sa/3.0/us/',
'Attribution-NonCommercial 3.0 United States' => 'http://creativecommons.org/licenses/by-nc/3.0/us/',
'Attribution-NoDerivs 3.0 United States' => 'http://creativecommons.org/licenses/by-nd/3.0/us/',
'Attribution-NonCommercial-NoDerivs 3.0 United States' => 'http://creativecommons.org/licenses/by-nc-nd/3.0/us/',
'Attribution-NonCommercial-ShareAlike 3.0 United States' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/us/',
'Public Domain Mark 1.0' => 'http://creativecommons.org/publicdomain/mark/1.0/',
'CC0 1.0 Universal' => 'http://creativecommons.org/publicdomain/zero/1.0/',
'All rights reserved' => 'All rights reserved'
}
# help text to display for form metadata elements, these will need to be updated to
# reflect a field name change (should one happen) in the generic file datastream
config.metadata_help = {
"generic_file_resource_type" => "The type of resource this file is in ScholarSphere.",
"generic_file_title" => "The title of the object being uploaded to ScholarSphere.",
"generic_file_tag" => "Keywords, or tags, that describe the object.",
"generic_file_subject" => "If you would like to align the description of your object with an existing vocabulary of subject terms, enter those here. ScholarSphere supports Library of Congress Subject Headings (LCSH). Begin typing a subject term and ScholarSphere will present you with a list of matching terms.",
"generic_file_creator" => "The name of a person or group primarily responsible for the creation of the object being uploaded.",
"generic_file_related_url" => "A URL about the object or the context in which it was created. Example: a link to the research project from which a data set was derived.",
"generic_file_based_near" => "A location that is relevant to where this file was created.",
"generic_file_contributor" => "A person or group that contributed to the object's existence, including schools, colleges, or institutes at Penn State, and funding agencies responsible for funding the research that produced the object.",
"generic_file_date_created" => "Date on which the object was created in its present form.",
"generic_file_description" => "A brief description, an abstract, or notes about relationships between this object and other objects to which it is related, providing extra context about the object.",
"generic_file_identifier" => "A unique handle identifying the object in an external context, e.g. if it has an ISBN, OCLC number, or similar identifying numbers or names.",
"generic_file_language" => "A language in which the object is expressed.",
"generic_file_publisher" => "An entity responsible for dissemination of the object.",
"generic_file_rights" => "A statement about the rights assigned to the object or a content license such as those provided by Creative Commons. Note that these are not automatically enforced by ScholarSphere, which considers rights, licensing, and access levels separate."
}
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += Dir["#{config.root}/app/models/**/"]
config.autoload_paths += Dir["#{config.root}/lib/**/"]
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
end
end
# this prevents LoadErrors, related to Rails autoload behavior
require 'scholarsphere/permissions'
require 'scholarsphere/id_service'
require 'scholarsphere/noidify'
require 'scholarsphere/model_methods'
require 'scholarsphere/role_mapper'
removes language from list of descriptive metadata elements that FITS auto-populates
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'socket'
require 'sprockets'
require 'resolv'
require 'uri'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
Bundler.require *Rails.groups(:assets => %w(development, test))
module ScholarSphere
class Application < Rails::Application
# Returns an array containing the vhost 'CoSign service' value and URL
def get_vhost_by_host
hostname = Socket.gethostname
vhost = Rails.application.config.hosts_vhosts_map[hostname] || "https://#{hostname}/"
service = URI.parse(vhost).host
port = URI.parse(vhost).port
service << "-#{port}" unless port == 443
return [service, vhost]
end
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.fits_path = 'fits.sh'
config.max_days_between_audits = 7
config.id_namespace = "scholarsphere"
config.application_name = "ScholarSphere"
config.persistent_hostpath = "http://scholarsphere.psu.edu/files/"
# turning on the new asset pipeline for handling javascript, css, and image files
config.assets.enabled = true
config.assets.paths << '#{Rails.root}/app/assets/javascripts'
config.assets.paths << '#{Rails.root}/app/assets/stylesheets'
config.assets.paths << '#{Rails.root}/app/assets/images'
config.assets.paths << '#{Rails.root}/lib/assets/javascripts'
config.assets.paths << '#{Rails.root}/lib/assets/stylesheets'
config.assets.paths << '#{Rails.root}/lib/assets/images'
config.assets.paths << '#{Rails.root}/vendor/assets/javascripts'
config.assets.paths << '#{Rails.root}/vendor/assets/images'
config.assets.paths << '#{Rails.root}/vendor/assets/fonts'
# email to send on contact form - probably need one for the production
# environment
config.contact_email = 'DLT-GAMMA-PROJECT@lists.psu.edu'
config.fits_to_desc_mapping = {
:file_title => :title,
:file_author => :creator
}
# Map hostnames onto Google Analytics tracking IDs
config.ga_host_map = {
'scholarsphere-test.dlt.psu.edu' => 'UA-33252017-1',
'scholarsphere.psu.edu' => 'UA-33252017-2',
}
# Map hostnames onto vhosts
config.hosts_vhosts_map = {
'fedora1test' => 'https://scholarsphere-integration.dlt.psu.edu:8443/',
'fedora2test' => 'https://scholarsphere-test.dlt.psu.edu/',
'ss1stage' => 'https://scholarsphere-staging.dlt.psu.edu/',
'ss2stage' => 'https://scholarsphere-staging.dlt.psu.edu/',
'ss1prod' => 'https://scholarsphere.psu.edu/',
'ss2prod' => 'https://scholarsphere.psu.edu/'
}
config.resource_types = {
"Article"=>"Article",
"Multimedia"=>"Multimedia",
"Conference Proceeding"=> "Conference Proceeding",
"Data Set"=>"Data Set",
"Image"=>"Image",
"Thesis"=>"Thesis",
"Other"=>"Other"
}
config.public_permission_levels = {
"Choose Access"=>"none",
"View/Download" => "read"
}
config.permission_levels = {
"Choose Access"=>"none",
"View/Download" => "read",
"Edit" => "edit"
}
config.owner_permission_levels = {
"Edit" => "edit"
}
config.cc_licenses = {
'No license specified' => 'No license specified',
'Attribution 3.0 United States' => 'http://creativecommons.org/licenses/by/3.0/us/',
'Attribution-ShareAlike 3.0 United States' => 'http://creativecommons.org/licenses/by-sa/3.0/us/',
'Attribution-NonCommercial 3.0 United States' => 'http://creativecommons.org/licenses/by-nc/3.0/us/',
'Attribution-NoDerivs 3.0 United States' => 'http://creativecommons.org/licenses/by-nd/3.0/us/',
'Attribution-NonCommercial-NoDerivs 3.0 United States' => 'http://creativecommons.org/licenses/by-nc-nd/3.0/us/',
'Attribution-NonCommercial-ShareAlike 3.0 United States' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/us/',
'Public Domain Mark 1.0' => 'http://creativecommons.org/publicdomain/mark/1.0/',
'CC0 1.0 Universal' => 'http://creativecommons.org/publicdomain/zero/1.0/',
'All rights reserved' => 'All rights reserved'
}
# help text to display for form metadata elements, these will need to be updated to
# reflect a field name change (should one happen) in the generic file datastream
config.metadata_help = {
"generic_file_resource_type" => "The type of resource this file is in ScholarSphere.",
"generic_file_title" => "The title of the object being uploaded to ScholarSphere.",
"generic_file_tag" => "Keywords, or tags, that describe the object.",
"generic_file_subject" => "If you would like to align the description of your object with an existing vocabulary of subject terms, enter those here. ScholarSphere supports Library of Congress Subject Headings (LCSH). Begin typing a subject term and ScholarSphere will present you with a list of matching terms.",
"generic_file_creator" => "The name of a person or group primarily responsible for the creation of the object being uploaded.",
"generic_file_related_url" => "A URL about the object or the context in which it was created. Example: a link to the research project from which a data set was derived.",
"generic_file_based_near" => "A location that is relevant to where this file was created.",
"generic_file_contributor" => "A person or group that contributed to the object's existence, including schools, colleges, or institutes at Penn State, and funding agencies responsible for funding the research that produced the object.",
"generic_file_date_created" => "Date on which the object was created in its present form.",
"generic_file_description" => "A brief description, an abstract, or notes about relationships between this object and other objects to which it is related, providing extra context about the object.",
"generic_file_identifier" => "A unique handle identifying the object in an external context, e.g. if it has an ISBN, OCLC number, or similar identifying numbers or names.",
"generic_file_language" => "A language in which the object is expressed.",
"generic_file_publisher" => "An entity responsible for dissemination of the object.",
"generic_file_rights" => "A statement about the rights assigned to the object or a content license such as those provided by Creative Commons. Note that these are not automatically enforced by ScholarSphere, which considers rights, licensing, and access levels separate."
}
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += Dir["#{config.root}/app/models/**/"]
config.autoload_paths += Dir["#{config.root}/lib/**/"]
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
end
end
# this prevents LoadErrors, related to Rails autoload behavior
require 'scholarsphere/permissions'
require 'scholarsphere/id_service'
require 'scholarsphere/noidify'
require 'scholarsphere/model_methods'
require 'scholarsphere/role_mapper'
|
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Haitatsu
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified
# here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is
# alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector,
# :forum_observer
# Set Time.zone default to the specified zone and make Active Record
# auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
# Default is UTC.
config.time_zone = 'CET'
# 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 = :en
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the
# database.
# This is necessary if your schema can't be completely dumped by the
# schema dumper, like if you have constraints or database-specific
# column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for
# mass-assignment for all models in your app. As such, your models will
# need to explicitly whitelist or blacklist accessible parameters by
# using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.sendit_url = ''
config.storeit_url = ''
config.reprintsdesk = ActiveSupport::OrderedOptions.new
c = config.reprintsdesk
c.wsdl = 'https://www.reprintsdesk.com/webservice/main.asmx?wsdl'
c.user = ''
c.password = ''
c.username = ''
c.firstname = ''
c.lastname = ''
c.companyname = ''
c.address1 = ''
c.address2 = ''
c.city = ''
c.zipcode = ''
c.statecode = '*'
c.statename = '*'
c.countrycode = ''
c.phone = '*'
c.fax = '*'
c.systemmail = ''
c.order_prefix = ''
# c.accounts = {
# 'group1' => {
# 'user' => '',
# 'password' => '',
# },
# 'group2' => {
# 'user' => '',
# 'password' => '',
# },
# 'default' => {
# 'user' => '',
# 'password' => '',
# },
# }
config.local_scan = ActiveSupport::OrderedOptions.new
c = config.local_scan
c.order_mail = ''
c.from_mail = ''
c.order_prefix = ''
c.handle_mails_from = ''
end
end
if File.exists? File.dirname(__FILE__) + '/../application.local.rb'
require File.dirname(__FILE__) + '/../application.local.rb'
end
Fixed relative load of application.local.rb.
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Haitatsu
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified
# here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is
# alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector,
# :forum_observer
# Set Time.zone default to the specified zone and make Active Record
# auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
# Default is UTC.
config.time_zone = 'CET'
# 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 = :en
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the
# database.
# This is necessary if your schema can't be completely dumped by the
# schema dumper, like if you have constraints or database-specific
# column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for
# mass-assignment for all models in your app. As such, your models will
# need to explicitly whitelist or blacklist accessible parameters by
# using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.sendit_url = ''
config.storeit_url = ''
config.reprintsdesk = ActiveSupport::OrderedOptions.new
c = config.reprintsdesk
c.wsdl = 'https://www.reprintsdesk.com/webservice/main.asmx?wsdl'
c.user = ''
c.password = ''
c.username = ''
c.firstname = ''
c.lastname = ''
c.companyname = ''
c.address1 = ''
c.address2 = ''
c.city = ''
c.zipcode = ''
c.statecode = '*'
c.statename = '*'
c.countrycode = ''
c.phone = '*'
c.fax = '*'
c.systemmail = ''
c.order_prefix = ''
# c.accounts = {
# 'group1' => {
# 'user' => '',
# 'password' => '',
# },
# 'group2' => {
# 'user' => '',
# 'password' => '',
# },
# 'default' => {
# 'user' => '',
# 'password' => '',
# },
# }
config.local_scan = ActiveSupport::OrderedOptions.new
c = config.local_scan
c.order_mail = ''
c.from_mail = ''
c.order_prefix = ''
c.handle_mails_from = ''
end
end
if File.exists? File.dirname(__FILE__) + '/application.local.rb'
require File.dirname(__FILE__) + '/application.local.rb'
end
|
#
# Copyright (c) 2016 by appPlant GmbH. All rights reserved.
#
# @APPPLANT_LICENSE_HEADER_START@
#
# This file contains Original Code and/or Modifications of Original Code
# as defined in and that are subject to the Apache License
# Version 2.0 (the 'License'). You may not use this file except in
# compliance with the License. Please obtain a copy of the License at
# http://opensource.org/licenses/Apache-2.0/ and read it before using this
# file.
#
# The Original Code and all software distributed under the License are
# distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
# EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
# INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
# Please see the License for the specific language governing rights and
# limitations under the License.
#
# @APPPLANT_LICENSE_HEADER_END@
opt! :help do
<<-USAGE
#{ISS::LOGO}
usage: iss [options...]
Options:
-e, --environment The environment to run the server with.
-h, --host The host to bind the local server on.
Defaults to: 0.0.0.0
-p, --port The port number to start the local server on.
Defaults to: 1974
-h, --help This help text
-v, --version Show version number
USAGE
end
opt! :version do
"v#{ISS::VERSION} - #{OS.sysname} #{OS.bits(:binary)}-Bit (#{OS.machine})"
end
opt :environment, 'development' do |env|
ENV['SHELF_ENV'] = env
end
opt :port, 1974 do |port|
set :port, port.to_i
end
opt :host, 'localhost' do |host|
set :host, host
end
Show iss in version line output
#
# Copyright (c) 2016 by appPlant GmbH. All rights reserved.
#
# @APPPLANT_LICENSE_HEADER_START@
#
# This file contains Original Code and/or Modifications of Original Code
# as defined in and that are subject to the Apache License
# Version 2.0 (the 'License'). You may not use this file except in
# compliance with the License. Please obtain a copy of the License at
# http://opensource.org/licenses/Apache-2.0/ and read it before using this
# file.
#
# The Original Code and all software distributed under the License are
# distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
# EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
# INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
# Please see the License for the specific language governing rights and
# limitations under the License.
#
# @APPPLANT_LICENSE_HEADER_END@
opt! :help do
<<-USAGE
#{ISS::LOGO}
usage: iss [options...]
Options:
-e, --environment The environment to run the server with.
-h, --host The host to bind the local server on.
Defaults to: 0.0.0.0
-p, --port The port number to start the local server on.
Defaults to: 1974
-h, --help This help text
-v, --version Show version number
USAGE
end
opt! :version do
"iss v#{ISS::VERSION} - #{OS.sysname} #{OS.bits(:binary)}-Bit (#{OS.machine})"
end
opt :environment, 'development' do |env|
ENV['SHELF_ENV'] = env
end
opt :port, 1974 do |port|
set :port, port.to_i
end
opt :host, 'localhost' do |host|
set :host, host
end
|
load 'deploy'
# =============================================================================
# TASKS
# =============================================================================
# Define tasks that run on all (or only some) of the machines. You can specify
# a role (or set of roles) that each task should be executed on. You can also
# narrow the set of servers to a subset of a role by specifying options, which
# must match the options given for the servers to select (like :primary => true)
namespace :webiva do
desc "Webiva Configuration Linking"
task :config do
run "rm -rf #{deploy.release_path}/config/sites"
run "ln -s #{deploy.shared_path}/config/sites #{deploy.release_path}/config/sites"
run "ln -s #{deploy.shared_path}/config/backup.yml #{deploy.release_path}/config/backup.yml; true"
run "ln -s #{deploy.shared_path}/config/cms.yml #{deploy.release_path}/config/cms.yml"
run "ln -s #{deploy.shared_path}/config/cms_migrator.yml #{deploy.release_path}/config/cms_migrator.yml"
run "ln -s #{deploy.shared_path}/config/defaults.yml #{deploy.release_path}/config/defaults.yml"
run "ln -s #{deploy.shared_path}/config/workling.yml #{deploy.release_path}/config/workling.yml"
end
desc "Custom Webiva Deployment"
task :server_deploy do
transaction do
deploy.update_code
modules_install
deploy.web.disable
config
run "cd #{deploy_to}/current; ./script/background.rb stop; true"
run "cd #{deploy.release_path}; rake gems:build"
deploy.symlink
run "cd #{deploy.release_path}; rake -f #{deploy.release_path}/Rakefile cms:migrate_system_db"
run "cd #{deploy.release_path}; rake -f #{deploy.release_path}/Rakefile cms:migrate_domain_dbs"
run "cd #{deploy.release_path}; rake -f #{deploy.release_path}/Rakefile cms:migrate_domain_components"
run "cd #{deploy_to}/current; ./script/background.rb start; true"
sudo "nohup /etc/init.d/memcached restart"
end
deploy.restart
deploy.web.enable
end
desc "Webiva Module deployment"
task :modules_install do
(webiva_modules||[]).each do |mod|
execute = []
execute << "cd #{deploy.release_path}/vendor/modules"
execute << "git clone #{module_repository}#{mod}.git #{mod.downcase}"
run execute.join(" && ")
end
end
desc "Webiva Setup Config"
task :setup do
transaction do
top.deploy.update_code
run "mkdir #{deploy.shared_path}; true"
run "mkdir #{deploy.shared_path}/log; true"
run "mkdir #{deploy.shared_path}/pids; true"
run "mkdir #{deploy.shared_path}/system; true"
run "mkdir #{deploy.shared_path}/config; true"
run "cp #{deploy.release_path}/config/cms.yml.example #{deploy.shared_path}/config/cms.yml; true"
run "cp #{deploy.release_path}/config/backup.yml.example #{deploy.shared_path}/config/backup.yml; true"
run "cp #{deploy.release_path}/config/cms_migrator.yml.example #{deploy.shared_path}/config/cms_migrator.yml; true"
run "cp #{deploy.release_path}/config/workling.yml.example #{deploy.shared_path}/config/workling.yml; true"
run "cp #{deploy.release_path}/config/defaults.yml.example #{deploy.shared_path}/config/defaults.yml; true"
run "mkdir #{deploy.shared_path}/config/sites; true"
config
deploy.symlink
end
end
end
namespace :deploy do
task :restart do
run "cd #{deploy_to}/current; touch tmp/restart.txt"
end
end
Fix undefined variable webiva_modules if deploying with no modules.
load 'deploy'
# =============================================================================
# TASKS
# =============================================================================
# Define tasks that run on all (or only some) of the machines. You can specify
# a role (or set of roles) that each task should be executed on. You can also
# narrow the set of servers to a subset of a role by specifying options, which
# must match the options given for the servers to select (like :primary => true)
namespace :webiva do
desc "Webiva Configuration Linking"
task :config do
run "rm -rf #{deploy.release_path}/config/sites"
run "ln -s #{deploy.shared_path}/config/sites #{deploy.release_path}/config/sites"
run "ln -s #{deploy.shared_path}/config/backup.yml #{deploy.release_path}/config/backup.yml; true"
run "ln -s #{deploy.shared_path}/config/cms.yml #{deploy.release_path}/config/cms.yml"
run "ln -s #{deploy.shared_path}/config/cms_migrator.yml #{deploy.release_path}/config/cms_migrator.yml"
run "ln -s #{deploy.shared_path}/config/defaults.yml #{deploy.release_path}/config/defaults.yml"
run "ln -s #{deploy.shared_path}/config/workling.yml #{deploy.release_path}/config/workling.yml"
end
desc "Custom Webiva Deployment"
task :server_deploy do
transaction do
deploy.update_code
modules_install
deploy.web.disable
config
run "cd #{deploy_to}/current; ./script/background.rb stop; true"
run "cd #{deploy.release_path}; rake gems:build"
deploy.symlink
run "cd #{deploy.release_path}; rake -f #{deploy.release_path}/Rakefile cms:migrate_system_db"
run "cd #{deploy.release_path}; rake -f #{deploy.release_path}/Rakefile cms:migrate_domain_dbs"
run "cd #{deploy.release_path}; rake -f #{deploy.release_path}/Rakefile cms:migrate_domain_components"
run "cd #{deploy_to}/current; ./script/background.rb start; true"
sudo "nohup /etc/init.d/memcached restart"
end
deploy.restart
deploy.web.enable
end
desc "Webiva Module deployment"
task :modules_install do
set :webiva_modules, [] if ! exists?(:webiva_modules)
(webiva_modules||[]).each do |mod|
execute = []
execute << "cd #{deploy.release_path}/vendor/modules"
execute << "git clone #{module_repository}#{mod}.git #{mod.downcase}"
run execute.join(" && ")
end
end
desc "Webiva Setup Config"
task :setup do
transaction do
top.deploy.update_code
run "mkdir #{deploy.shared_path}; true"
run "mkdir #{deploy.shared_path}/log; true"
run "mkdir #{deploy.shared_path}/pids; true"
run "mkdir #{deploy.shared_path}/system; true"
run "mkdir #{deploy.shared_path}/config; true"
run "cp #{deploy.release_path}/config/cms.yml.example #{deploy.shared_path}/config/cms.yml; true"
run "cp #{deploy.release_path}/config/backup.yml.example #{deploy.shared_path}/config/backup.yml; true"
run "cp #{deploy.release_path}/config/cms_migrator.yml.example #{deploy.shared_path}/config/cms_migrator.yml; true"
run "cp #{deploy.release_path}/config/workling.yml.example #{deploy.shared_path}/config/workling.yml; true"
run "cp #{deploy.release_path}/config/defaults.yml.example #{deploy.shared_path}/config/defaults.yml; true"
run "mkdir #{deploy.shared_path}/config/sites; true"
config
deploy.symlink
end
end
end
namespace :deploy do
task :restart do
run "cd #{deploy_to}/current; touch tmp/restart.txt"
end
end
|
# encoding: utf-8
require 'rspec/core'
require 'rspec/expectations'
require 'rspec/mocks'
# Unp includes reference to fgdb_splitter
require_relative '../../lib/importer/unp'
describe CartoDB::Importer2::FgdbSplitter do
before do
@multiple_layer_filepath = path_to('filegeodatabase.gdb')
@temporary_directory = '/var/tmp'
@ogr2ogr_config = {}
end
describe '#run' do
it 'splits a multilayer FGDB into single-layer FGDB' do
source_file = CartoDB::Importer2::SourceFile.new(@multiple_layer_filepath)
splitter = CartoDB::Importer2::FgdbSplitter.new(source_file, @temporary_directory, @ogr2ogr_config)
splitter.run
splitter.source_files.length.should eq 2
end
end
describe '#layers_in' do
it 'returns all layers name in the file' do
source_file = CartoDB::Importer2::SourceFile.new(@multiple_layer_filepath)
splitter = CartoDB::Importer2::FgdbSplitter.new(source_file, @temporary_directory, @ogr2ogr_config)
splitter.layers_in(source_file).length.should eq 2
splitter.layers_in(source_file).should eq ["pts", "lns"]
end
end
def path_to(filepath)
File.expand_path(
File.join(File.dirname(__FILE__), "../fixtures/#{filepath}")
)
end
end
Lame response to block size hound
# encoding: utf-8
require 'rspec/core'
require 'rspec/expectations'
require 'rspec/mocks'
# Unp includes reference to fgdb_splitter
require_relative '../../lib/importer/unp'
describe CartoDB::Importer2::FgdbSplitter do
before do
@multiple_layer_filepath = path_to('filegeodatabase.gdb')
@temporary_directory = '/var/tmp'
@ogr2ogr_config = {}
end
describe '#run' do
it 'splits a multilayer FGDB into single-layer FGDB' do
source_file = CartoDB::Importer2::SourceFile.new(@multiple_layer_filepath)
splitter = CartoDB::Importer2::FgdbSplitter.new(source_file, @temporary_directory, @ogr2ogr_config)
splitter.run
splitter.source_files.length.should eq 2
end
end
describe '#layers_in' do
it 'returns all layers name in the file' do
source_file = CartoDB::Importer2::SourceFile.new(@multiple_layer_filepath)
splitter = CartoDB::Importer2::FgdbSplitter.new(source_file, @temporary_directory, @ogr2ogr_config)
splitter.layers_in(source_file).length.should eq 2
splitter.layers_in(source_file).should eq ["pts", "lns"]
end
end
def path_to(filepath)
File.expand_path(File.join(File.dirname(__FILE__), "../fixtures/#{filepath}"))
end
end
|
class CreateUniqueIndexes < ActiveRecord::Migration
def self.up
add_index :repository_git_extras, :repository_id, unique: true
add_index :repository_git_notifications, :repository_id, unique: true
add_index :repository_git_config_keys, :repository_id
add_index :repository_git_config_keys, [:key, :repository_id], unique: true
add_index :repository_post_receive_urls, :repository_id
add_index :repository_post_receive_urls, [:url, :repository_id], unique: true
add_index :repository_mirrors, :repository_id
add_index :repository_mirrors, [:url, :repository_id], unique: true
add_index :repository_deployment_credentials, [:repository_id, :gitolite_public_key_id], unique: true, name: 'index_deployment_credentials_on_repository_id_and_public_key_id'
add_index :gitolite_public_keys, [:title, :user_id], unique: true
add_index :github_comments, [:github_id, :journal_id], unique: true
add_index :github_issues, [:github_id, :issue_id], unique: true
end
def self.down
remove_index :repository_git_extras, :repository_id
remove_index :repository_git_notifications, :repository_id
remove_index :repository_git_config_keys, :repository_id
remove_index :repository_git_config_keys, [:key, :repository_id]
remove_index :repository_post_receive_urls, :repository_id
remove_index :repository_post_receive_urls, [:url, :repository_id]
remove_index :repository_mirrors, :repository_id
remove_index :repository_mirrors, [:url, :repository_id]
remove_index :repository_deployment_credentials, name: 'index_deployment_credentials_on_repository_id_and_public_key_id'
remove_index :gitolite_public_keys, [:title, :user_id]
remove_index :github_comments, [:github_id, :journal_id]
remove_index :github_issues, [:github_id, :issue_id]
end
end
Fix https://github.com/jbox-web/redmine_git_hosting/issues/524
class CreateUniqueIndexes < ActiveRecord::Migration
def self.up
add_index :repository_git_extras, :repository_id, unique: true
add_index :repository_git_notifications, :repository_id, unique: true
add_index :repository_git_config_keys, :repository_id
add_index :repository_git_config_keys, [:key, :repository_id], unique: true
add_index :repository_post_receive_urls, :repository_id
add_index :repository_post_receive_urls, [:url, :repository_id], unique: true
add_index :repository_mirrors, :repository_id
add_index :repository_mirrors, [:url, :repository_id], unique: true
add_index :repository_deployment_credentials, [:repository_id, :gitolite_public_key_id], unique: true, name: 'index_deployment_credentials_on_repo_id_and_public_key_id'
add_index :gitolite_public_keys, [:title, :user_id], unique: true
add_index :github_comments, [:github_id, :journal_id], unique: true
add_index :github_issues, [:github_id, :issue_id], unique: true
end
def self.down
remove_index :repository_git_extras, :repository_id
remove_index :repository_git_notifications, :repository_id
remove_index :repository_git_config_keys, :repository_id
remove_index :repository_git_config_keys, [:key, :repository_id]
remove_index :repository_post_receive_urls, :repository_id
remove_index :repository_post_receive_urls, [:url, :repository_id]
remove_index :repository_mirrors, :repository_id
remove_index :repository_mirrors, [:url, :repository_id]
remove_index :repository_deployment_credentials, name: 'index_deployment_credentials_on_repo_id_and_public_key_id'
remove_index :gitolite_public_keys, [:title, :user_id]
remove_index :github_comments, [:github_id, :journal_id]
remove_index :github_issues, [:github_id, :issue_id]
end
end
|
class AddPrimaryToGroups < ActiveRecord::Migration
def up
add_column :groups, :primary, :boolean, default: false, null: false
Threadable::Transactions.in_migration = true
threadable = Threadable.new(threadable_env)
threadable.organizations.all.each do |organization|
attributes = {
name: organization.name,
subject_tag: organization.subject_tag,
email_address_tag: organization.email_address_username,
auto_join: false,
primary: true,
color: '#7f8c8d',
}
group = organization.groups.create(attributes)
organization.members.all.each do |member|
next if member.ungrouped_mail_delivery == 0
membership = group.members.add member, send_notice: false
if member.ungrouped_mail_delivery == 2
membership.gets_in_summary!
end
end
group.update(auto_join: true)
# now move mail
organization.conversations.ungrouped.each do |conversation|
conversation.groups.add group
end
puts organization.name
end
end
def down
Threadable::Transactions.in_migration = true
threadable = Threadable.new(threadable_env)
Group.where(primary: true).each do |group_record|
group = Threadable::Group.new(threadable, group_record)
conversations = group.conversations.all
group_record.destroy
conversations.each(&:update_group_caches!)
puts group.organization.name
end
remove_column :groups, :primary
end
def threadable_env
{
host: Rails.application.config.default_host,
port: Rails.application.config.default_port,
protocol: Rails.application.config.default_protocol,
worker: true,
}
end
end
fixed the primary group migration
class AddPrimaryToGroups < ActiveRecord::Migration
def up
add_column :groups, :primary, :boolean, default: false, null: false
Threadable::Transactions.in_migration = true
threadable = Threadable.new(threadable_env)
threadable.organizations.all.each do |organization|
attributes = {
name: organization.name,
subject_tag: organization.subject_tag,
email_address_tag: organization.email_address_username,
auto_join: false,
primary: true,
color: '#7f8c8d',
}
group = organization.groups.create(attributes)
organization.members.all.each do |member|
next if member.organization_membership_record.ungrouped_mail_delivery == 0
membership = group.members.add member, send_notice: false
if member.organization_membership_record.ungrouped_mail_delivery == 2
membership.gets_in_summary!
end
end
group.update(auto_join: true)
# now move mail
organization.conversations.ungrouped.each do |conversation|
conversation.groups.add group
end
puts organization.name
end
end
def down
Threadable::Transactions.in_migration = true
threadable = Threadable.new(threadable_env)
Group.where(primary: true).each do |group_record|
group = Threadable::Group.new(threadable, group_record)
conversations = group.conversations.all
group_record.destroy
conversations.each(&:update_group_caches!)
puts group.organization.name
end
remove_column :groups, :primary
end
def threadable_env
{
host: Rails.application.config.default_host,
port: Rails.application.config.default_port,
protocol: Rails.application.config.default_protocol,
worker: true,
}
end
end
|
FactoryGirl.define do
factory :user do
username {Faker::Internet.user_name}
password_hash "123"
name {Faker::Name.name}
email {Faker::Internet.email}
avatar {Faker::Avatar.image}
bio "MyText"
end
factory :listing do
max_price {Faker::Commerce.price.to_s}
base_price {Faker::Commerce.price.to_s}
end
factory :offer do
offer_price {Faker::Commerce.price.to_s}
end
added some shit
FactoryGirl.define do
factory :user do
username {Faker::Internet.user_name}
password_hash "123"
name {Faker::Name.name}
email {Faker::Internet.email}
avatar {Faker::Avatar.image}
bio "MyText"
end
factory :listing do
max_price {Faker::Commerce.price.to_s}
base_price {Faker::Commerce.price.to_s}
end
factory :offer do
offer_price {Faker::Commerce.price.to_s}
end
factory :product do
name {Faker::Commerce.product_name}
image_url "MyText"
description "MyText"
condition "MyString"
end |
Remove invalid data
PREFIX pc: <http://purl.org/procurement/public-contracts#>
DELETE {
?contract ?p1 ?o1 .
?o1 ?p2 ?o2 .
?o2 ?p3 ?o3 .
}
WHERE {
?contract pc:isValid false ;
?p1 ?o1 .
OPTIONAL {
FILTER isBlank(?o1)
?o1 ?p2 ?o2 .
OPTIONAL {
FILTER isBlank(?o2)
?o2 ?p3 ?o3 .
}
}
}
|
#
# Be sure to run `pod spec lint rollbar-ios.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "Rollbar"
s.version = "0.1.3"
s.summary = "Objective-C library for crash reporting and logging with Rollbar."
s.description = <<-DESC
Find, fix, and resolve errors with Rollbar.
Easily send error data using Rollbar's API.
Analyze, de-dupe, send alerts, and prepare the data for further analysis.
Search, sort, and prioritize via the Rollbar dashboard.
DESC
s.homepage = "https://rollbar.com"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
# s.license = "MIT (example)"
s.license = { :type => "MIT", :file => "LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "Rollbar" => "support@rollbar.com" }
# Or just: s.author = "Rollbar"
# s.authors = { "Rollbar" => "support@rollbar.com" }
s.social_media_url = "http://twitter.com/rollbar"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
s.platform = :ios
# s.platform = :ios, "5.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "https://github.com/rollbar/rollbar-ios.git", :tag => "v0.1.3" }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any h, m, mm, c & cpp files. For header
# files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "Rollbar", "Vendor"
# s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
# s.frameworks = "SomeFramework", "AnotherFramework"
s.frameworks = "SystemConfiguration",
"UIKit",
"Foundation"
s.vendored_frameworks = "Vendor/CrashReporter.framework"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
end
Update podspec for v0.1.4
#
# Be sure to run `pod spec lint rollbar-ios.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "Rollbar"
s.version = "0.1.4"
s.summary = "Objective-C library for crash reporting and logging with Rollbar."
s.description = <<-DESC
Find, fix, and resolve errors with Rollbar.
Easily send error data using Rollbar's API.
Analyze, de-dupe, send alerts, and prepare the data for further analysis.
Search, sort, and prioritize via the Rollbar dashboard.
DESC
s.homepage = "https://rollbar.com"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
# s.license = "MIT (example)"
s.license = { :type => "MIT", :file => "LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "Rollbar" => "support@rollbar.com" }
# Or just: s.author = "Rollbar"
# s.authors = { "Rollbar" => "support@rollbar.com" }
s.social_media_url = "http://twitter.com/rollbar"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
s.platform = :ios
# s.platform = :ios, "5.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "https://github.com/rollbar/rollbar-ios.git", :tag => "v0.1.4" }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any h, m, mm, c & cpp files. For header
# files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "Rollbar", "Vendor"
# s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
# s.frameworks = "SomeFramework", "AnotherFramework"
s.frameworks = "SystemConfiguration",
"UIKit",
"Foundation"
s.vendored_frameworks = "Vendor/CrashReporter.framework"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
end
|
module Deploy
VERSION = "0.0.13"
end
Version bump
module Deploy
VERSION = "0.0.14"
end
|
module Dexter
class Indexer
include Logging
def initialize(options)
@create = options[:create]
@tablespace = options[:tablespace]
@log_level = options[:log_level]
@exclude_tables = options[:exclude]
@include_tables = Array(options[:include].split(",")) if options[:include]
@log_sql = options[:log_sql]
@log_explain = options[:log_explain]
@min_time = options[:min_time] || 0
@min_calls = options[:min_calls] || 0
@analyze = options[:analyze]
@min_cost_savings_pct = options[:min_cost_savings_pct].to_i
@options = options
@mutex = Mutex.new
create_extension unless extension_exists?
execute("SET lock_timeout = '5s'")
end
def process_stat_statements
queries = stat_statements.map { |q| Query.new(q) }.sort_by(&:fingerprint).group_by(&:fingerprint).map { |_, v| v.first }
log "Processing #{queries.size} new query fingerprints"
process_queries(queries)
end
def stat_activity
execute <<-SQL
SELECT
pid || ':' || COALESCE(query_start, xact_start) AS id,
query,
EXTRACT(EPOCH FROM NOW() - COALESCE(query_start, xact_start)) * 1000.0 AS duration_ms
FROM
pg_stat_activity
WHERE
datname = current_database()
AND state = 'active'
AND pid != pg_backend_pid()
ORDER BY
1
SQL
end
def process_queries(queries)
# reset hypothetical indexes
reset_hypothetical_indexes
tables = Set.new(database_tables + materialized_views)
# map tables without schema to schema
no_schema_tables = {}
search_path_index = Hash[search_path.map.with_index.to_a]
tables.group_by { |t| t.split(".")[-1] }.each do |group, t2|
no_schema_tables[group] = t2.sort_by { |t| [search_path_index[t.split(".")[0]] || 1000000, t] }[0]
end
# add tables from views
view_tables = database_view_tables
view_tables.each do |v, vt|
view_tables[v] = vt.map { |t| no_schema_tables[t] || t }
end
# fully resolve tables
# make sure no views in result
view_tables.each do |v, vt|
view_tables[v] = vt.flat_map { |t| view_tables[t] || [t] }.uniq
end
# filter queries from other databases and system tables
queries.each do |query|
# add schema to table if needed
query.tables = query.tables.map { |t| no_schema_tables[t] || t }
# substitute view tables
new_tables = query.tables.flat_map { |t| view_tables[t] || [t] }.uniq
query.tables_from_views = new_tables - query.tables
query.tables = new_tables
# check for missing tables
query.missing_tables = !query.tables.all? { |t| tables.include?(t) }
end
# set tables
tables = Set.new(queries.reject(&:missing_tables).flat_map(&:tables))
# must come after missing tables set
if @include_tables
include_set = Set.new(@include_tables)
tables.keep_if { |t| include_set.include?(t) || include_set.include?(t.split(".")[-1]) }
end
if @exclude_tables.any?
exclude_set = Set.new(@exclude_tables)
tables.delete_if { |t| exclude_set.include?(t) || exclude_set.include?(t.split(".")[-1]) }
end
# remove system tables
tables.delete_if { |t| t.start_with?("information_schema.") || t.start_with?("pg_catalog.") }
queries.each do |query|
query.candidate_tables = !query.missing_tables && query.tables.any? { |t| tables.include?(t) }
end
# analyze tables if needed
analyze_tables(tables) if tables.any? && (@analyze || @log_level == "debug2")
# create hypothetical indexes and explain queries
candidates = tables.any? ? create_hypothetical_indexes(queries.select(&:candidate_tables)) : {}
# see if new indexes were used and meet bar
new_indexes = determine_indexes(queries, candidates, tables)
# display and create new indexes
show_and_create_indexes(new_indexes, queries)
end
private
def create_extension
execute("SET client_min_messages = warning")
begin
execute("CREATE EXTENSION IF NOT EXISTS hypopg")
rescue PG::UndefinedFile
raise Dexter::Abort, "Install HypoPG first: https://github.com/ankane/dexter#installation"
rescue PG::InsufficientPrivilege
raise Dexter::Abort, "Use a superuser to run: CREATE EXTENSION hypopg"
end
end
def extension_exists?
execute("SELECT * FROM pg_available_extensions WHERE name = 'hypopg' AND installed_version IS NOT NULL").any?
end
def reset_hypothetical_indexes
execute("SELECT hypopg_reset()")
end
def analyze_tables(tables)
tables = tables.to_a.sort
analyze_stats = execute <<-SQL
SELECT
schemaname || '.' || relname AS table,
last_analyze,
last_autoanalyze
FROM
pg_stat_user_tables
WHERE
schemaname || '.' || relname IN (#{tables.map { |t| quote(t) }.join(", ")})
SQL
last_analyzed = {}
analyze_stats.each do |stats|
last_analyzed[stats["table"]] = Time.parse(stats["last_analyze"]) if stats["last_analyze"]
end
tables.each do |table|
la = last_analyzed[table]
if @log_level == "debug2"
time_str = la ? la.iso8601 : "Unknown"
log "Last analyze: #{table} : #{time_str}"
end
if @analyze && (!la || la < Time.now - 3600)
statement = "ANALYZE #{quote_ident(table)}"
log "Running analyze: #{statement}"
execute(statement)
end
end
end
def calculate_plan(queries)
queries.each do |query|
if @log_explain
puts "Explaining query"
puts
end
begin
query.plans << plan(query.statement)
if @log_explain
# Pass format to prevent ANALYZE
puts execute("EXPLAIN (FORMAT TEXT) #{safe_statement(query.statement)}", pretty: false).map { |r| r["QUERY PLAN"] }.join("\n")
end
rescue PG::Error, JSON::NestingError => e
if @log_explain
log e.message
end
end
puts if @log_explain
end
end
def create_hypothetical_indexes(queries)
candidates = {}
# get initial costs for queries
calculate_plan(queries)
explainable_queries = queries.select { |q| q.explainable? && q.high_cost? }
# filter tables for performance
tables = Set.new(explainable_queries.flat_map(&:tables))
tables_from_views = Set.new(explainable_queries.flat_map(&:tables_from_views))
if tables.any?
# since every set of multi-column indexes are expensive
# try to parse out columns
possible_columns = Set.new
explainable_queries.each do |query|
log "Finding columns: #{query.statement}" if @log_level == "debug3"
find_columns(query.tree).each do |col|
last_col = col["fields"].last
if last_col["String"]
possible_columns << last_col["String"]["str"]
end
end
end
# create hypothetical indexes
# use all columns in tables from views
columns_by_table = columns(tables).select { |c| possible_columns.include?(c[:column]) || tables_from_views.include?(c[:table]) }.group_by { |c| c[:table] }
# create single column indexes
create_hypothetical_indexes_helper(columns_by_table, 1, candidates)
# get next round of costs
calculate_plan(explainable_queries)
# create multicolumn indexes
create_hypothetical_indexes_helper(columns_by_table, 2, candidates)
# get next round of costs
calculate_plan(explainable_queries)
end
candidates
end
def find_columns(plan)
find_by_key(plan, "ColumnRef")
end
def find_indexes(plan)
find_by_key(plan, "Index Name")
end
def find_by_key(plan, key)
indexes = []
case plan
when Hash
plan.each do |k, v|
if k == key
indexes << v
else
indexes.concat(find_by_key(v, key))
end
end
when Array
indexes.concat(plan.flat_map { |v| find_by_key(v, key) })
end
indexes
end
def hypo_indexes_from_plan(index_name_to_columns, plan, index_set)
query_indexes = []
find_indexes(plan).uniq.sort.each do |index_name|
col_set = index_name_to_columns[index_name]
if col_set
index = {
table: col_set[0][:table],
columns: col_set.map { |c| c[:column] }
}
unless index_set.include?([index[:table], index[:columns]])
query_indexes << index
end
end
end
query_indexes
end
def determine_indexes(queries, candidates, tables)
new_indexes = {}
index_name_to_columns = candidates.invert
# filter out existing indexes
# this must happen at end of process
# since sometimes hypothetical indexes
# can give lower cost than actual indexes
index_set = Set.new
if tables.any?
indexes(tables).each do |index|
if index["using"] == "btree"
# don't add indexes that are already covered
index_set << [index["table"], index["columns"].first(1)]
index_set << [index["table"], index["columns"].first(2)]
end
end
end
savings_ratio = (1 - @min_cost_savings_pct / 100.0)
queries.each do |query|
if query.explainable? && query.high_cost?
new_cost, new_cost2 = query.costs[1..2]
cost_savings = new_cost < query.initial_cost * savings_ratio
# set high bar for multicolumn indexes
cost_savings2 = new_cost > 100 && new_cost2 < new_cost * savings_ratio
key = cost_savings2 ? 2 : 1
query_indexes = hypo_indexes_from_plan(index_name_to_columns, query.plans[key], index_set)
# likely a bad suggestion, so try single column
if cost_savings2 && query_indexes.size > 1
query_indexes = hypo_indexes_from_plan(index_name_to_columns, query.plans[1], index_set)
cost_savings2 = false
end
suggest_index = cost_savings || cost_savings2
cost_savings3 = false
new_cost3 = nil
# if multiple indexes are found (for either single or multicolumn)
# determine the impact of each individually
# there may be a better single index that we're not considering
# that didn't get picked up by pass1 or pass2
# TODO clean this up
# TODO suggest more than one index from this if savings are there
if suggest_index && query_indexes.size > 1
winning_index = nil
winning_cost = nil
winning_plan = nil
query_indexes.each do |query_index|
reset_hypothetical_indexes
create_hypothetical_index(query_index[:table], query_index[:columns].map { |v| {column: v} })
plan3 = plan(query.statement)
cost3 = plan3["Total Cost"]
if !winning_cost || cost3 < winning_cost
winning_cost = cost3
winning_index = query_index
winning_plan = plan3
end
end
query.plans << winning_plan
# duplicated from above
# TODO DRY
use_winning =
if cost_savings2
new_cost > 100 && winning_cost < new_cost * savings_ratio
else
winning_cost < query.initial_cost * savings_ratio
end
query_indexes = [winning_index]
new_cost3 = winning_cost
query.pass3_indexes = query_indexes
if use_winning
cost_savings3 = true
else
suggest_index = false
end
end
if suggest_index
query_indexes.each do |index|
new_indexes[index] ||= index.dup
(new_indexes[index][:queries] ||= []) << query
end
end
query.indexes = query_indexes
query.suggest_index = suggest_index
query.new_cost =
if suggest_index
cost_savings3 ? new_cost3 : (cost_savings2 ? new_cost2 : new_cost)
else
query.initial_cost
end
# TODO optimize
if @log_level.start_with?("debug")
query.pass1_indexes = hypo_indexes_from_plan(index_name_to_columns, query.plans[1], index_set)
query.pass2_indexes = hypo_indexes_from_plan(index_name_to_columns, query.plans[2], index_set)
end
end
end
# filter out covered indexes
covered = Set.new
new_indexes.values.each do |index|
if index[:columns].size > 1
covered << [index[:table], index[:columns].first(1)]
end
end
new_indexes.values.reject { |i| covered.include?([i[:table], i[:columns]]) }.sort_by(&:to_a)
end
def log_indexes(indexes)
if indexes.any?
indexes.map { |i| "#{i[:table]} (#{i[:columns].join(", ")})" }.join(", ")
else
"None"
end
end
def show_and_create_indexes(new_indexes, queries)
# print summary
if new_indexes.any?
new_indexes.each do |index|
log colorize("Index found: #{index[:table]} (#{index[:columns].join(", ")})", :green)
end
else
log "No new indexes found"
end
# debug info
if @log_level.start_with?("debug")
index_queries = new_indexes.flat_map { |i| i[:queries].sort_by(&:fingerprint) }
if @log_level == "debug2"
fingerprints = Set.new(index_queries.map(&:fingerprint))
index_queries.concat(queries.reject { |q| fingerprints.include?(q.fingerprint) }.sort_by(&:fingerprint))
end
index_queries.each do |query|
log "-" * 80
log "Query #{query.fingerprint}"
log "Total time: #{(query.total_time / 60000.0).round(1)} min, avg time: #{(query.total_time / query.calls.to_f).round} ms, calls: #{query.calls}" if query.total_time
if query.fingerprint == "unknown"
log "Could not parse query"
elsif query.tables.empty?
log "No tables"
elsif query.missing_tables
log "Tables not present in current database"
elsif !query.candidate_tables
log "No candidate tables for indexes"
elsif query.explainable? && !query.high_cost?
log "Low initial cost: #{query.initial_cost}"
elsif query.explainable?
query_indexes = query.indexes || []
log "Start: #{query.costs[0]}"
log "Pass1: #{query.costs[1]} : #{log_indexes(query.pass1_indexes || [])}"
log "Pass2: #{query.costs[2]} : #{log_indexes(query.pass2_indexes || [])}"
if query.costs[3]
log "Pass3: #{query.costs[3]} : #{log_indexes(query.pass3_indexes || [])}"
end
log "Final: #{query.new_cost} : #{log_indexes(query.suggest_index ? query_indexes : [])}"
if (query.pass1_indexes.any? || query.pass2_indexes.any?) && !query.suggest_index
log "Need #{@min_cost_savings_pct}% cost savings to suggest index"
end
else
log "Could not run explain"
end
log
log query.statement
log
end
end
# create
if @create && new_indexes.any?
# 1. create lock
# 2. refresh existing index list
# 3. create indexes that still don't exist
# 4. release lock
with_advisory_lock do
new_indexes.each do |index|
unless index_exists?(index)
statement = String.new("CREATE INDEX CONCURRENTLY ON #{quote_ident(index[:table])} (#{index[:columns].map { |c| quote_ident(c) }.join(", ")})")
statement << " TABLESPACE #{quote_ident(@tablespace)}" if @tablespace
log "Creating index: #{statement}"
started_at = monotonic_time
begin
execute(statement)
log "Index created: #{((monotonic_time - started_at) * 1000).to_i} ms"
rescue PG::LockNotAvailable
log "Could not acquire lock: #{index[:table]}"
end
end
end
end
end
new_indexes
end
def monotonic_time
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
def conn
@conn ||= begin
# set connect timeout if none set
ENV["PGCONNECT_TIMEOUT"] ||= "2"
if @options[:dbname] =~ /\Apostgres(ql)?:\/\//
config = @options[:dbname]
else
config = {
host: @options[:host],
port: @options[:port],
dbname: @options[:dbname],
user: @options[:username]
}.reject { |_, value| value.to_s.empty? }
config = config[:dbname] if config.keys == [:dbname] && config[:dbname].include?("=")
end
PG::Connection.new(config)
end
rescue PG::ConnectionBad => e
raise Dexter::Abort, e.message
end
def execute(query, pretty: true)
# use exec_params instead of exec for security
#
# Unlike PQexec, PQexecParams allows at most one SQL command in the given string.
# (There can be semicolons in it, but not more than one nonempty command.)
# This is a limitation of the underlying protocol, but has some usefulness
# as an extra defense against SQL-injection attacks.
# https://www.postgresql.org/docs/current/static/libpq-exec.html
query = squish(query) if pretty
log colorize("[sql] #{query}", :cyan) if @log_sql
@mutex.synchronize do
conn.exec_params(query, []).to_a
end
end
def plan(query)
# strip semi-colons as another measure of defense
JSON.parse(execute("EXPLAIN (FORMAT JSON) #{safe_statement(query)}", pretty: false).first["QUERY PLAN"], max_nesting: 1000).first["Plan"]
end
# TODO for multicolumn indexes, use ordering
def create_hypothetical_indexes_helper(columns_by_table, n, candidates)
columns_by_table.each do |table, cols|
# no reason to use btree index for json columns
cols.reject { |c| ["json", "jsonb"].include?(c[:type]) }.permutation(n) do |col_set|
candidates[col_set] = create_hypothetical_index(table, col_set)
end
end
end
def create_hypothetical_index(table, col_set)
execute("SELECT * FROM hypopg_create_index('CREATE INDEX ON #{quote_ident(table)} (#{col_set.map { |c| quote_ident(c[:column]) }.join(", ")})')").first["indexname"]
end
def database_tables
result = execute <<-SQL
SELECT
table_schema || '.' || table_name AS table_name
FROM
information_schema.tables
WHERE
table_catalog = current_database()
SQL
result.map { |r| r["table_name"] }
end
def materialized_views
if server_version_num >= 90300
result = execute <<-SQL
SELECT
schemaname || '.' || matviewname AS table_name
FROM
pg_matviews
SQL
result.map { |r| r["table_name"] }
else
[]
end
end
def server_version_num
execute("SHOW server_version_num").first["server_version_num"].to_i
end
def database_view_tables
result = execute <<-SQL
SELECT
schemaname || '.' || viewname AS table_name,
definition
FROM
pg_views
WHERE
schemaname NOT IN ('information_schema', 'pg_catalog')
SQL
view_tables = {}
result.each do |row|
begin
view_tables[row["table_name"]] = PgQuery.parse(row["definition"]).tables
rescue PgQuery::ParseError
if @log_level.start_with?("debug")
log colorize("ERROR: Cannot parse view definition: #{row["table_name"]}", :red)
end
end
end
view_tables
end
def stat_statements
result = execute <<-SQL
SELECT
DISTINCT query
FROM
pg_stat_statements
INNER JOIN
pg_database ON pg_database.oid = pg_stat_statements.dbid
WHERE
datname = current_database()
AND total_time >= #{@min_time * 60000}
AND calls >= #{@min_calls}
ORDER BY
1
SQL
result.map { |q| q["query"] }
end
def with_advisory_lock
lock_id = 123456
first_time = true
while execute("SELECT pg_try_advisory_lock(#{lock_id})").first["pg_try_advisory_lock"] != "t"
if first_time
log "Waiting for lock..."
first_time = false
end
sleep(1)
end
yield
ensure
with_min_messages("error") do
execute("SELECT pg_advisory_unlock(#{lock_id})")
end
end
def with_min_messages(value)
execute("SET client_min_messages = #{quote(value)}")
yield
ensure
execute("SET client_min_messages = warning")
end
def index_exists?(index)
indexes([index[:table]]).find { |i| i["columns"] == index[:columns] }
end
def columns(tables)
columns = execute <<-SQL
SELECT
s.nspname || '.' || t.relname AS table_name,
a.attname AS column_name,
pg_catalog.format_type(a.atttypid, a.atttypmod) AS data_type
FROM pg_attribute a
JOIN pg_class t on a.attrelid = t.oid
JOIN pg_namespace s on t.relnamespace = s.oid
WHERE a.attnum > 0
AND NOT a.attisdropped
AND s.nspname || '.' || t.relname IN (#{tables.map { |t| quote(t) }.join(", ")})
ORDER BY
1, 2
SQL
columns.map { |v| {table: v["table_name"], column: v["column_name"], type: v["data_type"]} }
end
def indexes(tables)
execute(<<-SQL
SELECT
schemaname || '.' || t.relname AS table,
ix.relname AS name,
regexp_replace(pg_get_indexdef(i.indexrelid), '^[^\\(]*\\((.*)\\)$', '\\1') AS columns,
regexp_replace(pg_get_indexdef(i.indexrelid), '.* USING ([^ ]*) \\(.*', '\\1') AS using
FROM
pg_index i
INNER JOIN
pg_class t ON t.oid = i.indrelid
INNER JOIN
pg_class ix ON ix.oid = i.indexrelid
LEFT JOIN
pg_stat_user_indexes ui ON ui.indexrelid = i.indexrelid
WHERE
schemaname || '.' || t.relname IN (#{tables.map { |t| quote(t) }.join(", ")}) AND
indisvalid = 't' AND
indexprs IS NULL AND
indpred IS NULL
ORDER BY
1, 2
SQL
).map { |v| v["columns"] = v["columns"].sub(") WHERE (", " WHERE ").split(", ").map { |c| unquote(c) }; v }
end
def search_path
execute("SELECT current_schemas(true)")[0]["current_schemas"][1..-2].split(",")
end
def unquote(part)
if part && part.start_with?('"') && part.end_with?('"')
part[1..-2]
else
part
end
end
def quote_ident(value)
value.split(".").map { |v| conn.quote_ident(v) }.join(".")
end
def quote(value)
if value.is_a?(String)
"'#{quote_string(value)}'"
else
value
end
end
# from activerecord
def quote_string(s)
s.gsub(/\\/, '\&\&').gsub(/'/, "''")
end
# from activesupport
def squish(str)
str.to_s.gsub(/\A[[:space:]]+/, "").gsub(/[[:space:]]+\z/, "").gsub(/[[:space:]]+/, " ")
end
def safe_statement(statement)
statement.gsub(";", "")
end
end
end
Removed recursion [skip ci]
module Dexter
class Indexer
include Logging
def initialize(options)
@create = options[:create]
@tablespace = options[:tablespace]
@log_level = options[:log_level]
@exclude_tables = options[:exclude]
@include_tables = Array(options[:include].split(",")) if options[:include]
@log_sql = options[:log_sql]
@log_explain = options[:log_explain]
@min_time = options[:min_time] || 0
@min_calls = options[:min_calls] || 0
@analyze = options[:analyze]
@min_cost_savings_pct = options[:min_cost_savings_pct].to_i
@options = options
@mutex = Mutex.new
create_extension unless extension_exists?
execute("SET lock_timeout = '5s'")
end
def process_stat_statements
queries = stat_statements.map { |q| Query.new(q) }.sort_by(&:fingerprint).group_by(&:fingerprint).map { |_, v| v.first }
log "Processing #{queries.size} new query fingerprints"
process_queries(queries)
end
def stat_activity
execute <<-SQL
SELECT
pid || ':' || COALESCE(query_start, xact_start) AS id,
query,
EXTRACT(EPOCH FROM NOW() - COALESCE(query_start, xact_start)) * 1000.0 AS duration_ms
FROM
pg_stat_activity
WHERE
datname = current_database()
AND state = 'active'
AND pid != pg_backend_pid()
ORDER BY
1
SQL
end
def process_queries(queries)
# reset hypothetical indexes
reset_hypothetical_indexes
tables = Set.new(database_tables + materialized_views)
# map tables without schema to schema
no_schema_tables = {}
search_path_index = Hash[search_path.map.with_index.to_a]
tables.group_by { |t| t.split(".")[-1] }.each do |group, t2|
no_schema_tables[group] = t2.sort_by { |t| [search_path_index[t.split(".")[0]] || 1000000, t] }[0]
end
# add tables from views
view_tables = database_view_tables
view_tables.each do |v, vt|
view_tables[v] = vt.map { |t| no_schema_tables[t] || t }
end
# fully resolve tables
# make sure no views in result
view_tables.each do |v, vt|
view_tables[v] = vt.flat_map { |t| view_tables[t] || [t] }.uniq
end
# filter queries from other databases and system tables
queries.each do |query|
# add schema to table if needed
query.tables = query.tables.map { |t| no_schema_tables[t] || t }
# substitute view tables
new_tables = query.tables.flat_map { |t| view_tables[t] || [t] }.uniq
query.tables_from_views = new_tables - query.tables
query.tables = new_tables
# check for missing tables
query.missing_tables = !query.tables.all? { |t| tables.include?(t) }
end
# set tables
tables = Set.new(queries.reject(&:missing_tables).flat_map(&:tables))
# must come after missing tables set
if @include_tables
include_set = Set.new(@include_tables)
tables.keep_if { |t| include_set.include?(t) || include_set.include?(t.split(".")[-1]) }
end
if @exclude_tables.any?
exclude_set = Set.new(@exclude_tables)
tables.delete_if { |t| exclude_set.include?(t) || exclude_set.include?(t.split(".")[-1]) }
end
# remove system tables
tables.delete_if { |t| t.start_with?("information_schema.") || t.start_with?("pg_catalog.") }
queries.each do |query|
query.candidate_tables = !query.missing_tables && query.tables.any? { |t| tables.include?(t) }
end
# analyze tables if needed
analyze_tables(tables) if tables.any? && (@analyze || @log_level == "debug2")
# create hypothetical indexes and explain queries
candidates = tables.any? ? create_hypothetical_indexes(queries.select(&:candidate_tables)) : {}
# see if new indexes were used and meet bar
new_indexes = determine_indexes(queries, candidates, tables)
# display and create new indexes
show_and_create_indexes(new_indexes, queries)
end
private
def create_extension
execute("SET client_min_messages = warning")
begin
execute("CREATE EXTENSION IF NOT EXISTS hypopg")
rescue PG::UndefinedFile
raise Dexter::Abort, "Install HypoPG first: https://github.com/ankane/dexter#installation"
rescue PG::InsufficientPrivilege
raise Dexter::Abort, "Use a superuser to run: CREATE EXTENSION hypopg"
end
end
def extension_exists?
execute("SELECT * FROM pg_available_extensions WHERE name = 'hypopg' AND installed_version IS NOT NULL").any?
end
def reset_hypothetical_indexes
execute("SELECT hypopg_reset()")
end
def analyze_tables(tables)
tables = tables.to_a.sort
analyze_stats = execute <<-SQL
SELECT
schemaname || '.' || relname AS table,
last_analyze,
last_autoanalyze
FROM
pg_stat_user_tables
WHERE
schemaname || '.' || relname IN (#{tables.map { |t| quote(t) }.join(", ")})
SQL
last_analyzed = {}
analyze_stats.each do |stats|
last_analyzed[stats["table"]] = Time.parse(stats["last_analyze"]) if stats["last_analyze"]
end
tables.each do |table|
la = last_analyzed[table]
if @log_level == "debug2"
time_str = la ? la.iso8601 : "Unknown"
log "Last analyze: #{table} : #{time_str}"
end
if @analyze && (!la || la < Time.now - 3600)
statement = "ANALYZE #{quote_ident(table)}"
log "Running analyze: #{statement}"
execute(statement)
end
end
end
def calculate_plan(queries)
queries.each do |query|
if @log_explain
puts "Explaining query"
puts
end
begin
query.plans << plan(query.statement)
if @log_explain
# Pass format to prevent ANALYZE
puts execute("EXPLAIN (FORMAT TEXT) #{safe_statement(query.statement)}", pretty: false).map { |r| r["QUERY PLAN"] }.join("\n")
end
rescue PG::Error, JSON::NestingError => e
if @log_explain
log e.message
end
end
puts if @log_explain
end
end
def create_hypothetical_indexes(queries)
candidates = {}
# get initial costs for queries
calculate_plan(queries)
explainable_queries = queries.select { |q| q.explainable? && q.high_cost? }
# filter tables for performance
tables = Set.new(explainable_queries.flat_map(&:tables))
tables_from_views = Set.new(explainable_queries.flat_map(&:tables_from_views))
if tables.any?
# since every set of multi-column indexes are expensive
# try to parse out columns
possible_columns = Set.new
explainable_queries.each do |query|
log "Finding columns: #{query.statement}" if @log_level == "debug3"
find_columns(query.tree).each do |col|
last_col = col["fields"].last
if last_col["String"]
possible_columns << last_col["String"]["str"]
end
end
end
# create hypothetical indexes
# use all columns in tables from views
columns_by_table = columns(tables).select { |c| possible_columns.include?(c[:column]) || tables_from_views.include?(c[:table]) }.group_by { |c| c[:table] }
# create single column indexes
create_hypothetical_indexes_helper(columns_by_table, 1, candidates)
# get next round of costs
calculate_plan(explainable_queries)
# create multicolumn indexes
create_hypothetical_indexes_helper(columns_by_table, 2, candidates)
# get next round of costs
calculate_plan(explainable_queries)
end
candidates
end
def find_columns(plan)
find_by_key(plan, "ColumnRef")
end
def find_indexes(plan)
find_by_key(plan, "Index Name")
end
def find_by_key(plan, key)
result = []
queue = [plan]
while queue.any?
node = queue.pop
case node
when Hash
node.each do |k, v|
if k == key
result << v
elsif !v.nil?
queue << v
end
end
when Array
queue.concat(node)
end
end
result
end
def hypo_indexes_from_plan(index_name_to_columns, plan, index_set)
query_indexes = []
find_indexes(plan).uniq.sort.each do |index_name|
col_set = index_name_to_columns[index_name]
if col_set
index = {
table: col_set[0][:table],
columns: col_set.map { |c| c[:column] }
}
unless index_set.include?([index[:table], index[:columns]])
query_indexes << index
end
end
end
query_indexes
end
def determine_indexes(queries, candidates, tables)
new_indexes = {}
index_name_to_columns = candidates.invert
# filter out existing indexes
# this must happen at end of process
# since sometimes hypothetical indexes
# can give lower cost than actual indexes
index_set = Set.new
if tables.any?
indexes(tables).each do |index|
if index["using"] == "btree"
# don't add indexes that are already covered
index_set << [index["table"], index["columns"].first(1)]
index_set << [index["table"], index["columns"].first(2)]
end
end
end
savings_ratio = (1 - @min_cost_savings_pct / 100.0)
queries.each do |query|
if query.explainable? && query.high_cost?
new_cost, new_cost2 = query.costs[1..2]
cost_savings = new_cost < query.initial_cost * savings_ratio
# set high bar for multicolumn indexes
cost_savings2 = new_cost > 100 && new_cost2 < new_cost * savings_ratio
key = cost_savings2 ? 2 : 1
query_indexes = hypo_indexes_from_plan(index_name_to_columns, query.plans[key], index_set)
# likely a bad suggestion, so try single column
if cost_savings2 && query_indexes.size > 1
query_indexes = hypo_indexes_from_plan(index_name_to_columns, query.plans[1], index_set)
cost_savings2 = false
end
suggest_index = cost_savings || cost_savings2
cost_savings3 = false
new_cost3 = nil
# if multiple indexes are found (for either single or multicolumn)
# determine the impact of each individually
# there may be a better single index that we're not considering
# that didn't get picked up by pass1 or pass2
# TODO clean this up
# TODO suggest more than one index from this if savings are there
if suggest_index && query_indexes.size > 1
winning_index = nil
winning_cost = nil
winning_plan = nil
query_indexes.each do |query_index|
reset_hypothetical_indexes
create_hypothetical_index(query_index[:table], query_index[:columns].map { |v| {column: v} })
plan3 = plan(query.statement)
cost3 = plan3["Total Cost"]
if !winning_cost || cost3 < winning_cost
winning_cost = cost3
winning_index = query_index
winning_plan = plan3
end
end
query.plans << winning_plan
# duplicated from above
# TODO DRY
use_winning =
if cost_savings2
new_cost > 100 && winning_cost < new_cost * savings_ratio
else
winning_cost < query.initial_cost * savings_ratio
end
query_indexes = [winning_index]
new_cost3 = winning_cost
query.pass3_indexes = query_indexes
if use_winning
cost_savings3 = true
else
suggest_index = false
end
end
if suggest_index
query_indexes.each do |index|
new_indexes[index] ||= index.dup
(new_indexes[index][:queries] ||= []) << query
end
end
query.indexes = query_indexes
query.suggest_index = suggest_index
query.new_cost =
if suggest_index
cost_savings3 ? new_cost3 : (cost_savings2 ? new_cost2 : new_cost)
else
query.initial_cost
end
# TODO optimize
if @log_level.start_with?("debug")
query.pass1_indexes = hypo_indexes_from_plan(index_name_to_columns, query.plans[1], index_set)
query.pass2_indexes = hypo_indexes_from_plan(index_name_to_columns, query.plans[2], index_set)
end
end
end
# filter out covered indexes
covered = Set.new
new_indexes.values.each do |index|
if index[:columns].size > 1
covered << [index[:table], index[:columns].first(1)]
end
end
new_indexes.values.reject { |i| covered.include?([i[:table], i[:columns]]) }.sort_by(&:to_a)
end
def log_indexes(indexes)
if indexes.any?
indexes.map { |i| "#{i[:table]} (#{i[:columns].join(", ")})" }.join(", ")
else
"None"
end
end
def show_and_create_indexes(new_indexes, queries)
# print summary
if new_indexes.any?
new_indexes.each do |index|
log colorize("Index found: #{index[:table]} (#{index[:columns].join(", ")})", :green)
end
else
log "No new indexes found"
end
# debug info
if @log_level.start_with?("debug")
index_queries = new_indexes.flat_map { |i| i[:queries].sort_by(&:fingerprint) }
if @log_level == "debug2"
fingerprints = Set.new(index_queries.map(&:fingerprint))
index_queries.concat(queries.reject { |q| fingerprints.include?(q.fingerprint) }.sort_by(&:fingerprint))
end
index_queries.each do |query|
log "-" * 80
log "Query #{query.fingerprint}"
log "Total time: #{(query.total_time / 60000.0).round(1)} min, avg time: #{(query.total_time / query.calls.to_f).round} ms, calls: #{query.calls}" if query.total_time
if query.fingerprint == "unknown"
log "Could not parse query"
elsif query.tables.empty?
log "No tables"
elsif query.missing_tables
log "Tables not present in current database"
elsif !query.candidate_tables
log "No candidate tables for indexes"
elsif query.explainable? && !query.high_cost?
log "Low initial cost: #{query.initial_cost}"
elsif query.explainable?
query_indexes = query.indexes || []
log "Start: #{query.costs[0]}"
log "Pass1: #{query.costs[1]} : #{log_indexes(query.pass1_indexes || [])}"
log "Pass2: #{query.costs[2]} : #{log_indexes(query.pass2_indexes || [])}"
if query.costs[3]
log "Pass3: #{query.costs[3]} : #{log_indexes(query.pass3_indexes || [])}"
end
log "Final: #{query.new_cost} : #{log_indexes(query.suggest_index ? query_indexes : [])}"
if (query.pass1_indexes.any? || query.pass2_indexes.any?) && !query.suggest_index
log "Need #{@min_cost_savings_pct}% cost savings to suggest index"
end
else
log "Could not run explain"
end
log
log query.statement
log
end
end
# create
if @create && new_indexes.any?
# 1. create lock
# 2. refresh existing index list
# 3. create indexes that still don't exist
# 4. release lock
with_advisory_lock do
new_indexes.each do |index|
unless index_exists?(index)
statement = String.new("CREATE INDEX CONCURRENTLY ON #{quote_ident(index[:table])} (#{index[:columns].map { |c| quote_ident(c) }.join(", ")})")
statement << " TABLESPACE #{quote_ident(@tablespace)}" if @tablespace
log "Creating index: #{statement}"
started_at = monotonic_time
begin
execute(statement)
log "Index created: #{((monotonic_time - started_at) * 1000).to_i} ms"
rescue PG::LockNotAvailable
log "Could not acquire lock: #{index[:table]}"
end
end
end
end
end
new_indexes
end
def monotonic_time
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
def conn
@conn ||= begin
# set connect timeout if none set
ENV["PGCONNECT_TIMEOUT"] ||= "2"
if @options[:dbname] =~ /\Apostgres(ql)?:\/\//
config = @options[:dbname]
else
config = {
host: @options[:host],
port: @options[:port],
dbname: @options[:dbname],
user: @options[:username]
}.reject { |_, value| value.to_s.empty? }
config = config[:dbname] if config.keys == [:dbname] && config[:dbname].include?("=")
end
PG::Connection.new(config)
end
rescue PG::ConnectionBad => e
raise Dexter::Abort, e.message
end
def execute(query, pretty: true)
# use exec_params instead of exec for security
#
# Unlike PQexec, PQexecParams allows at most one SQL command in the given string.
# (There can be semicolons in it, but not more than one nonempty command.)
# This is a limitation of the underlying protocol, but has some usefulness
# as an extra defense against SQL-injection attacks.
# https://www.postgresql.org/docs/current/static/libpq-exec.html
query = squish(query) if pretty
log colorize("[sql] #{query}", :cyan) if @log_sql
@mutex.synchronize do
conn.exec_params(query, []).to_a
end
end
def plan(query)
# strip semi-colons as another measure of defense
JSON.parse(execute("EXPLAIN (FORMAT JSON) #{safe_statement(query)}", pretty: false).first["QUERY PLAN"], max_nesting: 1000).first["Plan"]
end
# TODO for multicolumn indexes, use ordering
def create_hypothetical_indexes_helper(columns_by_table, n, candidates)
columns_by_table.each do |table, cols|
# no reason to use btree index for json columns
cols.reject { |c| ["json", "jsonb"].include?(c[:type]) }.permutation(n) do |col_set|
candidates[col_set] = create_hypothetical_index(table, col_set)
end
end
end
def create_hypothetical_index(table, col_set)
execute("SELECT * FROM hypopg_create_index('CREATE INDEX ON #{quote_ident(table)} (#{col_set.map { |c| quote_ident(c[:column]) }.join(", ")})')").first["indexname"]
end
def database_tables
result = execute <<-SQL
SELECT
table_schema || '.' || table_name AS table_name
FROM
information_schema.tables
WHERE
table_catalog = current_database()
SQL
result.map { |r| r["table_name"] }
end
def materialized_views
if server_version_num >= 90300
result = execute <<-SQL
SELECT
schemaname || '.' || matviewname AS table_name
FROM
pg_matviews
SQL
result.map { |r| r["table_name"] }
else
[]
end
end
def server_version_num
execute("SHOW server_version_num").first["server_version_num"].to_i
end
def database_view_tables
result = execute <<-SQL
SELECT
schemaname || '.' || viewname AS table_name,
definition
FROM
pg_views
WHERE
schemaname NOT IN ('information_schema', 'pg_catalog')
SQL
view_tables = {}
result.each do |row|
begin
view_tables[row["table_name"]] = PgQuery.parse(row["definition"]).tables
rescue PgQuery::ParseError
if @log_level.start_with?("debug")
log colorize("ERROR: Cannot parse view definition: #{row["table_name"]}", :red)
end
end
end
view_tables
end
def stat_statements
result = execute <<-SQL
SELECT
DISTINCT query
FROM
pg_stat_statements
INNER JOIN
pg_database ON pg_database.oid = pg_stat_statements.dbid
WHERE
datname = current_database()
AND total_time >= #{@min_time * 60000}
AND calls >= #{@min_calls}
ORDER BY
1
SQL
result.map { |q| q["query"] }
end
def with_advisory_lock
lock_id = 123456
first_time = true
while execute("SELECT pg_try_advisory_lock(#{lock_id})").first["pg_try_advisory_lock"] != "t"
if first_time
log "Waiting for lock..."
first_time = false
end
sleep(1)
end
yield
ensure
with_min_messages("error") do
execute("SELECT pg_advisory_unlock(#{lock_id})")
end
end
def with_min_messages(value)
execute("SET client_min_messages = #{quote(value)}")
yield
ensure
execute("SET client_min_messages = warning")
end
def index_exists?(index)
indexes([index[:table]]).find { |i| i["columns"] == index[:columns] }
end
def columns(tables)
columns = execute <<-SQL
SELECT
s.nspname || '.' || t.relname AS table_name,
a.attname AS column_name,
pg_catalog.format_type(a.atttypid, a.atttypmod) AS data_type
FROM pg_attribute a
JOIN pg_class t on a.attrelid = t.oid
JOIN pg_namespace s on t.relnamespace = s.oid
WHERE a.attnum > 0
AND NOT a.attisdropped
AND s.nspname || '.' || t.relname IN (#{tables.map { |t| quote(t) }.join(", ")})
ORDER BY
1, 2
SQL
columns.map { |v| {table: v["table_name"], column: v["column_name"], type: v["data_type"]} }
end
def indexes(tables)
execute(<<-SQL
SELECT
schemaname || '.' || t.relname AS table,
ix.relname AS name,
regexp_replace(pg_get_indexdef(i.indexrelid), '^[^\\(]*\\((.*)\\)$', '\\1') AS columns,
regexp_replace(pg_get_indexdef(i.indexrelid), '.* USING ([^ ]*) \\(.*', '\\1') AS using
FROM
pg_index i
INNER JOIN
pg_class t ON t.oid = i.indrelid
INNER JOIN
pg_class ix ON ix.oid = i.indexrelid
LEFT JOIN
pg_stat_user_indexes ui ON ui.indexrelid = i.indexrelid
WHERE
schemaname || '.' || t.relname IN (#{tables.map { |t| quote(t) }.join(", ")}) AND
indisvalid = 't' AND
indexprs IS NULL AND
indpred IS NULL
ORDER BY
1, 2
SQL
).map { |v| v["columns"] = v["columns"].sub(") WHERE (", " WHERE ").split(", ").map { |c| unquote(c) }; v }
end
def search_path
execute("SELECT current_schemas(true)")[0]["current_schemas"][1..-2].split(",")
end
def unquote(part)
if part && part.start_with?('"') && part.end_with?('"')
part[1..-2]
else
part
end
end
def quote_ident(value)
value.split(".").map { |v| conn.quote_ident(v) }.join(".")
end
def quote(value)
if value.is_a?(String)
"'#{quote_string(value)}'"
else
value
end
end
# from activerecord
def quote_string(s)
s.gsub(/\\/, '\&\&').gsub(/'/, "''")
end
# from activesupport
def squish(str)
str.to_s.gsub(/\A[[:space:]]+/, "").gsub(/[[:space:]]+\z/, "").gsub(/[[:space:]]+/, " ")
end
def safe_statement(statement)
statement.gsub(";", "")
end
end
end
|
module Dexter
class Indexer
include Logging
def initialize(database_url, options)
@database_url = database_url
@create = options[:create]
@log_level = options[:log_level]
@exclude_tables = options[:exclude]
create_extension
end
def process_queries(queries)
# reset hypothetical indexes
reset_hypothetical_indexes
# filter queries from other databases and system tables
tables = possible_tables(queries)
queries.each do |query|
query.missing_tables = !query.tables.all? { |t| tables.include?(t) }
end
# exclude user specified tables
# TODO exclude write-heavy tables
@exclude_tables.each do |table|
tables.delete(table)
end
# analyze tables if needed
analyze_tables(tables) if tables.any?
# get initial costs for queries
calculate_initial_cost(queries.reject(&:missing_tables))
# create hypothetical indexes
candidates = tables.any? ? create_hypothetical_indexes(tables) : {}
# get new costs and see if new indexes were used
new_indexes = determine_indexes(queries, candidates)
# display and create new indexes
show_and_create_indexes(new_indexes)
end
private
def create_extension
select_all("SET client_min_messages = warning")
select_all("CREATE EXTENSION IF NOT EXISTS hypopg")
end
def reset_hypothetical_indexes
select_all("SELECT hypopg_reset()")
end
def analyze_tables(tables)
tables = tables.to_a.sort
analyze_stats = select_all <<-SQL
SELECT
schemaname AS schema,
relname AS table,
last_analyze,
last_autoanalyze
FROM
pg_stat_user_tables
WHERE
relname IN (#{tables.map { |t| quote(t) }.join(", ")})
SQL
last_analyzed = {}
analyze_stats.each do |stats|
last_analyzed[stats["table"]] = Time.parse(stats["last_analyze"]) if stats["last_analyze"]
end
tables.each do |table|
if !last_analyzed[table] || last_analyzed[table] < Time.now - 3600
statement = "ANALYZE #{quote_ident(table)}"
log "Running analyze: #{statement}"
select_all(statement)
end
end
end
def calculate_initial_cost(queries)
queries.each do |query|
begin
query.initial_cost = plan(query.statement)["Total Cost"]
rescue PG::Error
# do nothing
end
end
end
def create_hypothetical_indexes(tables)
# get existing indexes
index_set = Set.new
indexes(tables).each do |index|
# TODO make sure btree
index_set << [index["table"], index["columns"]]
end
# create hypothetical indexes
candidates = {}
columns(tables).each do |col|
unless index_set.include?([col[:table], [col[:column]]])
candidates[col] = select_all("SELECT * FROM hypopg_create_index('CREATE INDEX ON #{col[:table]} (#{[col[:column]].join(", ")})');").first["indexname"]
end
end
candidates
end
def determine_indexes(queries, candidates)
new_indexes = {}
queries.each do |query|
if query.initial_cost
new_plan = plan(query.statement)
query.new_cost = new_plan["Total Cost"]
cost_savings = query.new_cost < query.initial_cost * 0.5
query_indexes = []
candidates.each do |col, index_name|
if new_plan.inspect.include?(index_name)
index = {
table: col[:table],
columns: [col[:column]]
}
query_indexes << index
if cost_savings
new_indexes[index] ||= index.dup
(new_indexes[index][:queries] ||= []) << query
end
end
end
end
if @log_level == "debug2"
log "Processed #{query.fingerprint}"
if query.initial_cost
log "Cost: #{query.initial_cost} -> #{query.new_cost}"
if query_indexes.any?
log "Indexes: #{query_indexes.map { |i| "#{i[:table]} (#{i[:columns].join(", ")})" }.join(", ")}"
log "Need 50% cost savings to suggest index" unless cost_savings
else
log "Indexes: None"
end
elsif query.fingerprint == "unknown"
log "Could not parse query"
elsif query.tables.empty?
log "No tables"
elsif query.missing_tables
log "Tables not present in current database"
else
log "Could not run explain"
end
puts
puts query.statement
puts
end
end
new_indexes.values.sort_by(&:to_a)
end
def show_and_create_indexes(new_indexes)
if new_indexes.any?
new_indexes.each do |index|
log "Index found: #{index[:table]} (#{index[:columns].join(", ")})"
if @log_level.start_with?("debug")
index[:queries].sort_by(&:fingerprint).each do |query|
log "Query #{query.fingerprint} (Cost: #{query.initial_cost} -> #{query.new_cost})"
puts
puts query.statement
puts
end
end
end
if @create
# TODO use advisory locks
# 1. create lock
# 2. refresh existing index list
# 3. create indexes that still don't exist
# 4. release lock
new_indexes.each do |index|
statement = "CREATE INDEX CONCURRENTLY ON #{index[:table]} (#{index[:columns].join(", ")})"
log "Creating index: #{statement}"
started_at = Time.now
select_all(statement)
log "Index created: #{((Time.now - started_at) * 1000).to_i} ms"
end
end
else
log "No indexes found"
end
new_indexes
end
def conn
@conn ||= begin
uri = URI.parse(@database_url)
config = {
host: uri.host,
port: uri.port,
dbname: uri.path.sub(/\A\//, ""),
user: uri.user,
password: uri.password,
connect_timeout: 3
}.reject { |_, value| value.to_s.empty? }
PG::Connection.new(config)
end
rescue PG::ConnectionBad
abort "Bad database url"
end
def select_all(query)
conn.exec(query).to_a
end
def plan(query)
JSON.parse(select_all("EXPLAIN (FORMAT JSON) #{query}").first["QUERY PLAN"]).first["Plan"]
end
def database_tables
result = select_all <<-SQL
SELECT
table_name
FROM
information_schema.tables
WHERE
table_catalog = current_database() AND
table_schema NOT IN ('pg_catalog', 'information_schema')
SQL
result.map { |r| r["table_name"] }
end
def possible_tables(queries)
Set.new(queries.flat_map(&:tables).uniq & database_tables)
end
def columns(tables)
columns = select_all <<-SQL
SELECT
table_name,
column_name
FROM
information_schema.columns
WHERE
table_schema = 'public' AND
table_name IN (#{tables.map { |t| quote(t) }.join(", ")})
SQL
columns.map { |v| {table: v["table_name"], column: v["column_name"]} }
end
def indexes(tables)
select_all(<<-SQL
SELECT
schemaname AS schema,
t.relname AS table,
ix.relname AS name,
regexp_replace(pg_get_indexdef(i.indexrelid), '^[^\\(]*\\((.*)\\)$', '\\1') AS columns,
regexp_replace(pg_get_indexdef(i.indexrelid), '.* USING ([^ ]*) \\(.*', '\\1') AS using,
indisunique AS unique,
indisprimary AS primary,
indisvalid AS valid,
indexprs::text,
indpred::text,
pg_get_indexdef(i.indexrelid) AS definition
FROM
pg_index i
INNER JOIN
pg_class t ON t.oid = i.indrelid
INNER JOIN
pg_class ix ON ix.oid = i.indexrelid
LEFT JOIN
pg_stat_user_indexes ui ON ui.indexrelid = i.indexrelid
WHERE
t.relname IN (#{tables.map { |t| quote(t) }.join(", ")}) AND
schemaname IS NOT NULL AND
indisvalid = 't' AND
indexprs IS NULL AND
indpred IS NULL
ORDER BY
1, 2
SQL
).map { |v| v["columns"] = v["columns"].sub(") WHERE (", " WHERE ").split(", ").map { |c| unquote(c) }; v }
end
def unquote(part)
if part && part.start_with?('"')
part[1..-2]
else
part
end
end
def quote_ident(value)
conn.quote_ident(value)
end
def quote(value)
if value.is_a?(String)
"'#{quote_string(value)}'"
else
value
end
end
# activerecord
def quote_string(s)
s.gsub(/\\/, '\&\&').gsub(/'/, "''")
end
end
end
Use exec_params
module Dexter
class Indexer
include Logging
def initialize(database_url, options)
@database_url = database_url
@create = options[:create]
@log_level = options[:log_level]
@exclude_tables = options[:exclude]
create_extension
end
def process_queries(queries)
# reset hypothetical indexes
reset_hypothetical_indexes
# filter queries from other databases and system tables
tables = possible_tables(queries)
queries.each do |query|
query.missing_tables = !query.tables.all? { |t| tables.include?(t) }
end
# exclude user specified tables
# TODO exclude write-heavy tables
@exclude_tables.each do |table|
tables.delete(table)
end
# analyze tables if needed
analyze_tables(tables) if tables.any?
# get initial costs for queries
calculate_initial_cost(queries.reject(&:missing_tables))
# create hypothetical indexes
candidates = tables.any? ? create_hypothetical_indexes(tables) : {}
# get new costs and see if new indexes were used
new_indexes = determine_indexes(queries, candidates)
# display and create new indexes
show_and_create_indexes(new_indexes)
end
private
def create_extension
select_all("SET client_min_messages = warning")
select_all("CREATE EXTENSION IF NOT EXISTS hypopg")
end
def reset_hypothetical_indexes
select_all("SELECT hypopg_reset()")
end
def analyze_tables(tables)
tables = tables.to_a.sort
analyze_stats = select_all <<-SQL
SELECT
schemaname AS schema,
relname AS table,
last_analyze,
last_autoanalyze
FROM
pg_stat_user_tables
WHERE
relname IN (#{tables.map { |t| quote(t) }.join(", ")})
SQL
last_analyzed = {}
analyze_stats.each do |stats|
last_analyzed[stats["table"]] = Time.parse(stats["last_analyze"]) if stats["last_analyze"]
end
tables.each do |table|
if !last_analyzed[table] || last_analyzed[table] < Time.now - 3600
statement = "ANALYZE #{quote_ident(table)}"
log "Running analyze: #{statement}"
select_all(statement)
end
end
end
def calculate_initial_cost(queries)
queries.each do |query|
begin
query.initial_cost = plan(query.statement)["Total Cost"]
rescue PG::Error
# do nothing
end
end
end
def create_hypothetical_indexes(tables)
# get existing indexes
index_set = Set.new
indexes(tables).each do |index|
# TODO make sure btree
index_set << [index["table"], index["columns"]]
end
# create hypothetical indexes
candidates = {}
columns(tables).each do |col|
unless index_set.include?([col[:table], [col[:column]]])
candidates[col] = select_all("SELECT * FROM hypopg_create_index('CREATE INDEX ON #{col[:table]} (#{[col[:column]].join(", ")})');").first["indexname"]
end
end
candidates
end
def determine_indexes(queries, candidates)
new_indexes = {}
queries.each do |query|
if query.initial_cost
new_plan = plan(query.statement)
query.new_cost = new_plan["Total Cost"]
cost_savings = query.new_cost < query.initial_cost * 0.5
query_indexes = []
candidates.each do |col, index_name|
if new_plan.inspect.include?(index_name)
index = {
table: col[:table],
columns: [col[:column]]
}
query_indexes << index
if cost_savings
new_indexes[index] ||= index.dup
(new_indexes[index][:queries] ||= []) << query
end
end
end
end
if @log_level == "debug2"
log "Processed #{query.fingerprint}"
if query.initial_cost
log "Cost: #{query.initial_cost} -> #{query.new_cost}"
if query_indexes.any?
log "Indexes: #{query_indexes.map { |i| "#{i[:table]} (#{i[:columns].join(", ")})" }.join(", ")}"
log "Need 50% cost savings to suggest index" unless cost_savings
else
log "Indexes: None"
end
elsif query.fingerprint == "unknown"
log "Could not parse query"
elsif query.tables.empty?
log "No tables"
elsif query.missing_tables
log "Tables not present in current database"
else
log "Could not run explain"
end
puts
puts query.statement
puts
end
end
new_indexes.values.sort_by(&:to_a)
end
def show_and_create_indexes(new_indexes)
if new_indexes.any?
new_indexes.each do |index|
log "Index found: #{index[:table]} (#{index[:columns].join(", ")})"
if @log_level.start_with?("debug")
index[:queries].sort_by(&:fingerprint).each do |query|
log "Query #{query.fingerprint} (Cost: #{query.initial_cost} -> #{query.new_cost})"
puts
puts query.statement
puts
end
end
end
if @create
# TODO use advisory locks
# 1. create lock
# 2. refresh existing index list
# 3. create indexes that still don't exist
# 4. release lock
new_indexes.each do |index|
statement = "CREATE INDEX CONCURRENTLY ON #{index[:table]} (#{index[:columns].join(", ")})"
log "Creating index: #{statement}"
started_at = Time.now
select_all(statement)
log "Index created: #{((Time.now - started_at) * 1000).to_i} ms"
end
end
else
log "No indexes found"
end
new_indexes
end
def conn
@conn ||= begin
uri = URI.parse(@database_url)
config = {
host: uri.host,
port: uri.port,
dbname: uri.path.sub(/\A\//, ""),
user: uri.user,
password: uri.password,
connect_timeout: 3
}.reject { |_, value| value.to_s.empty? }
PG::Connection.new(config)
end
rescue PG::ConnectionBad
abort "Bad database url"
end
def select_all(query)
# use exec_params instead of exec for securiy
#
# Unlike PQexec, PQexecParams allows at most one SQL command in the given string.
# (There can be semicolons in it, but not more than one nonempty command.)
# This is a limitation of the underlying protocol, but has some usefulness
# as an extra defense against SQL-injection attacks.
# https://www.postgresql.org/docs/current/static/libpq-exec.html
conn.exec_params(query, []).to_a
end
def plan(query)
JSON.parse(select_all("EXPLAIN (FORMAT JSON) #{query}").first["QUERY PLAN"]).first["Plan"]
end
def database_tables
result = select_all <<-SQL
SELECT
table_name
FROM
information_schema.tables
WHERE
table_catalog = current_database() AND
table_schema NOT IN ('pg_catalog', 'information_schema')
SQL
result.map { |r| r["table_name"] }
end
def possible_tables(queries)
Set.new(queries.flat_map(&:tables).uniq & database_tables)
end
def columns(tables)
columns = select_all <<-SQL
SELECT
table_name,
column_name
FROM
information_schema.columns
WHERE
table_schema = 'public' AND
table_name IN (#{tables.map { |t| quote(t) }.join(", ")})
SQL
columns.map { |v| {table: v["table_name"], column: v["column_name"]} }
end
def indexes(tables)
select_all(<<-SQL
SELECT
schemaname AS schema,
t.relname AS table,
ix.relname AS name,
regexp_replace(pg_get_indexdef(i.indexrelid), '^[^\\(]*\\((.*)\\)$', '\\1') AS columns,
regexp_replace(pg_get_indexdef(i.indexrelid), '.* USING ([^ ]*) \\(.*', '\\1') AS using,
indisunique AS unique,
indisprimary AS primary,
indisvalid AS valid,
indexprs::text,
indpred::text,
pg_get_indexdef(i.indexrelid) AS definition
FROM
pg_index i
INNER JOIN
pg_class t ON t.oid = i.indrelid
INNER JOIN
pg_class ix ON ix.oid = i.indexrelid
LEFT JOIN
pg_stat_user_indexes ui ON ui.indexrelid = i.indexrelid
WHERE
t.relname IN (#{tables.map { |t| quote(t) }.join(", ")}) AND
schemaname IS NOT NULL AND
indisvalid = 't' AND
indexprs IS NULL AND
indpred IS NULL
ORDER BY
1, 2
SQL
).map { |v| v["columns"] = v["columns"].sub(") WHERE (", " WHERE ").split(", ").map { |c| unquote(c) }; v }
end
def unquote(part)
if part && part.start_with?('"')
part[1..-2]
else
part
end
end
def quote_ident(value)
conn.quote_ident(value)
end
def quote(value)
if value.is_a?(String)
"'#{quote_string(value)}'"
else
value
end
end
# activerecord
def quote_string(s)
s.gsub(/\\/, '\&\&').gsub(/'/, "''")
end
end
end
|
# frozen_string_literal: true
# These classes hold relevant Discord data, such as messages or channels.
require 'ostruct'
require 'discordrb/permissions'
require 'discordrb/errors'
require 'discordrb/api'
require 'discordrb/api/channel'
require 'discordrb/api/server'
require 'discordrb/api/invite'
require 'discordrb/api/user'
require 'discordrb/webhooks/embeds'
require 'time'
require 'base64'
# Discordrb module
module Discordrb
# The unix timestamp Discord IDs are based on
DISCORD_EPOCH = 1_420_070_400_000
# Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID.
def self.id_compare(one_id, other)
other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other)
end
# The maximum length a Discord message can have
CHARACTER_LIMIT = 2000
# Splits a message into chunks of 2000 characters. Attempts to split by lines if possible.
# @param msg [String] The message to split.
# @return [Array<String>] the message split into chunks
def self.split_message(msg)
# If the messages is empty, return an empty array
return [] if msg.empty?
# Split the message into lines
lines = msg.lines
# Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become
# [
# [1],
# [1, 2],
# [1, 2, 3],
# [1, 2, 3, 4]
# ]
tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first }
# Join the individual elements together to get an array of strings with consecutively more lines
joined = tri.map(&:join)
# Find the largest element that is still below the character limit, or if none such element exists return the first
ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length }
# If it's still larger than the character limit (none was smaller than it) split it into slices with the length
# being the character limit, otherwise just return an array with one element
ideal_ary = ideal.length > CHARACTER_LIMIT ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal]
# Slice off the ideal part and strip newlines
rest = msg[ideal.length..-1].strip
# If none remains, return an empty array -> we're done
return [] unless rest
# Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array
ideal_ary + split_message(rest)
end
# Mixin for objects that have IDs
module IDObject
# @return [Integer] the ID which uniquely identifies this object across Discord.
attr_reader :id
alias_method :resolve_id, :id
# ID based comparison
def ==(other)
Discordrb.id_compare(@id, other)
end
# Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but
# shouldn't be relied on as Discord might change its algorithm at any time
# @return [Time] when this object was created at
def creation_time
# Milliseconds
ms = (@id >> 22) + DISCORD_EPOCH
Time.at(ms / 1000.0)
end
end
# Mixin for the attributes users should have
module UserAttributes
# @return [String] this user's username
attr_reader :username
alias_method :name, :username
# @return [String] this user's discriminator which is used internally to identify users with identical usernames.
attr_reader :discriminator
alias_method :discrim, :discriminator
alias_method :tag, :discriminator
alias_method :discord_tag, :discriminator
# @return [true, false] whether this user is a Discord bot account
attr_reader :bot_account
alias_method :bot_account?, :bot_account
# @return [String] the ID of this user's current avatar, can be used to generate an avatar URL.
# @see #avatar_url
attr_accessor :avatar_id
# Utility function to mention users in messages
# @return [String] the mention code in the form of <@id>
def mention
"<@#{@id}>"
end
# Utility function to get Discord's distinct representation of a user, i. e. username + discriminator
# @return [String] distinct representation of user
def distinct
"#{@username}##{@discriminator}"
end
# Utility function to get a user's avatar URL.
# @return [String] the URL to the avatar image.
def avatar_url
API::User.avatar_url(@id, @avatar_id)
end
end
# User on Discord, including internal data like discriminators
class User
include IDObject
include UserAttributes
# @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`)
attr_reader :status
# @return [String, nil] the game the user is currently playing, or `nil` if none is being played.
attr_reader :game
# @return [String, nil] the URL to the stream, if the user is currently streaming something.
attr_reader :stream_url
# @return [String, Integer, nil] the type of the stream. Can technically be set to anything, most of the time it
# will be 0 for no stream or 1 for Twitch streams.
attr_reader :stream_type
def initialize(data, bot)
@bot = bot
@username = data['username']
@id = data['id'].to_i
@discriminator = data['discriminator']
@avatar_id = data['avatar']
@roles = {}
@bot_account = false
@bot_account = true if data['bot']
@status = :offline
end
# Get a user's PM channel or send them a PM
# @overload pm
# Creates a private message channel for this user or returns an existing one if it already exists
# @return [Channel] the PM channel to this user.
# @overload pm(content)
# Sends a private to this user.
# @param content [String] The content to send.
# @return [Message] the message sent to this user.
def pm(content = nil)
if content
# Recursively call pm to get the channel, then send a message to it
channel = pm
channel.send_message(content)
else
# If no message was specified, return the PM channel
@bot.pm_channel(@id)
end
end
alias_method :dm, :pm
# Send the user a file.
# @param file [File] The file to send to the user
# @param caption [String] The caption of the file being sent
# @return [Message] the message sent to this user.
def send_file(file, caption = nil)
pm.send_file(file, caption: caption)
end
# Set the user's name
# @note for internal use only
# @!visibility private
def update_username(username)
@username = username
end
# Set the user's presence data
# @note for internal use only
# @!visibility private
def update_presence(data)
@status = data['status'].to_sym
if data['game']
game = data['game']
@game = game['name']
@stream_url = game['url']
@stream_type = game['type']
else
@game = @stream_url = @stream_type = nil
end
end
# Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this
# user's ID as a :from attribute.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block)
end
# Gets the member this user is on a server
# @param server [Server] The server to get the member for
# @return [Member] this user as a member on a particular server
def on(server)
id = server.resolve_id
@bot.server(id).member(@id)
end
# Is the user the bot?
# @return [true, false] whether this user is the bot
def current_bot?
@bot.profile.id == @id
end
# @return [true, false] whether this user is a fake user for a webhook message
def webhook?
@discriminator == Message::ZERO_DISCRIM
end
[:offline, :idle, :online].each do |e|
define_method(e.to_s + '?') do
@status.to_sym == e
end
end
# The inspect method is overwritten to give more useful output
def inspect
"<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>"
end
end
# OAuth Application information
class Application
include IDObject
# @return [String] the application name
attr_reader :name
# @return [String] the application description
attr_reader :description
# @return [Array<String>] the applications origins permitted to use RPC
attr_reader :rpc_origins
# @return [Integer]
attr_reader :flags
# Gets the user object of the owner. May be limited to username, discriminator,
# ID and avatar if the bot cannot reach the owner.
# @return [User] the user object of the owner
attr_reader :owner
def initialize(data, bot)
@bot = bot
@name = data['name']
@id = data['id'].to_i
@description = data['description']
@icon_id = data['icon']
@rpc_origins = data['rpc_origins']
@flags = data['flags']
@owner = @bot.ensure_user(data['owner'])
end
# Utility function to get a application's icon URL.
# @return [String, nil] the URL to the icon image (nil if no image is set).
def icon_url
return nil if @icon_id.nil?
API.app_icon_url(@id, @icon_id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Application name=#{@name} id=#{@id}>"
end
end
# Mixin for the attributes members and private members should have
module MemberAttributes
# @return [Time] when this member joined the server.
attr_reader :joined_at
# @return [String, nil] the nickname this member has, or nil if it has none.
attr_reader :nick
alias_method :nickname, :nick
# @return [Array<Role>] the roles this member has.
attr_reader :roles
# @return [Server] the server this member is on.
attr_reader :server
end
# Mixin to calculate resulting permissions from overrides etc.
module PermissionCalculator
# Checks whether this user can do the particular action, regardless of whether it has the permission defined,
# through for example being the server owner or having the Manage Roles permission
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @example Check if the bot can send messages to a specific channel in a server.
# bot_profile = bot.profile.on(event.server)
# can_send_messages = bot_profile.permission?(:send_messages, channel)
# @return [true, false] whether or not this user has the permission.
def permission?(action, channel = nil)
# If the member is the server owner, it irrevocably has all permissions.
return true if owner?
# First, check whether the user has Manage Roles defined.
# (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a
# Manage Permissions deny overwrite will override Manage Roles, so we can just check for
# Manage Roles once and call it a day.)
return true if defined_permission?(:administrator, channel)
# Otherwise, defer to defined_permission
defined_permission?(action, channel)
end
# Checks whether this user has a particular permission defined (i. e. not implicit, through for example
# Manage Roles)
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @example Check if a member has the Manage Channels permission defined in the server.
# has_manage_channels = member.defined_permission?(:manage_channels)
# @return [true, false] whether or not this user has the permission defined.
def defined_permission?(action, channel = nil)
# Get the permission the user's roles have
role_permission = defined_role_permission?(action, channel)
# Once we have checked the role permission, we have to check the channel overrides for the
# specific user
user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable
# Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role
return role_permission unless user_specific_override
user_specific_override == :allow
end
# Define methods for querying permissions
Discordrb::Permissions::Flags.each_value do |flag|
define_method "can_#{flag}?" do |channel = nil|
permission? flag, channel
end
end
alias_method :can_administrate?, :can_administrator?
private
def defined_role_permission?(action, channel)
# For each role, check if
# (1) the channel explicitly allows or permits an action for the role and
# (2) if the user is allowed to do the action if the channel doesn't specify
@roles.reduce(false) do |can_act, role|
# Get the override defined for the role on the channel
channel_allow = permission_overwrite(action, channel, role.id)
can_act = if channel_allow
# If the channel has an override, check whether it is an allow - if yes,
# the user can act, if not, it can't
channel_allow == :allow
else
# Otherwise defer to the role
role.permissions.instance_variable_get("@#{action}") || can_act
end
can_act
end
end
def permission_overwrite(action, channel, id)
# If no overwrites are defined, or no channel is set, no overwrite will be present
return nil unless channel && channel.permission_overwrites[id]
# Otherwise, check the allow and deny objects
allow = channel.permission_overwrites[id].allow
deny = channel.permission_overwrites[id].deny
if allow.instance_variable_get("@#{action}")
:allow
elsif deny.instance_variable_get("@#{action}")
:deny
end
# If there's no variable defined, nil will implicitly be returned
end
end
# A voice state represents the state of a member's connection to a voice channel. It includes data like the voice
# channel the member is connected to and mute/deaf flags.
class VoiceState
# @return [Integer] the ID of the user whose voice state is represented by this object.
attr_reader :user_id
# @return [true, false] whether this voice state's member is muted server-wide.
attr_reader :mute
# @return [true, false] whether this voice state's member is deafened server-wide.
attr_reader :deaf
# @return [true, false] whether this voice state's member has muted themselves.
attr_reader :self_mute
# @return [true, false] whether this voice state's member has deafened themselves.
attr_reader :self_deaf
# @return [Channel] the voice channel this voice state's member is in.
attr_reader :voice_channel
# @!visibility private
def initialize(user_id)
@user_id = user_id
end
# Update this voice state with new data from Discord
# @note For internal use only.
# @!visibility private
def update(channel, mute, deaf, self_mute, self_deaf)
@voice_channel = channel
@mute = mute
@deaf = deaf
@self_mute = self_mute
@self_deaf = self_deaf
end
end
# A presence represents a
# A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like
# that.
class Member < DelegateClass(User)
# @return [true, false] whether this member is muted server-wide.
def mute
voice_state_attribute(:mute)
end
# @return [true, false] whether this member is deafened server-wide.
def deaf
voice_state_attribute(:deaf)
end
# @return [true, false] whether this member has muted themselves.
def self_mute
voice_state_attribute(:self_mute)
end
# @return [true, false] whether this member has deafened themselves.
def self_deaf
voice_state_attribute(:self_deaf)
end
# @return [Channel] the voice channel this member is in.
def voice_channel
voice_state_attribute(:voice_channel)
end
alias_method :muted?, :mute
alias_method :deafened?, :deaf
alias_method :self_muted?, :self_mute
alias_method :self_deafened?, :self_deaf
include MemberAttributes
# @!visibility private
def initialize(data, server, bot)
@bot = bot
@user = bot.ensure_user(data['user'])
super @user # Initialize the delegate class
# Somehow, Discord doesn't send the server ID in the standard member format...
raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil?
@server = server || bot.server(data['guild_id'].to_i)
# Initialize the roles by getting the roles from the server one-by-one
update_roles(data['roles'])
@nick = data['nick']
@joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil
end
# @return [true, false] whether this member is the server owner.
def owner?
@server.owner == self
end
# @param role [Role, Integer, #resolve_id] the role to check or its ID.
# @return [true, false] whether this member has the specified role.
def role?(role)
role = role.resolve_id
@roles.any? { |e| e.id == role }
end
# Bulk sets a member's roles.
# @param role [Role, Array<Role>] The role(s) to set.
def roles=(role)
role_ids = role_id_array(role)
API::Server.update_member(@bot.token, @server.id, @user.id, roles: role_ids)
end
# Adds and removes roles from a member.
# @param add [Role, Array<Role>] The role(s) to add.
# @param remove [Role, Array<Role>] The role(s) to remove.
# @example Remove the 'Member' role from a user, and add the 'Muted' role to them.
# to_add = server.roles.find {|role| role.name == 'Muted'}
# to_remove = server.roles.find {|role| role.name == 'Member'}
# member.modify_roles(to_add, to_remove)
def modify_roles(add, remove)
add_role_ids = role_id_array(add)
remove_role_ids = role_id_array(remove)
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids - remove_role_ids + add_role_ids).uniq
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids)
end
# Adds one or more roles to this member.
# @param role [Role, Array<Role>] The role(s) to add.
def add_role(role)
role_ids = role_id_array(role)
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids + role_ids).uniq
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids)
end
# Removes one or more roles from this member.
# @param role [Role, Array<Role>] The role(s) to remove.
def remove_role(role)
old_role_ids = @roles.map(&:id)
role_ids = role_id_array(role)
new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) }
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids)
end
# Server deafens this member.
def server_deafen
API::Server.update_member(@bot.token, @server.id, @user.id, deaf: true)
end
# Server undeafens this member.
def server_undeafen
API::Server.update_member(@bot.token, @server.id, @user.id, deaf: false)
end
# Server mutes this member.
def server_mute
API::Server.update_member(@bot.token, @server.id, @user.id, mute: true)
end
# Server unmutes this member.
def server_unmute
API::Server.update_member(@bot.token, @server.id, @user.id, mute: false)
end
# Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage
# Nicknames for other users.
# @param nick [String, nil] The string to set the nickname to, or nil if it should be reset.
def nick=(nick)
# Discord uses the empty string to signify 'no nickname' so we convert nil into that
nick ||= ''
if @user.current_bot?
API::User.change_own_nickname(@bot.token, @server.id, nick)
else
API::Server.update_member(@bot.token, @server.id, @user.id, nick: nick)
end
end
alias_method :nickname=, :nick=
# @return [String] the name the user displays as (nickname if they have one, username otherwise)
def display_name
nickname || username
end
# Update this member's roles
# @note For internal use only.
# @!visibility private
def update_roles(roles)
@roles = roles.map do |role|
role.is_a?(Role) ? role : @server.role(role.to_i)
end
end
# Update this member's nick
# @note For internal use only.
# @!visibility private
def update_nick(nick)
@nick = nick
end
include PermissionCalculator
# Overwriting inspect for debug purposes
def inspect
"<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>"
end
private
# Utility method to get a list of role IDs from one role or an array of roles
def role_id_array(role)
if role.is_a? Array
role.map(&:resolve_id)
else
[role.resolve_id]
end
end
# Utility method to get data out of this member's voice state
def voice_state_attribute(name)
voice_state = @server.voice_states[@user.id]
voice_state.send name if voice_state
end
end
# Recipients are members on private channels - they exist for completeness purposes, but all
# the attributes will be empty.
class Recipient < DelegateClass(User)
include MemberAttributes
# @return [Channel] the private channel this recipient is the recipient of.
attr_reader :channel
# @!visibility private
def initialize(user, channel, bot)
@bot = bot
@channel = channel
raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private?
@user = user
super @user
# Member attributes
@mute = @deaf = @self_mute = @self_deaf = false
@voice_channel = nil
@server = nil
@roles = []
@joined_at = @channel.creation_time
end
# Overwriting inspect for debug purposes
def inspect
"<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>"
end
end
# This class is a special variant of User that represents the bot's user profile (things like own username and the avatar).
# It can be accessed using {Bot#profile}.
class Profile < User
def initialize(data, bot)
super(data, bot)
end
# Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true.
# @return [true]
def current_bot?
true
end
# Sets the bot's username.
# @param username [String] The new username.
def username=(username)
update_profile_data(username: username)
end
alias_method :name=, :username=
# Changes the bot's avatar.
# @param avatar [String, #read] A JPG file to be used as the avatar, either
# something readable (e. g. File Object) or as a data URL.
def avatar=(avatar)
if avatar.respond_to? :read
# Set the file to binary mode if supported, so we don't get problems with Windows
avatar.binmode if avatar.respond_to?(:binmode)
avatar_string = 'data:image/jpg;base64,'
avatar_string += Base64.strict_encode64(avatar.read)
update_profile_data(avatar: avatar_string)
else
update_profile_data(avatar: avatar)
end
end
# Updates the cached profile data with the new one.
# @note For internal use only.
# @!visibility private
def update_data(new_data)
@username = new_data[:username] || @username
@avatar_id = new_data[:avatar_id] || @avatar_id
end
# Sets the user status setting to Online.
# @note Only usable on User accounts.
def online
update_profile_status_setting('online')
end
# Sets the user status setting to Idle.
# @note Only usable on User accounts.
def idle
update_profile_status_setting('idle')
end
# Sets the user status setting to Do Not Disturb.
# @note Only usable on User accounts.
def dnd
update_profile_status_setting('dnd')
end
alias_method(:busy, :dnd)
# Sets the user status setting to Invisible.
# @note Only usable on User accounts.
def invisible
update_profile_status_setting('invisible')
end
# The inspect method is overwritten to give more useful output
def inspect
"<Profile user=#{super}>"
end
private
# Internal handler for updating the user's status setting
def update_profile_status_setting(status)
API::User.change_status_setting(@bot.token, status)
end
def update_profile_data(new_data)
API::User.update_profile(@bot.token,
nil, nil,
new_data[:username] || @username,
new_data.key?(:avatar) ? new_data[:avatar] : @avatar_id)
update_data(new_data)
end
end
# A Discord role that contains permissions and applies to certain users
class Role
include IDObject
# @return [Permissions] this role's permissions.
attr_reader :permissions
# @return [String] this role's name ("new role" if it hasn't been changed)
attr_reader :name
# @return [true, false] whether or not this role should be displayed separately from other users
attr_reader :hoist
# @return [true, false] whether this role can be mentioned using a role mention
attr_reader :mentionable
alias_method :mentionable?, :mentionable
# @return [ColourRGB] the role colour
attr_reader :colour
alias_method :color, :colour
# @return [Integer] the position of this role in the hierarchy
attr_reader :position
# This class is used internally as a wrapper to a Role object that allows easy writing of permission data.
class RoleWriter
# @!visibility private
def initialize(role, token)
@role = role
@token = token
end
# Write the specified permission data to the role, without updating the permission cache
# @param bits [Integer] The packed permissions to write.
def write(bits)
@role.send(:packed=, bits, false)
end
# The inspect method is overridden, in this case to prevent the token being leaked
def inspect
"<RoleWriter role=#{@role} token=...>"
end
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
@server = server
@permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token))
@name = data['name']
@id = data['id'].to_i
@position = data['position']
@hoist = data['hoist']
@mentionable = data['mentionable']
@colour = ColourRGB.new(data['color'])
end
# @return [String] a string that will mention this role, if it is mentionable.
def mention
"<@&#{@id}>"
end
# @return [Array<Member>] an array of members who have this role.
# @note This requests a member chunk if it hasn't for the server before, which may be slow initially
def members
@server.members.select { |m| m.role? role }
end
alias_method :users, :members
# Updates the data cache from another Role object
# @note For internal use only
# @!visibility private
def update_from(other)
@permissions = other.permissions
@name = other.name
@hoist = other.hoist
@colour = other.colour
@position = other.position
end
# Updates the data cache from a hash containing data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@hoist = new_data['hoist'] unless new_data['hoist'].nil?
@hoist = new_data[:hoist] unless new_data[:hoist].nil?
@colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour)
end
# Sets the role name to something new
# @param name [String] The name that should be set
def name=(name)
update_role_data(name: name)
end
# Changes whether or not this role is displayed at the top of the user list
# @param hoist [true, false] The value it should be changed to
def hoist=(hoist)
update_role_data(hoist: hoist)
end
# Changes whether or not this role can be mentioned
# @param mentionable [true, false] The value it should be changed to
def mentionable=(mentionable)
update_role_data(mentionable: mentionable)
end
# Sets the role colour to something new
# @param colour [ColourRGB] The new colour
def colour=(colour)
update_role_data(colour: colour)
end
alias_method :color=, :colour=
# Changes this role's permissions to a fixed bitfield. This allows setting multiple permissions at once with just
# one API call.
#
# Information on how this bitfield is structured can be found at
# https://discordapp.com/developers/docs/topics/permissions.
# @example Remove all permissions from a role
# role.packed = 0
# @param packed [Integer] A bitfield with the desired permissions value.
# @param update_perms [true, false] Whether the internal data should also be updated. This should always be true
# when calling externally.
def packed=(packed, update_perms = true)
update_role_data(permissions: packed)
@permissions.bits = packed if update_perms
end
# Deletes this role. This cannot be undone without recreating the role!
def delete
API::Server.delete_role(@bot.token, @server.id, @id)
@server.delete_role(@id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>"
end
private
def update_role_data(new_data)
API::Server.update_role(@bot.token, @server.id, @id,
new_data[:name] || @name,
(new_data[:colour] || @colour).combined,
new_data[:hoist].nil? ? @hoist : new_data[:hoist],
new_data[:mentionable].nil? ? @mentionable : new_data[:mentionable],
new_data[:permissions] || @permissions.bits)
update_data(new_data)
end
end
# A channel referenced by an invite. It has less data than regular channels, so it's a separate class
class InviteChannel
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [Integer] this channel's type (0: text, 1: private, 2: voice, 3: group).
attr_reader :type
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@type = data['type']
end
end
# A server referenced to by an invite
class InviteServer
include IDObject
# @return [String] this server's name.
attr_reader :name
# @return [String, nil] the hash of the server's invite splash screen (for partnered servers) or nil if none is
# present
attr_reader :splash_hash
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@splash_hash = data['splash_hash']
end
end
# A Discord invite to a channel
class Invite
# @return [InviteChannel] the channel this invite references.
attr_reader :channel
# @return [InviteServer] the server this invite references.
attr_reader :server
# @return [Integer] the amount of uses left on this invite.
attr_reader :uses
alias_method :max_uses, :uses
# @return [User, nil] the user that made this invite. May also be nil if the user can't be determined.
attr_reader :inviter
alias_method :user, :inviter
# @return [true, false] whether or not this invite is temporary.
attr_reader :temporary
alias_method :temporary?, :temporary
# @return [true, false] whether this invite is still valid.
attr_reader :revoked
alias_method :revoked?, :revoked
# @return [String] this invite's code
attr_reader :code
# @!visibility private
def initialize(data, bot)
@bot = bot
@channel = InviteChannel.new(data['channel'], bot)
@server = InviteServer.new(data['guild'], bot)
@uses = data['uses']
@inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil
@temporary = data['temporary']
@revoked = data['revoked']
@code = data['code']
end
# Code based comparison
def ==(other)
other.respond_to?(:code) ? (@code == other.code) : (@code == other)
end
# Deletes this invite
def delete
API::Invite.delete(@bot.token, @code)
end
alias_method :revoke, :delete
# The inspect method is overwritten to give more useful output
def inspect
"<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked}>"
end
# Creates an invite URL.
def url
"https://discord.gg/#{@code}"
end
end
# A Discord channel, including data like the topic
class Channel
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil.
attr_reader :server
# @return [Integer] the type of this channel (0: text, 1: private, 2: voice, 3: group)
attr_reader :type
# @return [Integer, nil] the id of the owner of the group channel or nil if this is not a group channel.
attr_reader :owner_id
# @return [Array<Recipient>, nil] the array of recipients of the private messages, or nil if this is not a Private channel
attr_reader :recipients
# @return [String] the channel's topic
attr_reader :topic
# @return [Integer] the bitrate (in bps) of the channel
attr_reader :bitrate
# @return [Integer] the amount of users that can be in the channel. `0` means it is unlimited.
attr_reader :user_limit
alias_method :limit, :user_limit
# @return [Integer] the channel's position on the channel list
attr_reader :position
# This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the
# `allow` and `deny` properties which are {Permissions} objects respectively.
# @return [Hash<Integer => OpenStruct>] the channel's permission overwrites
attr_reader :permission_overwrites
alias_method :overwrites, :permission_overwrites
# @return [true, false] whether or not this channel is a PM or group channel.
def private?
pm? || group?
end
# @return [String] a string that will mention the channel as a clickable link on Discord.
def mention
"<##{@id}>"
end
# @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel
def recipient
@recipients.first if pm?
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
# data is a sometimes a Hash and other times an array of Hashes, you only want the last one if it's an array
data = data[-1] if data.is_a?(Array)
@id = data['id'].to_i
@type = data['type'] || 0
@topic = data['topic']
@bitrate = data['bitrate']
@user_limit = data['user_limit']
@position = data['position']
if private?
@recipients = []
if data['recipients']
data['recipients'].each do |recipient|
recipient_user = bot.ensure_user(recipient)
@recipients << Recipient.new(recipient_user, self, bot)
end
end
if pm?
@name = @recipients.first.username
else
@name = data['name']
@owner_id = data['owner_id']
end
else
@name = data['name']
@server = if server
server
else
bot.server(data['guild_id'].to_i)
end
end
# Populate permission overwrites
@permission_overwrites = {}
return unless data['permission_overwrites']
data['permission_overwrites'].each do |element|
role_id = element['id'].to_i
deny = Permissions.new(element['deny'])
allow = Permissions.new(element['allow'])
@permission_overwrites[role_id] = OpenStruct.new
@permission_overwrites[role_id].deny = deny
@permission_overwrites[role_id].allow = allow
end
end
# @return [true, false] whether or not this channel is a text channel
def text?
@type.zero?
end
# @return [true, false] whether or not this channel is a PM channel.
def pm?
@type == 1
end
# @return [true, false] whether or not this channel is a voice channel.
def voice?
@type == 2
end
# @return [true, false] whether or not this channel is a group channel.
def group?
@type == 3
end
# Sends a message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
# @param embed [Hash, Discordrb::Webhooks::Embed, nil] The rich embed to append to this message.
# @return [Message] the message that was sent.
def send_message(content, tts = false, embed = nil)
@bot.send_message(@id, content, tts, embed)
end
alias_method :send, :send_message
# Sends a temporary message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param timeout [Float] The amount of time in seconds after which the message sent will be deleted.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
# @param embed [Hash, Discordrb::Webhooks::Embed, nil] The rich embed to append to this message.
def send_temporary_message(content, timeout, tts = false, embed = nil)
@bot.send_temporary_message(@id, content, timeout, tts, embed)
end
# Convenience method to send a message with an embed.
# @example Send a message with an embed
# channel.send_embed do |embed|
# embed.title = 'The Ruby logo'
# embed.image = Discordrb::Webhooks::EmbedImage.new(url: 'https://www.ruby-lang.org/images/header-ruby-logo.png')
# end
# @param message [String] The message that should be sent along with the embed. If this is the empty string, only the embed will be shown.
# @param embed [Discordrb::Webhooks::Embed, nil] The embed to start the building process with, or nil if one should be created anew.
# @yield [embed] Yields the embed to allow for easy building inside a block.
# @yieldparam embed [Discordrb::Webhooks::Embed] The embed from the parameters, or a new one.
# @return [Message] The resulting message.
def send_embed(message = '', embed = nil)
embed ||= Discordrb::Webhooks::Embed.new
yield(embed) if block_given?
send_message(message, false, embed)
end
# Sends multiple messages to a channel
# @param content [Array<String>] The messages to send.
def send_multiple(content)
content.each { |e| send_message(e) }
end
# Splits a message into chunks whose length is at most the Discord character limit, then sends them individually.
# Useful for sending long messages, but be wary of rate limits!
def split_send(content)
send_multiple(Discordrb.split_message(content))
end
# Sends a file to this channel. If it is an image, it will be embedded.
# @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed)
# @param caption [string] The caption for the file.
# @param tts [true, false] Whether or not this file's caption should be sent using Discord text-to-speech.
def send_file(file, caption: nil, tts: false)
@bot.send_file(@id, file, caption: caption, tts: tts)
end
# Permanently deletes this channel
def delete
API::Channel.delete(@bot.token, @id)
end
# Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations)
# @param name [String] The new name.
def name=(name)
@name = name
update_channel_data
end
# Sets this channel's topic.
# @param topic [String] The new topic.
def topic=(topic)
raise 'Tried to set topic on voice channel' if voice?
@topic = topic
update_channel_data
end
# Sets this channel's bitrate.
# @param bitrate [Integer] The new bitrate (in bps). Number has to be between 8000-96000 (128000 for VIP servers)
def bitrate=(bitrate)
raise 'Tried to set bitrate on text channel' if text?
@bitrate = bitrate
update_channel_data
end
# Sets this channel's user limit.
# @param limit [Integer] The new user limit. `0` for unlimited, has to be a number between 0-99
def user_limit=(limit)
raise 'Tried to set user_limit on text channel' if text?
@user_limit = limit
update_channel_data
end
alias_method :limit=, :user_limit=
# Sets this channel's position in the list.
# @param position [Integer] The new position.
def position=(position)
@position = position
update_channel_data
end
# Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny
# permission sets, or change an existing one.
# @param thing [User, Role] What to define an overwrite for.
# @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a
# green checkmark on Discord)
# @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red
# cross on Discord)
# @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites
# allow = Discordrb::Permissions.new
# allow.can_mention_everyone = true
# allow.can_send_tts_messages = true
#
# deny = Discordrb::Permissions.new
# deny.can_create_instant_invite = true
#
# channel.define_overwrite(user, allow, deny)
def define_overwrite(thing, allow, deny)
allow_bits = allow.respond_to?(:bits) ? allow.bits : allow
deny_bits = deny.respond_to?(:bits) ? deny.bits : deny
type = if thing.is_a?(User) || thing.is_a?(Member) || thing.is_a?(Recipient) || thing.is_a?(Profile)
:member
elsif thing.is_a? Role
:role
else
raise ArgumentError, '`thing` in define_overwrite needs to be a kind of User (User, Member, Recipient, Profile) or a Role!'
end
API::Channel.update_permission(@bot.token, @id, thing.id, allow_bits, deny_bits, type)
end
# Deletes a permission overwrite for this channel
# @param target [Member, User, Role, Profile, Recipient, #resolve_id] What permission overwrite to delete
def delete_overwrite(target)
raise 'Tried deleting a overwrite for an invalid target' unless target.is_a?(Member) || target.is_a?(User) || target.is_a?(Role) || target.is_a?(Profile) || target.is_a?(Recipient) || target.respond_to?(:resolve_id)
API::Channel.delete_permission(@bot.token, @id, target.resolve_id)
end
# Updates the cached data from another channel.
# @note For internal use only
# @!visibility private
def update_from(other)
@topic = other.topic
@name = other.name
@position = other.position
@topic = other.topic
@recipients = other.recipients
@bitrate = other.bitrate
@user_limit = other.user_limit
@permission_overwrites = other.permission_overwrites
end
# The list of users currently in this channel. For a voice channel, it will return all the members currently
# in that channel. For a text channel, it will return all online members that have permission to read it.
# @return [Array<Member>] the users in this channel
def users
if text?
@server.online_members(include_idle: true).select { |u| u.can_read_messages? self }
elsif voice?
@server.voice_states.map { |id, voice_state| @server.member(id) if !voice_state.voice_channel.nil? && voice_state.voice_channel.id == @id }.compact
end
end
# Retrieves some of this channel's message history.
# @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher
# than 100 it will be treated as 100 on Discord's side.
# @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should
# start at the current message.
# @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start
# as soon as possible with the specified amount.
# @example Count the number of messages in the last 50 messages that contain the letter 'e'.
# message_count = channel.history(50).count {|message| message.content.include? "e"}
# @return [Array<Message>] the retrieved messages.
def history(amount, before_id = nil, after_id = nil)
logs = API::Channel.messages(@bot.token, @id, amount, before_id, after_id)
JSON.parse(logs).map { |message| Message.new(message, @bot) }
end
# Retrieves message history, but only message IDs for use with prune
# @note For internal use only
# @!visibility private
def history_ids(amount, before_id = nil, after_id = nil)
logs = API::Channel.messages(@bot.token, @id, amount, before_id, after_id)
JSON.parse(logs).map { |message| message['id'] }
end
# Returns a single message from this channel's history by ID.
# @param message_id [Integer] The ID of the message to retrieve.
# @return [Message] the retrieved message.
def load_message(message_id)
response = API::Channel.message(@bot.token, @id, message_id)
return Message.new(JSON.parse(response), @bot)
rescue RestClient::ResourceNotFound
return nil
end
alias_method :message, :load_message
# Requests all pinned messages of a channel.
# @return [Array<Message>] the received messages.
def pins
msgs = API::Channel.pinned_messages(@bot.token, @id)
JSON.parse(msgs).map { |msg| Message.new(msg, @bot) }
end
# Delete the last N messages on this channel.
# @param amount [Integer] How many messages to delete. Must be a value between 2 and 100 (Discord limitation)
# @raise [ArgumentError] if the amount of messages is not a value between 2 and 100
def prune(amount)
raise ArgumentError, 'Can only prune between 2 and 100 messages!' unless amount.between?(2, 100)
messages = history_ids(amount)
API::Channel.bulk_delete_messages(@bot.token, @id, messages)
end
# Deletes a collection of messages
# @param messages [Array<Message, Integer>] the messages (or message IDs) to delete. Total must be an amount between 2 and 100 (Discord limitation)
# @raise [ArgumentError] if the amount of messages is not a value between 2 and 100
def delete_messages(messages)
raise ArgumentError, 'Can only delete between 2 and 100 messages!' unless messages.count.between?(2, 100)
messages.map!(&:resolve_id)
API::Channel.bulk_delete_messages(@bot.token, @id, messages)
end
# Updates the cached permission overwrites
# @note For internal use only
# @!visibility private
def update_overwrites(overwrites)
@permission_overwrites = overwrites
end
# Add an {Await} for a message in this channel. This is identical in functionality to adding a
# {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block)
end
# Creates a new invite to this channel.
# @param max_age [Integer] How many seconds this invite should last.
# @param max_uses [Integer] How many times this invite should be able to be used.
# @param temporary [true, false] Whether membership should be temporary (kicked after going offline).
# @return [Invite] the created invite.
def make_invite(max_age = 0, max_uses = 0, temporary = false)
response = API::Channel.create_invite(@bot.token, @id, max_age, max_uses, temporary)
Invite.new(JSON.parse(response), @bot)
end
alias_method :invite, :make_invite
# Starts typing, which displays the typing indicator on the client for five seconds.
# If you want to keep typing you'll have to resend this every five seconds. (An abstraction
# for this will eventually be coming)
def start_typing
API::Channel.start_typing(@bot.token, @id)
end
# Creates a Group channel
# @param user_ids [Array<Integer>] Array of user IDs to add to the new group channel (Excluding
# the recipient of the PM channel).
# @return [Channel] the created channel.
def create_group(user_ids)
raise 'Attempted to create group channel on a non-pm channel!' unless pm?
response = API::Channel.create_group(@bot.token, @id, user_ids.shift)
channel = Channel.new(JSON.parse(response), @bot)
channel.add_group_users(user_ids)
end
# Adds a user to a Group channel
# @param user_ids [Array<#resolve_id>, #resolve_id] User ID or array of user IDs to add to the group channel.
# @return [Channel] the group channel.
def add_group_users(user_ids)
raise 'Attempted to add a user to a non-group channel!' unless group?
user_ids = [user_ids] unless user_ids.is_a? Array
user_ids.each do |user_id|
API::Channel.add_group_user(@bot.token, @id, user_id.resolve_id)
end
self
end
alias_method :add_group_user, :add_group_users
# Removes a user from a group channel.
# @param user_ids [Array<#resolve_id>, #resolve_id] User ID or array of user IDs to remove from the group channel.
# @return [Channel] the group channel.
def remove_group_users(user_ids)
raise 'Attempted to remove a user from a non-group channel!' unless group?
user_ids = [user_ids] unless user_ids.is_a? Array
user_ids.each do |user_id|
API::Channel.remove_group_user(@bot.token, @id, user_id.resolve_id)
end
self
end
alias_method :remove_group_user, :remove_group_users
# Leaves the group
def leave_group
raise 'Attempted to leave a non-group channel!' unless group?
API::Channel.leave_group(@bot.token, @id)
end
alias_method :leave, :leave_group
# The inspect method is overwritten to give more useful output
def inspect
"<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>"
end
# Adds a recipient to a group channel.
# @param recipient [Recipient] the recipient to add to the group
# @raise [ArgumentError] if tried to add a non-recipient
# @note For internal use only
# @!visibility private
def add_recipient(recipient)
raise 'Tried to add recipient to a non-group channel' unless group?
raise ArgumentError, 'Tried to add a non-recipient to a group' unless recipient.is_a?(Recipient)
@recipients << recipient
end
# Removes a recipient from a group channel.
# @param recipient [Recipient] the recipient to remove from the group
# @raise [ArgumentError] if tried to remove a non-recipient
# @note For internal use only
# @!visibility private
def remove_recipient(recipient)
raise 'Tried to add recipient to a non-group channel' unless group?
raise ArgumentError, 'Tried to remove a non-recipient from a group' unless recipient.is_a?(Recipient)
@recipients.delete(recipient)
end
private
def update_channel_data
API::Channel.update(@bot.token, @id, @name, @topic, @position, @bitrate, @user_limit)
end
end
# An Embed object that is contained in a message
# A freshly generated embed object will not appear in a message object
# unless grabbed from its ID in a channel.
class Embed
# @return [Message] the message this embed object is contained in.
attr_reader :message
# @return [String] the URL this embed object is based on.
attr_reader :url
# @return [String, nil] the title of the embed object. `nil` if there is not a title
attr_reader :title
# @return [String, nil] the description of the embed object. `nil` if there is not a description
attr_reader :description
# @return [Symbol] the type of the embed object. Possible types are:
#
# * `:link`
# * `:video`
# * `:image`
attr_reader :type
# @return [EmbedProvider, nil] the provider of the embed object. `nil` is there is not a provider
attr_reader :provider
# @return [EmbedThumbnail, nil] the thumbnail of the embed object. `nil` is there is not a thumbnail
attr_reader :thumbnail
# @return [EmbedAuthor, nil] the author of the embed object. `nil` is there is not an author
attr_reader :author
# @!visibility private
def initialize(data, message)
@message = message
@url = data['url']
@title = data['title']
@type = data['type'].to_sym
@description = data['description']
@provider = data['provider'].nil? ? nil : EmbedProvider.new(data['provider'], self)
@thumbnail = data['thumbnail'].nil? ? nil : EmbedThumbnail.new(data['thumbnail'], self)
@author = data['author'].nil? ? nil : EmbedAuthor.new(data['author'], self)
end
end
# An Embed thumbnail for the embed object
class EmbedThumbnail
# @return [Embed] the embed object this is based on.
attr_reader :embed
# @return [String] the CDN URL this thumbnail can be downloaded at.
attr_reader :url
# @return [String] the thumbnail's proxy URL - I'm not sure what exactly this does, but I think it has something to
# do with CDNs
attr_reader :proxy_url
# @return [Integer] the width of this thumbnail file, in pixels.
attr_reader :width
# @return [Integer] the height of this thumbnail file, in pixels.
attr_reader :height
# @!visibility private
def initialize(data, embed)
@embed = embed
@url = data['url']
@proxy_url = data['proxy_url']
@width = data['width']
@height = data['height']
end
end
# An Embed provider for the embed object
class EmbedProvider
# @return [Embed] the embed object this is based on.
attr_reader :embed
# @return [String] the provider's name.
attr_reader :name
# @return [String, nil] the URL of the provider. `nil` is there is no URL
attr_reader :url
# @!visibility private
def initialize(data, embed)
@embed = embed
@name = data['name']
@url = data['url']
end
end
# An Embed author for the embed object
class EmbedAuthor
# @return [Embed] the embed object this is based on.
attr_reader :embed
# @return [String] the author's name.
attr_reader :name
# @return [String, nil] the URL of the author's website. `nil` is there is no URL
attr_reader :url
# @!visibility private
def initialize(data, embed)
@embed = embed
@name = data['name']
@url = data['url']
end
end
# An attachment to a message
class Attachment
include IDObject
# @return [Message] the message this attachment belongs to.
attr_reader :message
# @return [String] the CDN URL this attachment can be downloaded at.
attr_reader :url
# @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to
# do with CDNs
attr_reader :proxy_url
# @return [String] the attachment's filename.
attr_reader :filename
# @return [Integer] the attachment's file size in bytes.
attr_reader :size
# @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image.
attr_reader :width
# @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image.
attr_reader :height
# @!visibility private
def initialize(data, message, bot)
@bot = bot
@message = message
@url = data['url']
@proxy_url = data['proxy_url']
@filename = data['filename']
@size = data['size']
@width = data['width']
@height = data['height']
end
# @return [true, false] whether this file is an image file.
def image?
!(@width.nil? || @height.nil?)
end
end
# A message on Discord that was sent to a text channel
class Message
include IDObject
# @return [String] the content of this message.
attr_reader :content
alias_method :text, :content
alias_method :to_s, :content
# @return [Member, User] the user that sent this message. (Will be a {Member} most of the time, it should only be a
# {User} for old messages when the author has left the server since then)
attr_reader :author
alias_method :user, :author
alias_method :writer, :author
# @return [Channel] the channel in which this message was sent.
attr_reader :channel
# @return [Time] the timestamp at which this message was sent.
attr_reader :timestamp
# @return [Time] the timestamp at which this message was edited. `nil` if the message was never edited.
attr_reader :edited_timestamp
alias_method :edit_timestamp, :edited_timestamp
# @return [Array<User>] the users that were mentioned in this message.
attr_reader :mentions
# @return [Array<Role>] the roles that were mentioned in this message.
attr_reader :role_mentions
# @return [Array<Attachment>] the files attached to this message.
attr_reader :attachments
# @return [Array<Embed>] the embed objects contained in this message.
attr_reader :embeds
# @return [Hash<String, Reaction>] the reaction objects attached to this message keyed by the name of the reaction
attr_reader :reactions
# @return [true, false] whether the message used Text-To-Speech (TTS) or not.
attr_reader :tts
alias_method :tts?, :tts
# @return [String] used for validating a message was sent
attr_reader :nonce
# @return [true, false] whether the message was edited or not.
attr_reader :edited
alias_method :edited?, :edited
# @return [true, false] whether the message mentioned everyone or not.
attr_reader :mention_everyone
alias_method :mention_everyone?, :mention_everyone
alias_method :mentions_everyone?, :mention_everyone
# @return [true, false] whether the message is pinned or not.
attr_reader :pinned
alias_method :pinned?, :pinned
# @return [Integer, nil] the webhook ID that sent this message, or nil if it wasn't sent through a webhook.
attr_reader :webhook_id
# The discriminator that webhook user accounts have.
ZERO_DISCRIM = '0000'.freeze
# @!visibility private
def initialize(data, bot)
@bot = bot
@content = data['content']
@channel = bot.channel(data['channel_id'].to_i)
@pinned = data['pinned']
@tts = data['tts']
@nonce = data['nonce']
@mention_everyone = data['mention_everyone']
@author = if data['author']
if data['author']['discriminator'] == ZERO_DISCRIM
# This is a webhook user! It would be pointless to try to resolve a member here, so we just create
# a User and return that instead.
Discordrb::LOGGER.debug("Webhook user: #{data['author']['id']}")
User.new(data['author'], @bot)
elsif @channel.private?
# Turn the message user into a recipient - we can't use the channel recipient
# directly because the bot may also send messages to the channel
Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot)
else
member = @channel.server.member(data['author']['id'].to_i)
unless member
Discordrb::LOGGER.debug("Member with ID #{data['author']['id']} not cached (possibly left the server).")
member = @bot.user(data['author']['id'].to_i)
end
member
end
end
@webhook_id = data['webhook_id'].to_i if data['webhook_id']
@timestamp = Time.parse(data['timestamp']) if data['timestamp']
@edited_timestamp = data['edited_timestamp'].nil? ? nil : Time.parse(data['edited_timestamp'])
@edited = !@edited_timestamp.nil?
@id = data['id'].to_i
@emoji = []
@reactions = {}
if data['reactions']
data['reactions'].each do |element|
@reactions[element['emoji']['name']] = Reaction.new(element)
end
end
@mentions = []
if data['mentions']
data['mentions'].each do |element|
@mentions << bot.ensure_user(element)
end
end
@role_mentions = []
# Role mentions can only happen on public servers so make sure we only parse them there
if @channel.text?
if data['mention_roles']
data['mention_roles'].each do |element|
@role_mentions << @channel.server.role(element.to_i)
end
end
end
@attachments = []
@attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } if data['attachments']
@embeds = []
@embeds = data['embeds'].map { |e| Embed.new(e, self) } if data['embeds']
end
# Replies to this message with the specified content.
# @see Channel#send_message
def reply(content)
@channel.send_message(content)
end
# Edits this message to have the specified content instead.
# You can only edit your own messages.
# @param new_content [String] the new content the message should have.
# @param new_embed [Hash, Discordrb::Webhooks::Embed, nil] The new embed the message should have. If nil the message will be changed to have no embed.
# @return [Message] the resulting message.
def edit(new_content, new_embed = nil)
response = API::Channel.edit_message(@bot.token, @channel.id, @id, new_content, [], new_embed ? new_embed.to_hash : nil)
Message.new(JSON.parse(response), @bot)
end
# Deletes this message.
def delete
API::Channel.delete_message(@bot.token, @channel.id, @id)
nil
end
# Pins this message
def pin
API::Channel.pin_message(@bot.token, @channel.id, @id)
@pinned = true
nil
end
# Unpins this message
def unpin
API::Channel.unpin_message(@bot.token, @channel.id, @id)
@pinned = false
nil
end
# Add an {Await} for a message with the same user and channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block)
end
# @return [true, false] whether this message was sent by the current {Bot}.
def from_bot?
@author && @author.current_bot?
end
# @return [true, false] whether this message has been sent over a webhook.
def webhook?
!@webhook_id.nil?
end
# @!visibility private
# @return [Array<String>] the emoji mentions found in the message
def scan_for_emoji
emoji = @content.split
emoji = emoji.grep(/<:(?<name>\w+):(?<id>\d+)>?/)
emoji
end
# @return [Array<Emoji>] the emotes that were used/mentioned in this message (Only returns Emoji the bot has access to, else nil).
def emoji
return if @content.nil?
emoji = scan_for_emoji
emoji.each do |element|
@emoji << @bot.parse_mention(element)
end
@emoji
end
# Check if any emoji got used in this message
# @return [true, false] whether or not any emoji got used
def emoji?
emoji = scan_for_emoji
return true unless emoji.empty?
end
# Check if any reactions got used in this message
# @return [true, false] whether or not this message has reactions
def reactions?
@reactions.any?
end
# Returns the reactions made by the current bot or user
# @return [Array<Reaction>] the reactions
def my_reactions
@reactions.select(&:me)
end
# Reacts to a message
# @param [String, #to_reaction] the unicode emoji, Emoji, or GlobalEmoji
def create_reaction(reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
API::Channel.create_reaction(@bot.token, @channel.id, @id, reaction)
nil
end
alias_method :react, :create_reaction
# Returns the list of users who reacted with a certain reaction
# @param [String, #to_reaction] the unicode emoji, Emoji, or GlobalEmoji
# @return [Array<User>] the users who used this reaction
def reacted_with(reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
response = JSON.parse(API::Channel.get_reactions(@bot.token, @channel.id, @id, reaction))
response.map { |d| User.new(d, @bot) }
end
# Deletes a reaction made by a user on this message
# @param [User, #resolve_id] the user who used this reaction
# @param [String, #to_reaction] the reaction to remove
def delete_reaction(user, reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
API::Channel.delete_user_reaction(@bot.token, @channel.id, @id, reaction, user.resolve_id)
end
# Delete's this clients reaction on this message
# @param [String, #to_reaction] the reaction to remove
def delete_own_reaction(reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
API::Channel.delete_own_reaction(@bot.token, @channel.id, @id, reaction)
end
# Removes all reactions from this message
def delete_all_reactions
API::Channel.delete_all_reactions(@bot.token, @channel.id, @id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>"
end
end
# A reaction to a message
class Reaction
# @return [Integer] the amount of users who have reacted with this reaction
attr_reader :count
# @return [true, false] whether the current bot or user used this reaction
attr_reader :me
alias_method :me?, :me
# @return [Integer] the ID of the emoji, if it was custom
attr_reader :id
# @return [String] the name or unicode representation of the emoji
attr_reader :name
def initialize(data)
@count = data['count']
@me = data['me']
@id = data['emoji']['id'].nil? ? nil : data['emoji']['id'].to_i
@name = data['emoji']['name']
end
end
# Server emoji
class Emoji
include IDObject
# @return [String] the emoji name
attr_reader :name
# @return [Server] the server of this emoji
attr_reader :server
# @return [Array<Role>] roles this emoji is active for
attr_reader :roles
def initialize(data, bot, server)
@bot = bot
@roles = nil
@name = data['name']
@server = server
@id = data['id'].to_i
process_roles(data['roles']) if server
end
# @return [String] the layout to mention it (or have it used) in a message
def mention
"<:#{@name}:#{@id}>"
end
alias_method :use, :mention
alias_method :to_s, :mention
# @return [String] the layout to use this emoji in a reaction
def to_reaction
"#{@name}:#{@id}"
end
# @return [String] the icon URL of the emoji
def icon_url
API.emoji_icon_url(@id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Emoji name=#{@name} id=#{@id}>"
end
# @!visibility private
def process_roles(roles)
@roles = []
return unless roles
roles.each do |role_id|
role = server.role(role_id)
@roles << role
end
end
end
# Emoji that is not tailored to a server
class GlobalEmoji
include IDObject
# @return [String] the emoji name
attr_reader :name
# @return [Hash<Integer => Array<Role>>] roles this emoji is active for in every server
attr_reader :role_associations
def initialize(data, bot)
@bot = bot
@roles = nil
@name = data.name
@id = data.id
@role_associations = Hash.new([])
@role_associations[data.server.id] = data.roles
end
# @return [String] the layout to mention it (or have it used) in a message
def mention
"<:#{@name}:#{@id}>"
end
alias_method :use, :mention
alias_method :to_s, :mention
# @return [String] the layout to use this emoji in a reaction
def to_reaction
"#{@name}:#{@id}"
end
# @return [String] the icon URL of the emoji
def icon_url
API.emoji_icon_url(@id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<GlobalEmoji name=#{@name} id=#{@id}>"
end
# @!visibility private
def process_roles(roles)
new_roles = []
return unless roles
roles.each do
role = server.role(role_id)
new_roles << role
end
new_roles
end
end
# Basic attributes a server should have
module ServerAttributes
# @return [String] this server's name.
attr_reader :name
# @return [String] the hexadecimal ID used to identify this server's icon.
attr_reader :icon_id
# Utility function to get the URL for the icon image
# @return [String] the URL to the icon image
def icon_url
return nil unless @icon_id
API.icon_url(@id, @icon_id)
end
end
# Integration Account
class IntegrationAccount
# @return [String] this account's name.
attr_reader :name
# @return [Integer] this account's ID.
attr_reader :id
def initialize(data)
@name = data['name']
@id = data['id'].to_i
end
end
# Server integration
class Integration
include IDObject
# @return [String] the integration name
attr_reader :name
# @return [Server] the server the integration is linked to
attr_reader :server
# @return [User] the user the integration is linked to
attr_reader :user
# @return [Role, nil] the role that this integration uses for "subscribers"
attr_reader :role
# @return [true, false] whether emoticons are enabled
attr_reader :emoticon
alias_method :emoticon?, :emoticon
# @return [String] the integration type (Youtube, Twitch, etc.)
attr_reader :type
# @return [true, false] whether the integration is enabled
attr_reader :enabled
# @return [true, false] whether the integration is syncing
attr_reader :syncing
# @return [IntegrationAccount] the integration account information
attr_reader :account
# @return [Time] the time the integration was synced at
attr_reader :synced_at
# @return [Symbol] the behaviour of expiring subscribers (:remove = Remove User from role; :kick = Kick User from server)
attr_reader :expire_behaviour
alias_method :expire_behavior, :expire_behaviour
# @return [Integer] the grace period before subscribers expire (in days)
attr_reader :expire_grace_period
def initialize(data, bot, server)
@bot = bot
@name = data['name']
@server = server
@id = data['id'].to_i
@enabled = data['enabled']
@syncing = data['syncing']
@type = data['type']
@account = IntegrationAccount.new(data['account'])
@synced_at = Time.parse(data['synced_at'])
@expire_behaviour = [:remove, :kick][data['expire_behavior']]
@expire_grace_period = data['expire_grace_period']
@user = @bot.ensure_user(data['user'])
@role = server.role(data['role_id']) || nil
@emoticon = data['enable_emoticons']
end
# The inspect method is overwritten to give more useful output
def inspect
"<Integration name=#{@name} id=#{@id} type=#{@type} enabled=#{@enabled}>"
end
end
# A server on Discord
class Server
include IDObject
include ServerAttributes
# @return [String] the region the server is on (e. g. `amsterdam`).
attr_reader :region
# @return [Member] The server owner.
attr_reader :owner
# @return [Array<Channel>] an array of all the channels (text and voice) on this server.
attr_reader :channels
# @return [Array<Role>] an array of all the roles created on this server.
attr_reader :roles
# @return [Hash<Integer, Emoji>] a hash of all the emoji available on this server.
attr_reader :emoji
alias_method :emojis, :emoji
# @return [true, false] whether or not this server is large (members > 100). If it is,
# it means the members list may be inaccurate for a couple seconds after starting up the bot.
attr_reader :large
alias_method :large?, :large
# @return [Array<Symbol>] the features of the server (eg. "INVITE_SPLASH")
attr_reader :features
# @return [Integer] the absolute number of members on this server, offline or not.
attr_reader :member_count
# @return [Symbol] the verification level of the server (:none = none, :low = 'Must have a verified email on their Discord account', :medium = 'Has to be registered with Discord for at least 5 minutes', :high = 'Has to be a member of this server for at least 10 minutes').
attr_reader :verification_level
# @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds.
attr_reader :afk_timeout
# @return [Channel, nil] the AFK voice channel of this server, or nil if none is set
attr_reader :afk_channel
# @return [Hash<Integer => VoiceState>] the hash (user ID => voice state) of voice states of members on this server
attr_reader :voice_states
# @!visibility private
def initialize(data, bot, exists = true)
@bot = bot
@owner_id = data['owner_id'].to_i
@id = data['id'].to_i
update_data(data)
@large = data['large']
@member_count = data['member_count']
@verification_level = [:none, :low, :medium, :high][data['verification_level']]
@splash_id = nil
@embed = nil
@features = data['features'].map { |element| element.downcase.to_sym }
@members = {}
@voice_states = {}
@emoji = {}
process_roles(data['roles'])
process_emoji(data['emojis'])
process_members(data['members'])
process_presences(data['presences'])
process_channels(data['channels'])
process_voice_states(data['voice_states'])
# Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet
@chunked = false
@processed_chunk_members = 0
# Only get the owner of the server actually exists (i. e. not for ServerDeleteEvent)
@owner = member(@owner_id) if exists
end
# @return [Channel] The default channel on this server (usually called #general)
def default_channel
@bot.channel(@id)
end
alias_method :general_channel, :default_channel
# Gets a role on this server based on its ID.
# @param id [Integer] The role ID to look for.
def role(id)
@roles.find { |e| e.id == id }
end
# Gets a member on this server based on user ID
# @param id [Integer] The user ID to look for
# @param request [true, false] Whether the member should be requested from Discord if it's not cached
def member(id, request = true)
id = id.resolve_id
return @members[id] if member_cached?(id)
return nil unless request
member = @bot.member(self, id)
@members[id] = member
rescue
nil
end
# @return [Array<Member>] an array of all the members on this server.
def members
return @members.values if @chunked
@bot.debug("Members for server #{@id} not chunked yet - initiating")
@bot.request_chunks(@id)
sleep 0.05 until @chunked
@members.values
end
alias_method :users, :members
# @return [Array<Integration>] an array of all the integrations connected to this server.
def integrations
integration = JSON.parse(API.server_integrations(@bot.token, @id))
integration.map { |element| Integration.new(element, @bot, self) }
end
# Cache @embed
# @note For internal use only
# @!visibility private
def cache_embed
@embed = JSON.parse(API.server(@bot.token, @id))['embed_enabled'] if @embed.nil?
end
# @return [true, false] whether or not the server has widget enabled
def embed?
cache_embed if @embed.nil?
@embed
end
# @param include_idle [true, false] Whether to count idle members as online.
# @param include_bots [true, false] Whether to include bot accounts in the count.
# @return [Array<Member>] an array of online members on this server.
def online_members(include_idle: false, include_bots: true)
@members.values.select do |e|
((include_idle ? e.idle? : false) || e.online?) && (include_bots ? true : !e.bot_account?)
end
end
alias_method :online_users, :online_members
# @return [Array<Channel>] an array of text channels on this server
def text_channels
@channels.select(&:text?)
end
# @return [Array<Channel>] an array of voice channels on this server
def voice_channels
@channels.select(&:voice?)
end
# @return [String, nil] the widget URL to the server that displays the amount of online members in a
# stylish way. `nil` if the widget is not enabled.
def widget_url
cache_embed if @embed.nil?
return nil unless @embed
API.widget_url(@id)
end
# @param style [Symbol] The style the picture should have. Possible styles are:
# * `:banner1` creates a rectangular image with the server name, member count and icon, a "Powered by Discord" message on the bottom and an arrow on the right.
# * `:banner2` creates a less tall rectangular image that has the same information as `banner1`, but the Discord logo on the right - together with the arrow and separated by a diagonal separator.
# * `:banner3` creates an image similar in size to `banner1`, but it has the arrow in the bottom part, next to the Discord logo and with a "Chat now" text.
# * `:banner4` creates a tall, almost square, image that prominently features the Discord logo at the top and has a "Join my server" in a pill-style button on the bottom. The information about the server is in the same format as the other three `banner` styles.
# * `:shield` creates a very small, long rectangle, of the style you'd find at the top of GitHub `README.md` files. It features a small version of the Discord logo at the left and the member count at the right.
# @return [String, nil] the widget banner URL to the server that displays the amount of online members,
# server icon and server name in a stylish way. `nil` if the widget is not enabled.
def widget_banner_url(style)
return nil unless @embed
cache_embed if @embed.nil?
API.widget_url(@id, style)
end
# @return [String] the hexadecimal ID used to identify this server's splash image for their VIP invite page.
def splash_id
@splash_id = JSON.parse(API.server(@bot.token, @id))['splash'] if @splash_id.nil?
@splash_id
end
# @return [String, nil] the splash image URL for the server's VIP invite page.
# `nil` if there is no splash image.
def splash_url
splash_id if @splash_id.nil?
return nil unless @splash_id
API.splash_url(@id, @splash_id)
end
# Adds a role to the role cache
# @note For internal use only
# @!visibility private
def add_role(role)
@roles << role
end
# Removes a role from the role cache
# @note For internal use only
# @!visibility private
def delete_role(role_id)
@roles.reject! { |r| r.id == role_id }
@members.each do |_, member|
new_roles = member.roles.reject { |r| r.id == role_id }
member.update_roles(new_roles)
end
@channels.each do |channel|
overwrites = channel.permission_overwrites.reject { |id, _| id == role_id }
channel.update_overwrites(overwrites)
end
end
# Adds a member to the member cache.
# @note For internal use only
# @!visibility private
def add_member(member)
@members[member.id] = member
@member_count += 1
end
# Removes a member from the member cache.
# @note For internal use only
# @!visibility private
def delete_member(user_id)
@members.delete(user_id)
@member_count -= 1
end
# Checks whether a member is cached
# @note For internal use only
# @!visibility private
def member_cached?(user_id)
@members.include?(user_id)
end
# Adds a member to the cache
# @note For internal use only
# @!visibility private
def cache_member(member)
@members[member.id] = member
end
# Updates a member's voice state
# @note For internal use only
# @!visibility private
def update_voice_state(data)
user_id = data['user_id'].to_i
if data['channel_id']
unless @voice_states[user_id]
# Create a new voice state for the user
@voice_states[user_id] = VoiceState.new(user_id)
end
# Update the existing voice state (or the one we just created)
channel = @channels_by_id[data['channel_id'].to_i]
@voice_states[user_id].update(
channel,
data['mute'],
data['deaf'],
data['self_mute'],
data['self_deaf']
)
else
# The user is not in a voice channel anymore, so delete its voice state
@voice_states.delete(user_id)
end
end
# Creates a channel on this server with the given name.
# @param name [String] Name of the channel to create
# @param type [Integer] Type of channel to create (0: text, 2: voice)
# @return [Channel] the created channel.
# @raise [ArgumentError] if type is not 0 or 2
def create_channel(name, type = 0)
raise ArgumentError, 'Channel type must be either 0 (text) or 2 (voice)!' unless [0, 2].include?(type)
response = API::Server.create_channel(@bot.token, @id, name, type)
Channel.new(JSON.parse(response), @bot)
end
# Creates a role on this server which can then be modified. It will be initialized (on Discord's side)
# with the regular role defaults the client uses, i. e. name is "new role", permissions are the default,
# colour is the default etc.
# @return [Role] the created role.
def create_role
response = API::Server.create_role(@bot.token, @id)
role = Role.new(JSON.parse(response), @bot, self)
@roles << role
role
end
# @return [Array<User>] a list of banned users on this server.
def bans
users = JSON.parse(API::Server.bans(@bot.token, @id))
users.map { |e| User.new(e['user'], @bot) }
end
# Bans a user from this server.
# @param user [User, #resolve_id] The user to ban.
# @param message_days [Integer] How many days worth of messages sent by the user should be deleted.
def ban(user, message_days = 0)
API::Server.ban_user(@bot.token, @id, user.resolve_id, message_days)
end
# Unbans a previously banned user from this server.
# @param user [User, #resolve_id] The user to unban.
def unban(user)
API::Server.unban_user(@bot.token, @id, user.resolve_id)
end
# Kicks a user from this server.
# @param user [User, #resolve_id] The user to kick.
def kick(user)
API::Server.remove_member(@bot.token, @id, user.resolve_id)
end
# Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed.
# @param user [User] The user to move.
# @param channel [Channel] The voice channel to move into.
def move(user, channel)
API::Server.update_member(@bot.token, @id, user.id, channel_id: channel.id)
end
# Deletes this server. Be aware that this is permanent and impossible to undo, so be careful!
def delete
API::Server.delete(@bot.token, @id)
end
# Leave the server
def leave
API::User.leave_server(@bot.token, @id)
end
# Transfers server ownership to another user.
# @param user [User] The user who should become the new owner.
def owner=(user)
API::Server.transfer_ownership(@bot.token, @id, user.id)
end
# Sets the server's name.
# @param name [String] The new server name.
def name=(name)
update_server_data(name: name)
end
# Moves the server to another region. This will cause a voice interruption of at most a second.
# @param region [String] The new region the server should be in.
def region=(region)
update_server_data(region: region.to_s)
end
# Sets the server's icon.
# @param icon [String, #read] The new icon, in base64-encoded JPG format.
def icon=(icon)
if icon.respond_to? :read
icon_string = 'data:image/jpg;base64,'
icon_string += Base64.strict_encode64(icon.read)
update_server_data(icon: icon_string)
else
update_server_data(icon: icon)
end
end
# Sets the server's AFK channel.
# @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set.
def afk_channel=(afk_channel)
update_server_data(afk_channel_id: afk_channel.resolve_id)
end
# Sets the amount of time after which a user gets moved into the AFK channel.
# @param afk_timeout [Integer] The AFK timeout, in seconds.
def afk_timeout=(afk_timeout)
update_server_data(afk_timeout: afk_timeout)
end
# @return [true, false] whether this server has any emoji or not.
def any_emoji?
@emoji.any?
end
alias_method :has_emoji?, :any_emoji?
alias_method :emoji?, :any_emoji?
# Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field
# @note For internal use only
# @!visibility private
def process_chunk(members)
process_members(members)
@processed_chunk_members += members.length
LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}")
# Don't bother with the rest of the method if it's not truly the last packet
return unless @processed_chunk_members == @member_count
LOGGER.debug("Finished chunking server #{@id}")
# Reset everything to normal
@chunked = true
@processed_chunk_members = 0
end
# Updates the cached data with new data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@region = new_data[:region] || new_data['region'] || @region
@icon_id = new_data[:icon] || new_data['icon'] || @icon_id
@afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout
@afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id
begin
@afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id.nonzero? && (!@afk_channel || @afk_channel_id != @afk_channel.id)
rescue Discordrb::Errors::NoPermission
LOGGER.debug("AFK channel #{@afk_channel_id} on server #{@id} is unreachable, setting to nil even though one exists")
@afk_channel = nil
end
end
# Adds a channel to this server's cache
# @note For internal use only
# @!visibility private
def add_channel(channel)
@channels << channel
@channels_by_id[channel.id] = channel
end
# Deletes a channel from this server's cache
# @note For internal use only
# @!visibility private
def delete_channel(id)
@channels.reject! { |e| e.id == id }
@channels_by_id.delete(id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>"
end
private
def update_server_data(new_data)
API::Server.update(@bot.token, @id,
new_data[:name] || @name,
new_data[:region] || @region,
new_data[:icon_id] || @icon_id,
new_data[:afk_channel_id] || @afk_channel_id,
new_data[:afk_timeout] || @afk_timeout)
update_data(new_data)
end
def process_roles(roles)
# Create roles
@roles = []
@roles_by_id = {}
return unless roles
roles.each do |element|
role = Role.new(element, @bot, self)
@roles << role
@roles_by_id[role.id] = role
end
end
def process_emoji(emoji)
return if emoji.empty?
emoji.each do |element|
new_emoji = Emoji.new(element, @bot, self)
@emoji[new_emoji.id] = new_emoji
end
end
def process_members(members)
return unless members
members.each do |element|
member = Member.new(element, self, @bot)
@members[member.id] = member
end
end
def process_presences(presences)
# Update user statuses with presence info
return unless presences
presences.each do |element|
next unless element['user']
user_id = element['user']['id'].to_i
user = @members[user_id]
if user
user.update_presence(element)
else
LOGGER.warn "Rogue presence update! #{element['user']['id']} on #{@id}"
end
end
end
def process_channels(channels)
@channels = []
@channels_by_id = {}
return unless channels
channels.each do |element|
channel = @bot.ensure_channel(element, self)
@channels << channel
@channels_by_id[channel.id] = channel
end
end
def process_voice_states(voice_states)
return unless voice_states
voice_states.each do |element|
update_voice_state(element)
end
end
end
# A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias
# {ColorRGB} is also available.
class ColourRGB
# @return [Integer] the red part of this colour (0-255).
attr_reader :red
# @return [Integer] the green part of this colour (0-255).
attr_reader :green
# @return [Integer] the blue part of this colour (0-255).
attr_reader :blue
# @return [Integer] the colour's RGB values combined into one integer.
attr_reader :combined
# Make a new colour from the combined value.
# @param combined [Integer] The colour's RGB values combined into one integer
def initialize(combined)
@combined = combined
@red = (combined >> 16) & 0xFF
@green = (combined >> 8) & 0xFF
@blue = combined & 0xFF
end
end
# Alias for the class {ColourRGB}
ColorRGB = ColourRGB
end
Readded #update_emoji_data that was lost in the previous merge (Woops)
# frozen_string_literal: true
# These classes hold relevant Discord data, such as messages or channels.
require 'ostruct'
require 'discordrb/permissions'
require 'discordrb/errors'
require 'discordrb/api'
require 'discordrb/api/channel'
require 'discordrb/api/server'
require 'discordrb/api/invite'
require 'discordrb/api/user'
require 'discordrb/webhooks/embeds'
require 'time'
require 'base64'
# Discordrb module
module Discordrb
# The unix timestamp Discord IDs are based on
DISCORD_EPOCH = 1_420_070_400_000
# Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID.
def self.id_compare(one_id, other)
other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other)
end
# The maximum length a Discord message can have
CHARACTER_LIMIT = 2000
# Splits a message into chunks of 2000 characters. Attempts to split by lines if possible.
# @param msg [String] The message to split.
# @return [Array<String>] the message split into chunks
def self.split_message(msg)
# If the messages is empty, return an empty array
return [] if msg.empty?
# Split the message into lines
lines = msg.lines
# Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become
# [
# [1],
# [1, 2],
# [1, 2, 3],
# [1, 2, 3, 4]
# ]
tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first }
# Join the individual elements together to get an array of strings with consecutively more lines
joined = tri.map(&:join)
# Find the largest element that is still below the character limit, or if none such element exists return the first
ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length }
# If it's still larger than the character limit (none was smaller than it) split it into slices with the length
# being the character limit, otherwise just return an array with one element
ideal_ary = ideal.length > CHARACTER_LIMIT ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal]
# Slice off the ideal part and strip newlines
rest = msg[ideal.length..-1].strip
# If none remains, return an empty array -> we're done
return [] unless rest
# Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array
ideal_ary + split_message(rest)
end
# Mixin for objects that have IDs
module IDObject
# @return [Integer] the ID which uniquely identifies this object across Discord.
attr_reader :id
alias_method :resolve_id, :id
# ID based comparison
def ==(other)
Discordrb.id_compare(@id, other)
end
# Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but
# shouldn't be relied on as Discord might change its algorithm at any time
# @return [Time] when this object was created at
def creation_time
# Milliseconds
ms = (@id >> 22) + DISCORD_EPOCH
Time.at(ms / 1000.0)
end
end
# Mixin for the attributes users should have
module UserAttributes
# @return [String] this user's username
attr_reader :username
alias_method :name, :username
# @return [String] this user's discriminator which is used internally to identify users with identical usernames.
attr_reader :discriminator
alias_method :discrim, :discriminator
alias_method :tag, :discriminator
alias_method :discord_tag, :discriminator
# @return [true, false] whether this user is a Discord bot account
attr_reader :bot_account
alias_method :bot_account?, :bot_account
# @return [String] the ID of this user's current avatar, can be used to generate an avatar URL.
# @see #avatar_url
attr_accessor :avatar_id
# Utility function to mention users in messages
# @return [String] the mention code in the form of <@id>
def mention
"<@#{@id}>"
end
# Utility function to get Discord's distinct representation of a user, i. e. username + discriminator
# @return [String] distinct representation of user
def distinct
"#{@username}##{@discriminator}"
end
# Utility function to get a user's avatar URL.
# @return [String] the URL to the avatar image.
def avatar_url
API::User.avatar_url(@id, @avatar_id)
end
end
# User on Discord, including internal data like discriminators
class User
include IDObject
include UserAttributes
# @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`)
attr_reader :status
# @return [String, nil] the game the user is currently playing, or `nil` if none is being played.
attr_reader :game
# @return [String, nil] the URL to the stream, if the user is currently streaming something.
attr_reader :stream_url
# @return [String, Integer, nil] the type of the stream. Can technically be set to anything, most of the time it
# will be 0 for no stream or 1 for Twitch streams.
attr_reader :stream_type
def initialize(data, bot)
@bot = bot
@username = data['username']
@id = data['id'].to_i
@discriminator = data['discriminator']
@avatar_id = data['avatar']
@roles = {}
@bot_account = false
@bot_account = true if data['bot']
@status = :offline
end
# Get a user's PM channel or send them a PM
# @overload pm
# Creates a private message channel for this user or returns an existing one if it already exists
# @return [Channel] the PM channel to this user.
# @overload pm(content)
# Sends a private to this user.
# @param content [String] The content to send.
# @return [Message] the message sent to this user.
def pm(content = nil)
if content
# Recursively call pm to get the channel, then send a message to it
channel = pm
channel.send_message(content)
else
# If no message was specified, return the PM channel
@bot.pm_channel(@id)
end
end
alias_method :dm, :pm
# Send the user a file.
# @param file [File] The file to send to the user
# @param caption [String] The caption of the file being sent
# @return [Message] the message sent to this user.
def send_file(file, caption = nil)
pm.send_file(file, caption: caption)
end
# Set the user's name
# @note for internal use only
# @!visibility private
def update_username(username)
@username = username
end
# Set the user's presence data
# @note for internal use only
# @!visibility private
def update_presence(data)
@status = data['status'].to_sym
if data['game']
game = data['game']
@game = game['name']
@stream_url = game['url']
@stream_type = game['type']
else
@game = @stream_url = @stream_type = nil
end
end
# Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this
# user's ID as a :from attribute.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block)
end
# Gets the member this user is on a server
# @param server [Server] The server to get the member for
# @return [Member] this user as a member on a particular server
def on(server)
id = server.resolve_id
@bot.server(id).member(@id)
end
# Is the user the bot?
# @return [true, false] whether this user is the bot
def current_bot?
@bot.profile.id == @id
end
# @return [true, false] whether this user is a fake user for a webhook message
def webhook?
@discriminator == Message::ZERO_DISCRIM
end
[:offline, :idle, :online].each do |e|
define_method(e.to_s + '?') do
@status.to_sym == e
end
end
# The inspect method is overwritten to give more useful output
def inspect
"<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>"
end
end
# OAuth Application information
class Application
include IDObject
# @return [String] the application name
attr_reader :name
# @return [String] the application description
attr_reader :description
# @return [Array<String>] the applications origins permitted to use RPC
attr_reader :rpc_origins
# @return [Integer]
attr_reader :flags
# Gets the user object of the owner. May be limited to username, discriminator,
# ID and avatar if the bot cannot reach the owner.
# @return [User] the user object of the owner
attr_reader :owner
def initialize(data, bot)
@bot = bot
@name = data['name']
@id = data['id'].to_i
@description = data['description']
@icon_id = data['icon']
@rpc_origins = data['rpc_origins']
@flags = data['flags']
@owner = @bot.ensure_user(data['owner'])
end
# Utility function to get a application's icon URL.
# @return [String, nil] the URL to the icon image (nil if no image is set).
def icon_url
return nil if @icon_id.nil?
API.app_icon_url(@id, @icon_id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Application name=#{@name} id=#{@id}>"
end
end
# Mixin for the attributes members and private members should have
module MemberAttributes
# @return [Time] when this member joined the server.
attr_reader :joined_at
# @return [String, nil] the nickname this member has, or nil if it has none.
attr_reader :nick
alias_method :nickname, :nick
# @return [Array<Role>] the roles this member has.
attr_reader :roles
# @return [Server] the server this member is on.
attr_reader :server
end
# Mixin to calculate resulting permissions from overrides etc.
module PermissionCalculator
# Checks whether this user can do the particular action, regardless of whether it has the permission defined,
# through for example being the server owner or having the Manage Roles permission
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @example Check if the bot can send messages to a specific channel in a server.
# bot_profile = bot.profile.on(event.server)
# can_send_messages = bot_profile.permission?(:send_messages, channel)
# @return [true, false] whether or not this user has the permission.
def permission?(action, channel = nil)
# If the member is the server owner, it irrevocably has all permissions.
return true if owner?
# First, check whether the user has Manage Roles defined.
# (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a
# Manage Permissions deny overwrite will override Manage Roles, so we can just check for
# Manage Roles once and call it a day.)
return true if defined_permission?(:administrator, channel)
# Otherwise, defer to defined_permission
defined_permission?(action, channel)
end
# Checks whether this user has a particular permission defined (i. e. not implicit, through for example
# Manage Roles)
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @example Check if a member has the Manage Channels permission defined in the server.
# has_manage_channels = member.defined_permission?(:manage_channels)
# @return [true, false] whether or not this user has the permission defined.
def defined_permission?(action, channel = nil)
# Get the permission the user's roles have
role_permission = defined_role_permission?(action, channel)
# Once we have checked the role permission, we have to check the channel overrides for the
# specific user
user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable
# Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role
return role_permission unless user_specific_override
user_specific_override == :allow
end
# Define methods for querying permissions
Discordrb::Permissions::Flags.each_value do |flag|
define_method "can_#{flag}?" do |channel = nil|
permission? flag, channel
end
end
alias_method :can_administrate?, :can_administrator?
private
def defined_role_permission?(action, channel)
# For each role, check if
# (1) the channel explicitly allows or permits an action for the role and
# (2) if the user is allowed to do the action if the channel doesn't specify
@roles.reduce(false) do |can_act, role|
# Get the override defined for the role on the channel
channel_allow = permission_overwrite(action, channel, role.id)
can_act = if channel_allow
# If the channel has an override, check whether it is an allow - if yes,
# the user can act, if not, it can't
channel_allow == :allow
else
# Otherwise defer to the role
role.permissions.instance_variable_get("@#{action}") || can_act
end
can_act
end
end
def permission_overwrite(action, channel, id)
# If no overwrites are defined, or no channel is set, no overwrite will be present
return nil unless channel && channel.permission_overwrites[id]
# Otherwise, check the allow and deny objects
allow = channel.permission_overwrites[id].allow
deny = channel.permission_overwrites[id].deny
if allow.instance_variable_get("@#{action}")
:allow
elsif deny.instance_variable_get("@#{action}")
:deny
end
# If there's no variable defined, nil will implicitly be returned
end
end
# A voice state represents the state of a member's connection to a voice channel. It includes data like the voice
# channel the member is connected to and mute/deaf flags.
class VoiceState
# @return [Integer] the ID of the user whose voice state is represented by this object.
attr_reader :user_id
# @return [true, false] whether this voice state's member is muted server-wide.
attr_reader :mute
# @return [true, false] whether this voice state's member is deafened server-wide.
attr_reader :deaf
# @return [true, false] whether this voice state's member has muted themselves.
attr_reader :self_mute
# @return [true, false] whether this voice state's member has deafened themselves.
attr_reader :self_deaf
# @return [Channel] the voice channel this voice state's member is in.
attr_reader :voice_channel
# @!visibility private
def initialize(user_id)
@user_id = user_id
end
# Update this voice state with new data from Discord
# @note For internal use only.
# @!visibility private
def update(channel, mute, deaf, self_mute, self_deaf)
@voice_channel = channel
@mute = mute
@deaf = deaf
@self_mute = self_mute
@self_deaf = self_deaf
end
end
# A presence represents a
# A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like
# that.
class Member < DelegateClass(User)
# @return [true, false] whether this member is muted server-wide.
def mute
voice_state_attribute(:mute)
end
# @return [true, false] whether this member is deafened server-wide.
def deaf
voice_state_attribute(:deaf)
end
# @return [true, false] whether this member has muted themselves.
def self_mute
voice_state_attribute(:self_mute)
end
# @return [true, false] whether this member has deafened themselves.
def self_deaf
voice_state_attribute(:self_deaf)
end
# @return [Channel] the voice channel this member is in.
def voice_channel
voice_state_attribute(:voice_channel)
end
alias_method :muted?, :mute
alias_method :deafened?, :deaf
alias_method :self_muted?, :self_mute
alias_method :self_deafened?, :self_deaf
include MemberAttributes
# @!visibility private
def initialize(data, server, bot)
@bot = bot
@user = bot.ensure_user(data['user'])
super @user # Initialize the delegate class
# Somehow, Discord doesn't send the server ID in the standard member format...
raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil?
@server = server || bot.server(data['guild_id'].to_i)
# Initialize the roles by getting the roles from the server one-by-one
update_roles(data['roles'])
@nick = data['nick']
@joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil
end
# @return [true, false] whether this member is the server owner.
def owner?
@server.owner == self
end
# @param role [Role, Integer, #resolve_id] the role to check or its ID.
# @return [true, false] whether this member has the specified role.
def role?(role)
role = role.resolve_id
@roles.any? { |e| e.id == role }
end
# Bulk sets a member's roles.
# @param role [Role, Array<Role>] The role(s) to set.
def roles=(role)
role_ids = role_id_array(role)
API::Server.update_member(@bot.token, @server.id, @user.id, roles: role_ids)
end
# Adds and removes roles from a member.
# @param add [Role, Array<Role>] The role(s) to add.
# @param remove [Role, Array<Role>] The role(s) to remove.
# @example Remove the 'Member' role from a user, and add the 'Muted' role to them.
# to_add = server.roles.find {|role| role.name == 'Muted'}
# to_remove = server.roles.find {|role| role.name == 'Member'}
# member.modify_roles(to_add, to_remove)
def modify_roles(add, remove)
add_role_ids = role_id_array(add)
remove_role_ids = role_id_array(remove)
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids - remove_role_ids + add_role_ids).uniq
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids)
end
# Adds one or more roles to this member.
# @param role [Role, Array<Role>] The role(s) to add.
def add_role(role)
role_ids = role_id_array(role)
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids + role_ids).uniq
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids)
end
# Removes one or more roles from this member.
# @param role [Role, Array<Role>] The role(s) to remove.
def remove_role(role)
old_role_ids = @roles.map(&:id)
role_ids = role_id_array(role)
new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) }
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids)
end
# Server deafens this member.
def server_deafen
API::Server.update_member(@bot.token, @server.id, @user.id, deaf: true)
end
# Server undeafens this member.
def server_undeafen
API::Server.update_member(@bot.token, @server.id, @user.id, deaf: false)
end
# Server mutes this member.
def server_mute
API::Server.update_member(@bot.token, @server.id, @user.id, mute: true)
end
# Server unmutes this member.
def server_unmute
API::Server.update_member(@bot.token, @server.id, @user.id, mute: false)
end
# Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage
# Nicknames for other users.
# @param nick [String, nil] The string to set the nickname to, or nil if it should be reset.
def nick=(nick)
# Discord uses the empty string to signify 'no nickname' so we convert nil into that
nick ||= ''
if @user.current_bot?
API::User.change_own_nickname(@bot.token, @server.id, nick)
else
API::Server.update_member(@bot.token, @server.id, @user.id, nick: nick)
end
end
alias_method :nickname=, :nick=
# @return [String] the name the user displays as (nickname if they have one, username otherwise)
def display_name
nickname || username
end
# Update this member's roles
# @note For internal use only.
# @!visibility private
def update_roles(roles)
@roles = roles.map do |role|
role.is_a?(Role) ? role : @server.role(role.to_i)
end
end
# Update this member's nick
# @note For internal use only.
# @!visibility private
def update_nick(nick)
@nick = nick
end
include PermissionCalculator
# Overwriting inspect for debug purposes
def inspect
"<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>"
end
private
# Utility method to get a list of role IDs from one role or an array of roles
def role_id_array(role)
if role.is_a? Array
role.map(&:resolve_id)
else
[role.resolve_id]
end
end
# Utility method to get data out of this member's voice state
def voice_state_attribute(name)
voice_state = @server.voice_states[@user.id]
voice_state.send name if voice_state
end
end
# Recipients are members on private channels - they exist for completeness purposes, but all
# the attributes will be empty.
class Recipient < DelegateClass(User)
include MemberAttributes
# @return [Channel] the private channel this recipient is the recipient of.
attr_reader :channel
# @!visibility private
def initialize(user, channel, bot)
@bot = bot
@channel = channel
raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private?
@user = user
super @user
# Member attributes
@mute = @deaf = @self_mute = @self_deaf = false
@voice_channel = nil
@server = nil
@roles = []
@joined_at = @channel.creation_time
end
# Overwriting inspect for debug purposes
def inspect
"<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>"
end
end
# This class is a special variant of User that represents the bot's user profile (things like own username and the avatar).
# It can be accessed using {Bot#profile}.
class Profile < User
def initialize(data, bot)
super(data, bot)
end
# Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true.
# @return [true]
def current_bot?
true
end
# Sets the bot's username.
# @param username [String] The new username.
def username=(username)
update_profile_data(username: username)
end
alias_method :name=, :username=
# Changes the bot's avatar.
# @param avatar [String, #read] A JPG file to be used as the avatar, either
# something readable (e. g. File Object) or as a data URL.
def avatar=(avatar)
if avatar.respond_to? :read
# Set the file to binary mode if supported, so we don't get problems with Windows
avatar.binmode if avatar.respond_to?(:binmode)
avatar_string = 'data:image/jpg;base64,'
avatar_string += Base64.strict_encode64(avatar.read)
update_profile_data(avatar: avatar_string)
else
update_profile_data(avatar: avatar)
end
end
# Updates the cached profile data with the new one.
# @note For internal use only.
# @!visibility private
def update_data(new_data)
@username = new_data[:username] || @username
@avatar_id = new_data[:avatar_id] || @avatar_id
end
# Sets the user status setting to Online.
# @note Only usable on User accounts.
def online
update_profile_status_setting('online')
end
# Sets the user status setting to Idle.
# @note Only usable on User accounts.
def idle
update_profile_status_setting('idle')
end
# Sets the user status setting to Do Not Disturb.
# @note Only usable on User accounts.
def dnd
update_profile_status_setting('dnd')
end
alias_method(:busy, :dnd)
# Sets the user status setting to Invisible.
# @note Only usable on User accounts.
def invisible
update_profile_status_setting('invisible')
end
# The inspect method is overwritten to give more useful output
def inspect
"<Profile user=#{super}>"
end
private
# Internal handler for updating the user's status setting
def update_profile_status_setting(status)
API::User.change_status_setting(@bot.token, status)
end
def update_profile_data(new_data)
API::User.update_profile(@bot.token,
nil, nil,
new_data[:username] || @username,
new_data.key?(:avatar) ? new_data[:avatar] : @avatar_id)
update_data(new_data)
end
end
# A Discord role that contains permissions and applies to certain users
class Role
include IDObject
# @return [Permissions] this role's permissions.
attr_reader :permissions
# @return [String] this role's name ("new role" if it hasn't been changed)
attr_reader :name
# @return [true, false] whether or not this role should be displayed separately from other users
attr_reader :hoist
# @return [true, false] whether this role can be mentioned using a role mention
attr_reader :mentionable
alias_method :mentionable?, :mentionable
# @return [ColourRGB] the role colour
attr_reader :colour
alias_method :color, :colour
# @return [Integer] the position of this role in the hierarchy
attr_reader :position
# This class is used internally as a wrapper to a Role object that allows easy writing of permission data.
class RoleWriter
# @!visibility private
def initialize(role, token)
@role = role
@token = token
end
# Write the specified permission data to the role, without updating the permission cache
# @param bits [Integer] The packed permissions to write.
def write(bits)
@role.send(:packed=, bits, false)
end
# The inspect method is overridden, in this case to prevent the token being leaked
def inspect
"<RoleWriter role=#{@role} token=...>"
end
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
@server = server
@permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token))
@name = data['name']
@id = data['id'].to_i
@position = data['position']
@hoist = data['hoist']
@mentionable = data['mentionable']
@colour = ColourRGB.new(data['color'])
end
# @return [String] a string that will mention this role, if it is mentionable.
def mention
"<@&#{@id}>"
end
# @return [Array<Member>] an array of members who have this role.
# @note This requests a member chunk if it hasn't for the server before, which may be slow initially
def members
@server.members.select { |m| m.role? role }
end
alias_method :users, :members
# Updates the data cache from another Role object
# @note For internal use only
# @!visibility private
def update_from(other)
@permissions = other.permissions
@name = other.name
@hoist = other.hoist
@colour = other.colour
@position = other.position
end
# Updates the data cache from a hash containing data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@hoist = new_data['hoist'] unless new_data['hoist'].nil?
@hoist = new_data[:hoist] unless new_data[:hoist].nil?
@colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour)
end
# Sets the role name to something new
# @param name [String] The name that should be set
def name=(name)
update_role_data(name: name)
end
# Changes whether or not this role is displayed at the top of the user list
# @param hoist [true, false] The value it should be changed to
def hoist=(hoist)
update_role_data(hoist: hoist)
end
# Changes whether or not this role can be mentioned
# @param mentionable [true, false] The value it should be changed to
def mentionable=(mentionable)
update_role_data(mentionable: mentionable)
end
# Sets the role colour to something new
# @param colour [ColourRGB] The new colour
def colour=(colour)
update_role_data(colour: colour)
end
alias_method :color=, :colour=
# Changes this role's permissions to a fixed bitfield. This allows setting multiple permissions at once with just
# one API call.
#
# Information on how this bitfield is structured can be found at
# https://discordapp.com/developers/docs/topics/permissions.
# @example Remove all permissions from a role
# role.packed = 0
# @param packed [Integer] A bitfield with the desired permissions value.
# @param update_perms [true, false] Whether the internal data should also be updated. This should always be true
# when calling externally.
def packed=(packed, update_perms = true)
update_role_data(permissions: packed)
@permissions.bits = packed if update_perms
end
# Deletes this role. This cannot be undone without recreating the role!
def delete
API::Server.delete_role(@bot.token, @server.id, @id)
@server.delete_role(@id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>"
end
private
def update_role_data(new_data)
API::Server.update_role(@bot.token, @server.id, @id,
new_data[:name] || @name,
(new_data[:colour] || @colour).combined,
new_data[:hoist].nil? ? @hoist : new_data[:hoist],
new_data[:mentionable].nil? ? @mentionable : new_data[:mentionable],
new_data[:permissions] || @permissions.bits)
update_data(new_data)
end
end
# A channel referenced by an invite. It has less data than regular channels, so it's a separate class
class InviteChannel
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [Integer] this channel's type (0: text, 1: private, 2: voice, 3: group).
attr_reader :type
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@type = data['type']
end
end
# A server referenced to by an invite
class InviteServer
include IDObject
# @return [String] this server's name.
attr_reader :name
# @return [String, nil] the hash of the server's invite splash screen (for partnered servers) or nil if none is
# present
attr_reader :splash_hash
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@splash_hash = data['splash_hash']
end
end
# A Discord invite to a channel
class Invite
# @return [InviteChannel] the channel this invite references.
attr_reader :channel
# @return [InviteServer] the server this invite references.
attr_reader :server
# @return [Integer] the amount of uses left on this invite.
attr_reader :uses
alias_method :max_uses, :uses
# @return [User, nil] the user that made this invite. May also be nil if the user can't be determined.
attr_reader :inviter
alias_method :user, :inviter
# @return [true, false] whether or not this invite is temporary.
attr_reader :temporary
alias_method :temporary?, :temporary
# @return [true, false] whether this invite is still valid.
attr_reader :revoked
alias_method :revoked?, :revoked
# @return [String] this invite's code
attr_reader :code
# @!visibility private
def initialize(data, bot)
@bot = bot
@channel = InviteChannel.new(data['channel'], bot)
@server = InviteServer.new(data['guild'], bot)
@uses = data['uses']
@inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil
@temporary = data['temporary']
@revoked = data['revoked']
@code = data['code']
end
# Code based comparison
def ==(other)
other.respond_to?(:code) ? (@code == other.code) : (@code == other)
end
# Deletes this invite
def delete
API::Invite.delete(@bot.token, @code)
end
alias_method :revoke, :delete
# The inspect method is overwritten to give more useful output
def inspect
"<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked}>"
end
# Creates an invite URL.
def url
"https://discord.gg/#{@code}"
end
end
# A Discord channel, including data like the topic
class Channel
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil.
attr_reader :server
# @return [Integer] the type of this channel (0: text, 1: private, 2: voice, 3: group)
attr_reader :type
# @return [Integer, nil] the id of the owner of the group channel or nil if this is not a group channel.
attr_reader :owner_id
# @return [Array<Recipient>, nil] the array of recipients of the private messages, or nil if this is not a Private channel
attr_reader :recipients
# @return [String] the channel's topic
attr_reader :topic
# @return [Integer] the bitrate (in bps) of the channel
attr_reader :bitrate
# @return [Integer] the amount of users that can be in the channel. `0` means it is unlimited.
attr_reader :user_limit
alias_method :limit, :user_limit
# @return [Integer] the channel's position on the channel list
attr_reader :position
# This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the
# `allow` and `deny` properties which are {Permissions} objects respectively.
# @return [Hash<Integer => OpenStruct>] the channel's permission overwrites
attr_reader :permission_overwrites
alias_method :overwrites, :permission_overwrites
# @return [true, false] whether or not this channel is a PM or group channel.
def private?
pm? || group?
end
# @return [String] a string that will mention the channel as a clickable link on Discord.
def mention
"<##{@id}>"
end
# @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel
def recipient
@recipients.first if pm?
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
# data is a sometimes a Hash and other times an array of Hashes, you only want the last one if it's an array
data = data[-1] if data.is_a?(Array)
@id = data['id'].to_i
@type = data['type'] || 0
@topic = data['topic']
@bitrate = data['bitrate']
@user_limit = data['user_limit']
@position = data['position']
if private?
@recipients = []
if data['recipients']
data['recipients'].each do |recipient|
recipient_user = bot.ensure_user(recipient)
@recipients << Recipient.new(recipient_user, self, bot)
end
end
if pm?
@name = @recipients.first.username
else
@name = data['name']
@owner_id = data['owner_id']
end
else
@name = data['name']
@server = if server
server
else
bot.server(data['guild_id'].to_i)
end
end
# Populate permission overwrites
@permission_overwrites = {}
return unless data['permission_overwrites']
data['permission_overwrites'].each do |element|
role_id = element['id'].to_i
deny = Permissions.new(element['deny'])
allow = Permissions.new(element['allow'])
@permission_overwrites[role_id] = OpenStruct.new
@permission_overwrites[role_id].deny = deny
@permission_overwrites[role_id].allow = allow
end
end
# @return [true, false] whether or not this channel is a text channel
def text?
@type.zero?
end
# @return [true, false] whether or not this channel is a PM channel.
def pm?
@type == 1
end
# @return [true, false] whether or not this channel is a voice channel.
def voice?
@type == 2
end
# @return [true, false] whether or not this channel is a group channel.
def group?
@type == 3
end
# Sends a message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
# @param embed [Hash, Discordrb::Webhooks::Embed, nil] The rich embed to append to this message.
# @return [Message] the message that was sent.
def send_message(content, tts = false, embed = nil)
@bot.send_message(@id, content, tts, embed)
end
alias_method :send, :send_message
# Sends a temporary message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param timeout [Float] The amount of time in seconds after which the message sent will be deleted.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
# @param embed [Hash, Discordrb::Webhooks::Embed, nil] The rich embed to append to this message.
def send_temporary_message(content, timeout, tts = false, embed = nil)
@bot.send_temporary_message(@id, content, timeout, tts, embed)
end
# Convenience method to send a message with an embed.
# @example Send a message with an embed
# channel.send_embed do |embed|
# embed.title = 'The Ruby logo'
# embed.image = Discordrb::Webhooks::EmbedImage.new(url: 'https://www.ruby-lang.org/images/header-ruby-logo.png')
# end
# @param message [String] The message that should be sent along with the embed. If this is the empty string, only the embed will be shown.
# @param embed [Discordrb::Webhooks::Embed, nil] The embed to start the building process with, or nil if one should be created anew.
# @yield [embed] Yields the embed to allow for easy building inside a block.
# @yieldparam embed [Discordrb::Webhooks::Embed] The embed from the parameters, or a new one.
# @return [Message] The resulting message.
def send_embed(message = '', embed = nil)
embed ||= Discordrb::Webhooks::Embed.new
yield(embed) if block_given?
send_message(message, false, embed)
end
# Sends multiple messages to a channel
# @param content [Array<String>] The messages to send.
def send_multiple(content)
content.each { |e| send_message(e) }
end
# Splits a message into chunks whose length is at most the Discord character limit, then sends them individually.
# Useful for sending long messages, but be wary of rate limits!
def split_send(content)
send_multiple(Discordrb.split_message(content))
end
# Sends a file to this channel. If it is an image, it will be embedded.
# @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed)
# @param caption [string] The caption for the file.
# @param tts [true, false] Whether or not this file's caption should be sent using Discord text-to-speech.
def send_file(file, caption: nil, tts: false)
@bot.send_file(@id, file, caption: caption, tts: tts)
end
# Permanently deletes this channel
def delete
API::Channel.delete(@bot.token, @id)
end
# Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations)
# @param name [String] The new name.
def name=(name)
@name = name
update_channel_data
end
# Sets this channel's topic.
# @param topic [String] The new topic.
def topic=(topic)
raise 'Tried to set topic on voice channel' if voice?
@topic = topic
update_channel_data
end
# Sets this channel's bitrate.
# @param bitrate [Integer] The new bitrate (in bps). Number has to be between 8000-96000 (128000 for VIP servers)
def bitrate=(bitrate)
raise 'Tried to set bitrate on text channel' if text?
@bitrate = bitrate
update_channel_data
end
# Sets this channel's user limit.
# @param limit [Integer] The new user limit. `0` for unlimited, has to be a number between 0-99
def user_limit=(limit)
raise 'Tried to set user_limit on text channel' if text?
@user_limit = limit
update_channel_data
end
alias_method :limit=, :user_limit=
# Sets this channel's position in the list.
# @param position [Integer] The new position.
def position=(position)
@position = position
update_channel_data
end
# Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny
# permission sets, or change an existing one.
# @param thing [User, Role] What to define an overwrite for.
# @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a
# green checkmark on Discord)
# @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red
# cross on Discord)
# @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites
# allow = Discordrb::Permissions.new
# allow.can_mention_everyone = true
# allow.can_send_tts_messages = true
#
# deny = Discordrb::Permissions.new
# deny.can_create_instant_invite = true
#
# channel.define_overwrite(user, allow, deny)
def define_overwrite(thing, allow, deny)
allow_bits = allow.respond_to?(:bits) ? allow.bits : allow
deny_bits = deny.respond_to?(:bits) ? deny.bits : deny
type = if thing.is_a?(User) || thing.is_a?(Member) || thing.is_a?(Recipient) || thing.is_a?(Profile)
:member
elsif thing.is_a? Role
:role
else
raise ArgumentError, '`thing` in define_overwrite needs to be a kind of User (User, Member, Recipient, Profile) or a Role!'
end
API::Channel.update_permission(@bot.token, @id, thing.id, allow_bits, deny_bits, type)
end
# Deletes a permission overwrite for this channel
# @param target [Member, User, Role, Profile, Recipient, #resolve_id] What permission overwrite to delete
def delete_overwrite(target)
raise 'Tried deleting a overwrite for an invalid target' unless target.is_a?(Member) || target.is_a?(User) || target.is_a?(Role) || target.is_a?(Profile) || target.is_a?(Recipient) || target.respond_to?(:resolve_id)
API::Channel.delete_permission(@bot.token, @id, target.resolve_id)
end
# Updates the cached data from another channel.
# @note For internal use only
# @!visibility private
def update_from(other)
@topic = other.topic
@name = other.name
@position = other.position
@topic = other.topic
@recipients = other.recipients
@bitrate = other.bitrate
@user_limit = other.user_limit
@permission_overwrites = other.permission_overwrites
end
# The list of users currently in this channel. For a voice channel, it will return all the members currently
# in that channel. For a text channel, it will return all online members that have permission to read it.
# @return [Array<Member>] the users in this channel
def users
if text?
@server.online_members(include_idle: true).select { |u| u.can_read_messages? self }
elsif voice?
@server.voice_states.map { |id, voice_state| @server.member(id) if !voice_state.voice_channel.nil? && voice_state.voice_channel.id == @id }.compact
end
end
# Retrieves some of this channel's message history.
# @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher
# than 100 it will be treated as 100 on Discord's side.
# @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should
# start at the current message.
# @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start
# as soon as possible with the specified amount.
# @example Count the number of messages in the last 50 messages that contain the letter 'e'.
# message_count = channel.history(50).count {|message| message.content.include? "e"}
# @return [Array<Message>] the retrieved messages.
def history(amount, before_id = nil, after_id = nil)
logs = API::Channel.messages(@bot.token, @id, amount, before_id, after_id)
JSON.parse(logs).map { |message| Message.new(message, @bot) }
end
# Retrieves message history, but only message IDs for use with prune
# @note For internal use only
# @!visibility private
def history_ids(amount, before_id = nil, after_id = nil)
logs = API::Channel.messages(@bot.token, @id, amount, before_id, after_id)
JSON.parse(logs).map { |message| message['id'] }
end
# Returns a single message from this channel's history by ID.
# @param message_id [Integer] The ID of the message to retrieve.
# @return [Message] the retrieved message.
def load_message(message_id)
response = API::Channel.message(@bot.token, @id, message_id)
return Message.new(JSON.parse(response), @bot)
rescue RestClient::ResourceNotFound
return nil
end
alias_method :message, :load_message
# Requests all pinned messages of a channel.
# @return [Array<Message>] the received messages.
def pins
msgs = API::Channel.pinned_messages(@bot.token, @id)
JSON.parse(msgs).map { |msg| Message.new(msg, @bot) }
end
# Delete the last N messages on this channel.
# @param amount [Integer] How many messages to delete. Must be a value between 2 and 100 (Discord limitation)
# @raise [ArgumentError] if the amount of messages is not a value between 2 and 100
def prune(amount)
raise ArgumentError, 'Can only prune between 2 and 100 messages!' unless amount.between?(2, 100)
messages = history_ids(amount)
API::Channel.bulk_delete_messages(@bot.token, @id, messages)
end
# Deletes a collection of messages
# @param messages [Array<Message, Integer>] the messages (or message IDs) to delete. Total must be an amount between 2 and 100 (Discord limitation)
# @raise [ArgumentError] if the amount of messages is not a value between 2 and 100
def delete_messages(messages)
raise ArgumentError, 'Can only delete between 2 and 100 messages!' unless messages.count.between?(2, 100)
messages.map!(&:resolve_id)
API::Channel.bulk_delete_messages(@bot.token, @id, messages)
end
# Updates the cached permission overwrites
# @note For internal use only
# @!visibility private
def update_overwrites(overwrites)
@permission_overwrites = overwrites
end
# Add an {Await} for a message in this channel. This is identical in functionality to adding a
# {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block)
end
# Creates a new invite to this channel.
# @param max_age [Integer] How many seconds this invite should last.
# @param max_uses [Integer] How many times this invite should be able to be used.
# @param temporary [true, false] Whether membership should be temporary (kicked after going offline).
# @return [Invite] the created invite.
def make_invite(max_age = 0, max_uses = 0, temporary = false)
response = API::Channel.create_invite(@bot.token, @id, max_age, max_uses, temporary)
Invite.new(JSON.parse(response), @bot)
end
alias_method :invite, :make_invite
# Starts typing, which displays the typing indicator on the client for five seconds.
# If you want to keep typing you'll have to resend this every five seconds. (An abstraction
# for this will eventually be coming)
def start_typing
API::Channel.start_typing(@bot.token, @id)
end
# Creates a Group channel
# @param user_ids [Array<Integer>] Array of user IDs to add to the new group channel (Excluding
# the recipient of the PM channel).
# @return [Channel] the created channel.
def create_group(user_ids)
raise 'Attempted to create group channel on a non-pm channel!' unless pm?
response = API::Channel.create_group(@bot.token, @id, user_ids.shift)
channel = Channel.new(JSON.parse(response), @bot)
channel.add_group_users(user_ids)
end
# Adds a user to a Group channel
# @param user_ids [Array<#resolve_id>, #resolve_id] User ID or array of user IDs to add to the group channel.
# @return [Channel] the group channel.
def add_group_users(user_ids)
raise 'Attempted to add a user to a non-group channel!' unless group?
user_ids = [user_ids] unless user_ids.is_a? Array
user_ids.each do |user_id|
API::Channel.add_group_user(@bot.token, @id, user_id.resolve_id)
end
self
end
alias_method :add_group_user, :add_group_users
# Removes a user from a group channel.
# @param user_ids [Array<#resolve_id>, #resolve_id] User ID or array of user IDs to remove from the group channel.
# @return [Channel] the group channel.
def remove_group_users(user_ids)
raise 'Attempted to remove a user from a non-group channel!' unless group?
user_ids = [user_ids] unless user_ids.is_a? Array
user_ids.each do |user_id|
API::Channel.remove_group_user(@bot.token, @id, user_id.resolve_id)
end
self
end
alias_method :remove_group_user, :remove_group_users
# Leaves the group
def leave_group
raise 'Attempted to leave a non-group channel!' unless group?
API::Channel.leave_group(@bot.token, @id)
end
alias_method :leave, :leave_group
# The inspect method is overwritten to give more useful output
def inspect
"<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>"
end
# Adds a recipient to a group channel.
# @param recipient [Recipient] the recipient to add to the group
# @raise [ArgumentError] if tried to add a non-recipient
# @note For internal use only
# @!visibility private
def add_recipient(recipient)
raise 'Tried to add recipient to a non-group channel' unless group?
raise ArgumentError, 'Tried to add a non-recipient to a group' unless recipient.is_a?(Recipient)
@recipients << recipient
end
# Removes a recipient from a group channel.
# @param recipient [Recipient] the recipient to remove from the group
# @raise [ArgumentError] if tried to remove a non-recipient
# @note For internal use only
# @!visibility private
def remove_recipient(recipient)
raise 'Tried to add recipient to a non-group channel' unless group?
raise ArgumentError, 'Tried to remove a non-recipient from a group' unless recipient.is_a?(Recipient)
@recipients.delete(recipient)
end
private
def update_channel_data
API::Channel.update(@bot.token, @id, @name, @topic, @position, @bitrate, @user_limit)
end
end
# An Embed object that is contained in a message
# A freshly generated embed object will not appear in a message object
# unless grabbed from its ID in a channel.
class Embed
# @return [Message] the message this embed object is contained in.
attr_reader :message
# @return [String] the URL this embed object is based on.
attr_reader :url
# @return [String, nil] the title of the embed object. `nil` if there is not a title
attr_reader :title
# @return [String, nil] the description of the embed object. `nil` if there is not a description
attr_reader :description
# @return [Symbol] the type of the embed object. Possible types are:
#
# * `:link`
# * `:video`
# * `:image`
attr_reader :type
# @return [EmbedProvider, nil] the provider of the embed object. `nil` is there is not a provider
attr_reader :provider
# @return [EmbedThumbnail, nil] the thumbnail of the embed object. `nil` is there is not a thumbnail
attr_reader :thumbnail
# @return [EmbedAuthor, nil] the author of the embed object. `nil` is there is not an author
attr_reader :author
# @!visibility private
def initialize(data, message)
@message = message
@url = data['url']
@title = data['title']
@type = data['type'].to_sym
@description = data['description']
@provider = data['provider'].nil? ? nil : EmbedProvider.new(data['provider'], self)
@thumbnail = data['thumbnail'].nil? ? nil : EmbedThumbnail.new(data['thumbnail'], self)
@author = data['author'].nil? ? nil : EmbedAuthor.new(data['author'], self)
end
end
# An Embed thumbnail for the embed object
class EmbedThumbnail
# @return [Embed] the embed object this is based on.
attr_reader :embed
# @return [String] the CDN URL this thumbnail can be downloaded at.
attr_reader :url
# @return [String] the thumbnail's proxy URL - I'm not sure what exactly this does, but I think it has something to
# do with CDNs
attr_reader :proxy_url
# @return [Integer] the width of this thumbnail file, in pixels.
attr_reader :width
# @return [Integer] the height of this thumbnail file, in pixels.
attr_reader :height
# @!visibility private
def initialize(data, embed)
@embed = embed
@url = data['url']
@proxy_url = data['proxy_url']
@width = data['width']
@height = data['height']
end
end
# An Embed provider for the embed object
class EmbedProvider
# @return [Embed] the embed object this is based on.
attr_reader :embed
# @return [String] the provider's name.
attr_reader :name
# @return [String, nil] the URL of the provider. `nil` is there is no URL
attr_reader :url
# @!visibility private
def initialize(data, embed)
@embed = embed
@name = data['name']
@url = data['url']
end
end
# An Embed author for the embed object
class EmbedAuthor
# @return [Embed] the embed object this is based on.
attr_reader :embed
# @return [String] the author's name.
attr_reader :name
# @return [String, nil] the URL of the author's website. `nil` is there is no URL
attr_reader :url
# @!visibility private
def initialize(data, embed)
@embed = embed
@name = data['name']
@url = data['url']
end
end
# An attachment to a message
class Attachment
include IDObject
# @return [Message] the message this attachment belongs to.
attr_reader :message
# @return [String] the CDN URL this attachment can be downloaded at.
attr_reader :url
# @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to
# do with CDNs
attr_reader :proxy_url
# @return [String] the attachment's filename.
attr_reader :filename
# @return [Integer] the attachment's file size in bytes.
attr_reader :size
# @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image.
attr_reader :width
# @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image.
attr_reader :height
# @!visibility private
def initialize(data, message, bot)
@bot = bot
@message = message
@url = data['url']
@proxy_url = data['proxy_url']
@filename = data['filename']
@size = data['size']
@width = data['width']
@height = data['height']
end
# @return [true, false] whether this file is an image file.
def image?
!(@width.nil? || @height.nil?)
end
end
# A message on Discord that was sent to a text channel
class Message
include IDObject
# @return [String] the content of this message.
attr_reader :content
alias_method :text, :content
alias_method :to_s, :content
# @return [Member, User] the user that sent this message. (Will be a {Member} most of the time, it should only be a
# {User} for old messages when the author has left the server since then)
attr_reader :author
alias_method :user, :author
alias_method :writer, :author
# @return [Channel] the channel in which this message was sent.
attr_reader :channel
# @return [Time] the timestamp at which this message was sent.
attr_reader :timestamp
# @return [Time] the timestamp at which this message was edited. `nil` if the message was never edited.
attr_reader :edited_timestamp
alias_method :edit_timestamp, :edited_timestamp
# @return [Array<User>] the users that were mentioned in this message.
attr_reader :mentions
# @return [Array<Role>] the roles that were mentioned in this message.
attr_reader :role_mentions
# @return [Array<Attachment>] the files attached to this message.
attr_reader :attachments
# @return [Array<Embed>] the embed objects contained in this message.
attr_reader :embeds
# @return [Hash<String, Reaction>] the reaction objects attached to this message keyed by the name of the reaction
attr_reader :reactions
# @return [true, false] whether the message used Text-To-Speech (TTS) or not.
attr_reader :tts
alias_method :tts?, :tts
# @return [String] used for validating a message was sent
attr_reader :nonce
# @return [true, false] whether the message was edited or not.
attr_reader :edited
alias_method :edited?, :edited
# @return [true, false] whether the message mentioned everyone or not.
attr_reader :mention_everyone
alias_method :mention_everyone?, :mention_everyone
alias_method :mentions_everyone?, :mention_everyone
# @return [true, false] whether the message is pinned or not.
attr_reader :pinned
alias_method :pinned?, :pinned
# @return [Integer, nil] the webhook ID that sent this message, or nil if it wasn't sent through a webhook.
attr_reader :webhook_id
# The discriminator that webhook user accounts have.
ZERO_DISCRIM = '0000'.freeze
# @!visibility private
def initialize(data, bot)
@bot = bot
@content = data['content']
@channel = bot.channel(data['channel_id'].to_i)
@pinned = data['pinned']
@tts = data['tts']
@nonce = data['nonce']
@mention_everyone = data['mention_everyone']
@author = if data['author']
if data['author']['discriminator'] == ZERO_DISCRIM
# This is a webhook user! It would be pointless to try to resolve a member here, so we just create
# a User and return that instead.
Discordrb::LOGGER.debug("Webhook user: #{data['author']['id']}")
User.new(data['author'], @bot)
elsif @channel.private?
# Turn the message user into a recipient - we can't use the channel recipient
# directly because the bot may also send messages to the channel
Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot)
else
member = @channel.server.member(data['author']['id'].to_i)
unless member
Discordrb::LOGGER.debug("Member with ID #{data['author']['id']} not cached (possibly left the server).")
member = @bot.user(data['author']['id'].to_i)
end
member
end
end
@webhook_id = data['webhook_id'].to_i if data['webhook_id']
@timestamp = Time.parse(data['timestamp']) if data['timestamp']
@edited_timestamp = data['edited_timestamp'].nil? ? nil : Time.parse(data['edited_timestamp'])
@edited = !@edited_timestamp.nil?
@id = data['id'].to_i
@emoji = []
@reactions = {}
if data['reactions']
data['reactions'].each do |element|
@reactions[element['emoji']['name']] = Reaction.new(element)
end
end
@mentions = []
if data['mentions']
data['mentions'].each do |element|
@mentions << bot.ensure_user(element)
end
end
@role_mentions = []
# Role mentions can only happen on public servers so make sure we only parse them there
if @channel.text?
if data['mention_roles']
data['mention_roles'].each do |element|
@role_mentions << @channel.server.role(element.to_i)
end
end
end
@attachments = []
@attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } if data['attachments']
@embeds = []
@embeds = data['embeds'].map { |e| Embed.new(e, self) } if data['embeds']
end
# Replies to this message with the specified content.
# @see Channel#send_message
def reply(content)
@channel.send_message(content)
end
# Edits this message to have the specified content instead.
# You can only edit your own messages.
# @param new_content [String] the new content the message should have.
# @param new_embed [Hash, Discordrb::Webhooks::Embed, nil] The new embed the message should have. If nil the message will be changed to have no embed.
# @return [Message] the resulting message.
def edit(new_content, new_embed = nil)
response = API::Channel.edit_message(@bot.token, @channel.id, @id, new_content, [], new_embed ? new_embed.to_hash : nil)
Message.new(JSON.parse(response), @bot)
end
# Deletes this message.
def delete
API::Channel.delete_message(@bot.token, @channel.id, @id)
nil
end
# Pins this message
def pin
API::Channel.pin_message(@bot.token, @channel.id, @id)
@pinned = true
nil
end
# Unpins this message
def unpin
API::Channel.unpin_message(@bot.token, @channel.id, @id)
@pinned = false
nil
end
# Add an {Await} for a message with the same user and channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block)
end
# @return [true, false] whether this message was sent by the current {Bot}.
def from_bot?
@author && @author.current_bot?
end
# @return [true, false] whether this message has been sent over a webhook.
def webhook?
!@webhook_id.nil?
end
# @!visibility private
# @return [Array<String>] the emoji mentions found in the message
def scan_for_emoji
emoji = @content.split
emoji = emoji.grep(/<:(?<name>\w+):(?<id>\d+)>?/)
emoji
end
# @return [Array<Emoji>] the emotes that were used/mentioned in this message (Only returns Emoji the bot has access to, else nil).
def emoji
return if @content.nil?
emoji = scan_for_emoji
emoji.each do |element|
@emoji << @bot.parse_mention(element)
end
@emoji
end
# Check if any emoji got used in this message
# @return [true, false] whether or not any emoji got used
def emoji?
emoji = scan_for_emoji
return true unless emoji.empty?
end
# Check if any reactions got used in this message
# @return [true, false] whether or not this message has reactions
def reactions?
@reactions.any?
end
# Returns the reactions made by the current bot or user
# @return [Array<Reaction>] the reactions
def my_reactions
@reactions.select(&:me)
end
# Reacts to a message
# @param [String, #to_reaction] the unicode emoji, Emoji, or GlobalEmoji
def create_reaction(reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
API::Channel.create_reaction(@bot.token, @channel.id, @id, reaction)
nil
end
alias_method :react, :create_reaction
# Returns the list of users who reacted with a certain reaction
# @param [String, #to_reaction] the unicode emoji, Emoji, or GlobalEmoji
# @return [Array<User>] the users who used this reaction
def reacted_with(reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
response = JSON.parse(API::Channel.get_reactions(@bot.token, @channel.id, @id, reaction))
response.map { |d| User.new(d, @bot) }
end
# Deletes a reaction made by a user on this message
# @param [User, #resolve_id] the user who used this reaction
# @param [String, #to_reaction] the reaction to remove
def delete_reaction(user, reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
API::Channel.delete_user_reaction(@bot.token, @channel.id, @id, reaction, user.resolve_id)
end
# Delete's this clients reaction on this message
# @param [String, #to_reaction] the reaction to remove
def delete_own_reaction(reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
API::Channel.delete_own_reaction(@bot.token, @channel.id, @id, reaction)
end
# Removes all reactions from this message
def delete_all_reactions
API::Channel.delete_all_reactions(@bot.token, @channel.id, @id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>"
end
end
# A reaction to a message
class Reaction
# @return [Integer] the amount of users who have reacted with this reaction
attr_reader :count
# @return [true, false] whether the current bot or user used this reaction
attr_reader :me
alias_method :me?, :me
# @return [Integer] the ID of the emoji, if it was custom
attr_reader :id
# @return [String] the name or unicode representation of the emoji
attr_reader :name
def initialize(data)
@count = data['count']
@me = data['me']
@id = data['emoji']['id'].nil? ? nil : data['emoji']['id'].to_i
@name = data['emoji']['name']
end
end
# Server emoji
class Emoji
include IDObject
# @return [String] the emoji name
attr_reader :name
# @return [Server] the server of this emoji
attr_reader :server
# @return [Array<Role>] roles this emoji is active for
attr_reader :roles
def initialize(data, bot, server)
@bot = bot
@roles = nil
@name = data['name']
@server = server
@id = data['id'].to_i
process_roles(data['roles']) if server
end
# @return [String] the layout to mention it (or have it used) in a message
def mention
"<:#{@name}:#{@id}>"
end
alias_method :use, :mention
alias_method :to_s, :mention
# @return [String] the layout to use this emoji in a reaction
def to_reaction
"#{@name}:#{@id}"
end
# @return [String] the icon URL of the emoji
def icon_url
API.emoji_icon_url(@id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Emoji name=#{@name} id=#{@id}>"
end
# @!visibility private
def process_roles(roles)
@roles = []
return unless roles
roles.each do |role_id|
role = server.role(role_id)
@roles << role
end
end
end
# Emoji that is not tailored to a server
class GlobalEmoji
include IDObject
# @return [String] the emoji name
attr_reader :name
# @return [Hash<Integer => Array<Role>>] roles this emoji is active for in every server
attr_reader :role_associations
def initialize(data, bot)
@bot = bot
@roles = nil
@name = data.name
@id = data.id
@role_associations = Hash.new([])
@role_associations[data.server.id] = data.roles
end
# @return [String] the layout to mention it (or have it used) in a message
def mention
"<:#{@name}:#{@id}>"
end
alias_method :use, :mention
alias_method :to_s, :mention
# @return [String] the layout to use this emoji in a reaction
def to_reaction
"#{@name}:#{@id}"
end
# @return [String] the icon URL of the emoji
def icon_url
API.emoji_icon_url(@id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<GlobalEmoji name=#{@name} id=#{@id}>"
end
# @!visibility private
def process_roles(roles)
new_roles = []
return unless roles
roles.each do
role = server.role(role_id)
new_roles << role
end
new_roles
end
end
# Basic attributes a server should have
module ServerAttributes
# @return [String] this server's name.
attr_reader :name
# @return [String] the hexadecimal ID used to identify this server's icon.
attr_reader :icon_id
# Utility function to get the URL for the icon image
# @return [String] the URL to the icon image
def icon_url
return nil unless @icon_id
API.icon_url(@id, @icon_id)
end
end
# Integration Account
class IntegrationAccount
# @return [String] this account's name.
attr_reader :name
# @return [Integer] this account's ID.
attr_reader :id
def initialize(data)
@name = data['name']
@id = data['id'].to_i
end
end
# Server integration
class Integration
include IDObject
# @return [String] the integration name
attr_reader :name
# @return [Server] the server the integration is linked to
attr_reader :server
# @return [User] the user the integration is linked to
attr_reader :user
# @return [Role, nil] the role that this integration uses for "subscribers"
attr_reader :role
# @return [true, false] whether emoticons are enabled
attr_reader :emoticon
alias_method :emoticon?, :emoticon
# @return [String] the integration type (Youtube, Twitch, etc.)
attr_reader :type
# @return [true, false] whether the integration is enabled
attr_reader :enabled
# @return [true, false] whether the integration is syncing
attr_reader :syncing
# @return [IntegrationAccount] the integration account information
attr_reader :account
# @return [Time] the time the integration was synced at
attr_reader :synced_at
# @return [Symbol] the behaviour of expiring subscribers (:remove = Remove User from role; :kick = Kick User from server)
attr_reader :expire_behaviour
alias_method :expire_behavior, :expire_behaviour
# @return [Integer] the grace period before subscribers expire (in days)
attr_reader :expire_grace_period
def initialize(data, bot, server)
@bot = bot
@name = data['name']
@server = server
@id = data['id'].to_i
@enabled = data['enabled']
@syncing = data['syncing']
@type = data['type']
@account = IntegrationAccount.new(data['account'])
@synced_at = Time.parse(data['synced_at'])
@expire_behaviour = [:remove, :kick][data['expire_behavior']]
@expire_grace_period = data['expire_grace_period']
@user = @bot.ensure_user(data['user'])
@role = server.role(data['role_id']) || nil
@emoticon = data['enable_emoticons']
end
# The inspect method is overwritten to give more useful output
def inspect
"<Integration name=#{@name} id=#{@id} type=#{@type} enabled=#{@enabled}>"
end
end
# A server on Discord
class Server
include IDObject
include ServerAttributes
# @return [String] the region the server is on (e. g. `amsterdam`).
attr_reader :region
# @return [Member] The server owner.
attr_reader :owner
# @return [Array<Channel>] an array of all the channels (text and voice) on this server.
attr_reader :channels
# @return [Array<Role>] an array of all the roles created on this server.
attr_reader :roles
# @return [Hash<Integer, Emoji>] a hash of all the emoji available on this server.
attr_reader :emoji
alias_method :emojis, :emoji
# @return [true, false] whether or not this server is large (members > 100). If it is,
# it means the members list may be inaccurate for a couple seconds after starting up the bot.
attr_reader :large
alias_method :large?, :large
# @return [Array<Symbol>] the features of the server (eg. "INVITE_SPLASH")
attr_reader :features
# @return [Integer] the absolute number of members on this server, offline or not.
attr_reader :member_count
# @return [Symbol] the verification level of the server (:none = none, :low = 'Must have a verified email on their Discord account', :medium = 'Has to be registered with Discord for at least 5 minutes', :high = 'Has to be a member of this server for at least 10 minutes').
attr_reader :verification_level
# @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds.
attr_reader :afk_timeout
# @return [Channel, nil] the AFK voice channel of this server, or nil if none is set
attr_reader :afk_channel
# @return [Hash<Integer => VoiceState>] the hash (user ID => voice state) of voice states of members on this server
attr_reader :voice_states
# @!visibility private
def initialize(data, bot, exists = true)
@bot = bot
@owner_id = data['owner_id'].to_i
@id = data['id'].to_i
update_data(data)
@large = data['large']
@member_count = data['member_count']
@verification_level = [:none, :low, :medium, :high][data['verification_level']]
@splash_id = nil
@embed = nil
@features = data['features'].map { |element| element.downcase.to_sym }
@members = {}
@voice_states = {}
@emoji = {}
process_roles(data['roles'])
process_emoji(data['emojis'])
process_members(data['members'])
process_presences(data['presences'])
process_channels(data['channels'])
process_voice_states(data['voice_states'])
# Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet
@chunked = false
@processed_chunk_members = 0
# Only get the owner of the server actually exists (i. e. not for ServerDeleteEvent)
@owner = member(@owner_id) if exists
end
# @return [Channel] The default channel on this server (usually called #general)
def default_channel
@bot.channel(@id)
end
alias_method :general_channel, :default_channel
# Gets a role on this server based on its ID.
# @param id [Integer] The role ID to look for.
def role(id)
@roles.find { |e| e.id == id }
end
# Gets a member on this server based on user ID
# @param id [Integer] The user ID to look for
# @param request [true, false] Whether the member should be requested from Discord if it's not cached
def member(id, request = true)
id = id.resolve_id
return @members[id] if member_cached?(id)
return nil unless request
member = @bot.member(self, id)
@members[id] = member
rescue
nil
end
# @return [Array<Member>] an array of all the members on this server.
def members
return @members.values if @chunked
@bot.debug("Members for server #{@id} not chunked yet - initiating")
@bot.request_chunks(@id)
sleep 0.05 until @chunked
@members.values
end
alias_method :users, :members
# @return [Array<Integration>] an array of all the integrations connected to this server.
def integrations
integration = JSON.parse(API.server_integrations(@bot.token, @id))
integration.map { |element| Integration.new(element, @bot, self) }
end
# Cache @embed
# @note For internal use only
# @!visibility private
def cache_embed
@embed = JSON.parse(API.server(@bot.token, @id))['embed_enabled'] if @embed.nil?
end
# @return [true, false] whether or not the server has widget enabled
def embed?
cache_embed if @embed.nil?
@embed
end
# @param include_idle [true, false] Whether to count idle members as online.
# @param include_bots [true, false] Whether to include bot accounts in the count.
# @return [Array<Member>] an array of online members on this server.
def online_members(include_idle: false, include_bots: true)
@members.values.select do |e|
((include_idle ? e.idle? : false) || e.online?) && (include_bots ? true : !e.bot_account?)
end
end
alias_method :online_users, :online_members
# @return [Array<Channel>] an array of text channels on this server
def text_channels
@channels.select(&:text?)
end
# @return [Array<Channel>] an array of voice channels on this server
def voice_channels
@channels.select(&:voice?)
end
# @return [String, nil] the widget URL to the server that displays the amount of online members in a
# stylish way. `nil` if the widget is not enabled.
def widget_url
cache_embed if @embed.nil?
return nil unless @embed
API.widget_url(@id)
end
# @param style [Symbol] The style the picture should have. Possible styles are:
# * `:banner1` creates a rectangular image with the server name, member count and icon, a "Powered by Discord" message on the bottom and an arrow on the right.
# * `:banner2` creates a less tall rectangular image that has the same information as `banner1`, but the Discord logo on the right - together with the arrow and separated by a diagonal separator.
# * `:banner3` creates an image similar in size to `banner1`, but it has the arrow in the bottom part, next to the Discord logo and with a "Chat now" text.
# * `:banner4` creates a tall, almost square, image that prominently features the Discord logo at the top and has a "Join my server" in a pill-style button on the bottom. The information about the server is in the same format as the other three `banner` styles.
# * `:shield` creates a very small, long rectangle, of the style you'd find at the top of GitHub `README.md` files. It features a small version of the Discord logo at the left and the member count at the right.
# @return [String, nil] the widget banner URL to the server that displays the amount of online members,
# server icon and server name in a stylish way. `nil` if the widget is not enabled.
def widget_banner_url(style)
return nil unless @embed
cache_embed if @embed.nil?
API.widget_url(@id, style)
end
# @return [String] the hexadecimal ID used to identify this server's splash image for their VIP invite page.
def splash_id
@splash_id = JSON.parse(API.server(@bot.token, @id))['splash'] if @splash_id.nil?
@splash_id
end
# @return [String, nil] the splash image URL for the server's VIP invite page.
# `nil` if there is no splash image.
def splash_url
splash_id if @splash_id.nil?
return nil unless @splash_id
API.splash_url(@id, @splash_id)
end
# Adds a role to the role cache
# @note For internal use only
# @!visibility private
def add_role(role)
@roles << role
end
# Removes a role from the role cache
# @note For internal use only
# @!visibility private
def delete_role(role_id)
@roles.reject! { |r| r.id == role_id }
@members.each do |_, member|
new_roles = member.roles.reject { |r| r.id == role_id }
member.update_roles(new_roles)
end
@channels.each do |channel|
overwrites = channel.permission_overwrites.reject { |id, _| id == role_id }
channel.update_overwrites(overwrites)
end
end
# Adds a member to the member cache.
# @note For internal use only
# @!visibility private
def add_member(member)
@members[member.id] = member
@member_count += 1
end
# Removes a member from the member cache.
# @note For internal use only
# @!visibility private
def delete_member(user_id)
@members.delete(user_id)
@member_count -= 1
end
# Checks whether a member is cached
# @note For internal use only
# @!visibility private
def member_cached?(user_id)
@members.include?(user_id)
end
# Adds a member to the cache
# @note For internal use only
# @!visibility private
def cache_member(member)
@members[member.id] = member
end
# Updates a member's voice state
# @note For internal use only
# @!visibility private
def update_voice_state(data)
user_id = data['user_id'].to_i
if data['channel_id']
unless @voice_states[user_id]
# Create a new voice state for the user
@voice_states[user_id] = VoiceState.new(user_id)
end
# Update the existing voice state (or the one we just created)
channel = @channels_by_id[data['channel_id'].to_i]
@voice_states[user_id].update(
channel,
data['mute'],
data['deaf'],
data['self_mute'],
data['self_deaf']
)
else
# The user is not in a voice channel anymore, so delete its voice state
@voice_states.delete(user_id)
end
end
# Creates a channel on this server with the given name.
# @param name [String] Name of the channel to create
# @param type [Integer] Type of channel to create (0: text, 2: voice)
# @return [Channel] the created channel.
# @raise [ArgumentError] if type is not 0 or 2
def create_channel(name, type = 0)
raise ArgumentError, 'Channel type must be either 0 (text) or 2 (voice)!' unless [0, 2].include?(type)
response = API::Server.create_channel(@bot.token, @id, name, type)
Channel.new(JSON.parse(response), @bot)
end
# Creates a role on this server which can then be modified. It will be initialized (on Discord's side)
# with the regular role defaults the client uses, i. e. name is "new role", permissions are the default,
# colour is the default etc.
# @return [Role] the created role.
def create_role
response = API::Server.create_role(@bot.token, @id)
role = Role.new(JSON.parse(response), @bot, self)
@roles << role
role
end
# @return [Array<User>] a list of banned users on this server.
def bans
users = JSON.parse(API::Server.bans(@bot.token, @id))
users.map { |e| User.new(e['user'], @bot) }
end
# Bans a user from this server.
# @param user [User, #resolve_id] The user to ban.
# @param message_days [Integer] How many days worth of messages sent by the user should be deleted.
def ban(user, message_days = 0)
API::Server.ban_user(@bot.token, @id, user.resolve_id, message_days)
end
# Unbans a previously banned user from this server.
# @param user [User, #resolve_id] The user to unban.
def unban(user)
API::Server.unban_user(@bot.token, @id, user.resolve_id)
end
# Kicks a user from this server.
# @param user [User, #resolve_id] The user to kick.
def kick(user)
API::Server.remove_member(@bot.token, @id, user.resolve_id)
end
# Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed.
# @param user [User] The user to move.
# @param channel [Channel] The voice channel to move into.
def move(user, channel)
API::Server.update_member(@bot.token, @id, user.id, channel_id: channel.id)
end
# Deletes this server. Be aware that this is permanent and impossible to undo, so be careful!
def delete
API::Server.delete(@bot.token, @id)
end
# Leave the server
def leave
API::User.leave_server(@bot.token, @id)
end
# Transfers server ownership to another user.
# @param user [User] The user who should become the new owner.
def owner=(user)
API::Server.transfer_ownership(@bot.token, @id, user.id)
end
# Sets the server's name.
# @param name [String] The new server name.
def name=(name)
update_server_data(name: name)
end
# Moves the server to another region. This will cause a voice interruption of at most a second.
# @param region [String] The new region the server should be in.
def region=(region)
update_server_data(region: region.to_s)
end
# Sets the server's icon.
# @param icon [String, #read] The new icon, in base64-encoded JPG format.
def icon=(icon)
if icon.respond_to? :read
icon_string = 'data:image/jpg;base64,'
icon_string += Base64.strict_encode64(icon.read)
update_server_data(icon: icon_string)
else
update_server_data(icon: icon)
end
end
# Sets the server's AFK channel.
# @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set.
def afk_channel=(afk_channel)
update_server_data(afk_channel_id: afk_channel.resolve_id)
end
# Sets the amount of time after which a user gets moved into the AFK channel.
# @param afk_timeout [Integer] The AFK timeout, in seconds.
def afk_timeout=(afk_timeout)
update_server_data(afk_timeout: afk_timeout)
end
# @return [true, false] whether this server has any emoji or not.
def any_emoji?
@emoji.any?
end
alias_method :has_emoji?, :any_emoji?
alias_method :emoji?, :any_emoji?
# Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field
# @note For internal use only
# @!visibility private
def process_chunk(members)
process_members(members)
@processed_chunk_members += members.length
LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}")
# Don't bother with the rest of the method if it's not truly the last packet
return unless @processed_chunk_members == @member_count
LOGGER.debug("Finished chunking server #{@id}")
# Reset everything to normal
@chunked = true
@processed_chunk_members = 0
end
# Updates the cached data with new data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@region = new_data[:region] || new_data['region'] || @region
@icon_id = new_data[:icon] || new_data['icon'] || @icon_id
@afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout
@afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id
begin
@afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id.nonzero? && (!@afk_channel || @afk_channel_id != @afk_channel.id)
rescue Discordrb::Errors::NoPermission
LOGGER.debug("AFK channel #{@afk_channel_id} on server #{@id} is unreachable, setting to nil even though one exists")
@afk_channel = nil
end
end
# Adds a channel to this server's cache
# @note For internal use only
# @!visibility private
def add_channel(channel)
@channels << channel
@channels_by_id[channel.id] = channel
end
# Deletes a channel from this server's cache
# @note For internal use only
# @!visibility private
def delete_channel(id)
@channels.reject! { |e| e.id == id }
@channels_by_id.delete(id)
end
# Updates the cached emoji data with new data
# @note For internal use only
# @!visibility private
def update_emoji_data(new_data)
@emoji = {}
process_emoji(new_data['emojis'])
end
# The inspect method is overwritten to give more useful output
def inspect
"<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>"
end
private
def update_server_data(new_data)
API::Server.update(@bot.token, @id,
new_data[:name] || @name,
new_data[:region] || @region,
new_data[:icon_id] || @icon_id,
new_data[:afk_channel_id] || @afk_channel_id,
new_data[:afk_timeout] || @afk_timeout)
update_data(new_data)
end
def process_roles(roles)
# Create roles
@roles = []
@roles_by_id = {}
return unless roles
roles.each do |element|
role = Role.new(element, @bot, self)
@roles << role
@roles_by_id[role.id] = role
end
end
def process_emoji(emoji)
return if emoji.empty?
emoji.each do |element|
new_emoji = Emoji.new(element, @bot, self)
@emoji[new_emoji.id] = new_emoji
end
end
def process_members(members)
return unless members
members.each do |element|
member = Member.new(element, self, @bot)
@members[member.id] = member
end
end
def process_presences(presences)
# Update user statuses with presence info
return unless presences
presences.each do |element|
next unless element['user']
user_id = element['user']['id'].to_i
user = @members[user_id]
if user
user.update_presence(element)
else
LOGGER.warn "Rogue presence update! #{element['user']['id']} on #{@id}"
end
end
end
def process_channels(channels)
@channels = []
@channels_by_id = {}
return unless channels
channels.each do |element|
channel = @bot.ensure_channel(element, self)
@channels << channel
@channels_by_id[channel.id] = channel
end
end
def process_voice_states(voice_states)
return unless voice_states
voice_states.each do |element|
update_voice_state(element)
end
end
end
# A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias
# {ColorRGB} is also available.
class ColourRGB
# @return [Integer] the red part of this colour (0-255).
attr_reader :red
# @return [Integer] the green part of this colour (0-255).
attr_reader :green
# @return [Integer] the blue part of this colour (0-255).
attr_reader :blue
# @return [Integer] the colour's RGB values combined into one integer.
attr_reader :combined
# Make a new colour from the combined value.
# @param combined [Integer] The colour's RGB values combined into one integer
def initialize(combined)
@combined = combined
@red = (combined >> 16) & 0xFF
@green = (combined >> 8) & 0xFF
@blue = combined & 0xFF
end
end
# Alias for the class {ColourRGB}
ColorRGB = ColourRGB
end
|
# frozen_string_literal: true
# These classes hold relevant Discord data, such as messages or channels.
require 'ostruct'
require 'discordrb/permissions'
require 'discordrb/api'
require 'discordrb/events/message'
require 'time'
require 'base64'
# Discordrb module
module Discordrb
# The unix timestamp Discord IDs are based on
DISCORD_EPOCH = 1_420_070_400_000
# Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID.
def self.id_compare(one_id, other)
other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other)
end
# The maximum length a Discord message can have
CHARACTER_LIMIT = 2000
# Splits a message into chunks of 2000 characters. Attempts to split by lines if possible.
# @param msg [String] The message to split.
# @return [Array<String>] the message split into chunks
def self.split_message(msg)
# If the messages is empty, return an empty array
return [] if msg.empty?
# Split the message into lines
lines = msg.lines
# Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become
# [
# [1],
# [1, 2],
# [1, 2, 3],
# [1, 2, 3, 4]
# ]
tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first }
# Join the individual elements together to get an array of strings with consecutively more lines
joined = tri.map(&:join)
# Find the largest element that is still below the character limit, or if none such element exists return the first
ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length }
# If it's still larger than the character limit (none was smaller than it) split it into slices with the length
# being the character limit, otherwise just return an array with one element
ideal_ary = (ideal.length > CHARACTER_LIMIT) ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal]
# Slice off the ideal part and strip newlines
rest = msg[ideal.length..-1].strip
# If none remains, return an empty array -> we're done
return [] unless rest
# Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array
ideal_ary + split_message(rest)
end
# Mixin for objects that have IDs
module IDObject
# @return [Integer] the ID which uniquely identifies this object across Discord.
attr_reader :id
alias_method :resolve_id, :id
# ID based comparison
def ==(other)
Discordrb.id_compare(@id, other)
end
# Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but
# shouldn't be relied on as Discord might change its algorithm at any time
# @return [Time] when this object was created at
def creation_time
# Milliseconds
ms = (@id >> 22) + DISCORD_EPOCH
Time.at(ms / 1000.0)
end
end
# Mixin for the attributes users should have
module UserAttributes
# @return [String] this user's username
attr_reader :username
alias_method :name, :username
# @return [String] this user's discriminator which is used internally to identify users with identical usernames.
attr_reader :discriminator
alias_method :discrim, :discriminator
alias_method :tag, :discriminator
alias_method :discord_tag, :discriminator
# @return [true, false] whether this user is a Discord bot account
attr_reader :bot_account
alias_method :bot_account?, :bot_account
# @return [String] the ID of this user's current avatar, can be used to generate an avatar URL.
# @see #avatar_url
attr_reader :avatar_id
# Utility function to mention users in messages
# @return [String] the mention code in the form of <@id>
def mention
"<@#{@id}>"
end
# Utility function to get Discord's distinct representation of a user, i. e. username + discriminator
# @return [String] distinct representation of user
def distinct
"#{@username}##{@discriminator}"
end
# Utility function to get a user's avatar URL.
# @return [String] the URL to the avatar image.
def avatar_url
API.avatar_url(@id, @avatar_id)
end
end
# User on Discord, including internal data like discriminators
class User
include IDObject
include UserAttributes
# @!attribute [r] status
# @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`)
attr_accessor :status
# @!attribute [r] game
# @return [String, nil] the game the user is currently playing, or `nil` if none is being played.
attr_accessor :game
def initialize(data, bot)
@bot = bot
@username = data['username']
@id = data['id'].to_i
@discriminator = data['discriminator']
@avatar_id = data['avatar']
@roles = {}
@bot_account = false
@bot_account = true if data['bot']
@status = :offline
end
# Get a user's PM channel or send them a PM
# @overload pm
# Creates a private message channel for this user or returns an existing one if it already exists
# @return [Channel] the PM channel to this user.
# @overload pm(content)
# Sends a private to this user.
# @param content [String] The content to send.
# @return [Message] the message sent to this user.
def pm(content = nil)
if content
# Recursively call pm to get the channel, then send a message to it
channel = pm
channel.send_message(content)
else
# If no message was specified, return the PM channel
@bot.private_channel(@id)
end
end
# Set the user's name
# @note for internal use only
# @!visibility private
def update_username(username)
@username = username
end
# Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this
# user's ID as a :from attribute.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block)
end
# Gets the member this user is on a server
# @param server [Server] The server to get the member for
# @return [Member] this user as a member on a particular server
def on(server)
id = server.resolve_id
@bot.server(id).member(@id)
end
# Is the user the bot?
# @return [true, false] whether this user is the bot
def current_bot?
@bot.profile.id == @id
end
[:offline, :idle, :online].each do |e|
define_method(e.to_s + '?') do
@status.to_sym == e
end
end
# The inspect method is overwritten to give more useful output
def inspect
"<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>"
end
end
# Mixin for the attributes members and private members should have
module MemberAttributes
# @return [true, false] whether this member is muted server-wide.
attr_reader :mute
alias_method :muted?, :mute
# @return [true, false] whether this member is deafened server-wide.
attr_reader :deaf
alias_method :deafened?, :deaf
# @return [true, false] whether this member has muted themselves.
attr_reader :self_mute
alias_method :self_muted?, :self_mute
# @return [true, false] whether this member has deafened themselves.
attr_reader :self_deaf
alias_method :self_deafened?, :self_deaf
# @return [Time] when this member joined the server.
attr_reader :joined_at
# @return [String, nil] the nickname this member has, or nil if it has none.
attr_reader :nick
alias_method :nickname, :nick
# @return [Array<Role>] the roles this member has.
attr_reader :roles
# @return [Server] the server this member is on.
attr_reader :server
# @return [Channel] the voice channel the user is in.
attr_reader :voice_channel
end
# Mixin to calculate resulting permissions from overrides etc.
module PermissionCalculator
# Checks whether this user can do the particular action, regardless of whether it has the permission defined,
# through for example being the server owner or having the Manage Roles permission
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @return [true, false] whether or not this user has the permission.
def permission?(action, channel = nil)
# If the member is the server owner, it irrevocably has all permissions.
return true if owner?
# First, check whether the user has Manage Roles defined.
# (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a
# Manage Permissions deny overwrite will override Manage Roles, so we can just check for
# Manage Roles once and call it a day.)
return true if defined_permission?(:manage_roles, channel)
# Otherwise, defer to defined_permission
defined_permission?(action, channel)
end
# Checks whether this user has a particular permission defined (i. e. not implicit, through for example
# Manage Roles)
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @return [true, false] whether or not this user has the permission defined.
def defined_permission?(action, channel = nil)
# Get the permission the user's roles have
role_permission = defined_role_permission?(action, channel)
# Once we have checked the role permission, we have to check the channel overrides for the
# specific user
user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable
# Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role
return role_permission unless user_specific_override
user_specific_override == :allow
end
# Define methods for querying permissions
Discordrb::Permissions::Flags.each_value do |flag|
define_method "can_#{flag}?" do |channel = nil|
permission? flag, channel
end
end
private
def defined_role_permission?(action, channel)
# For each role, check if
# (1) the channel explicitly allows or permits an action for the role and
# (2) if the user is allowed to do the action if the channel doesn't specify
@roles.reduce(false) do |can_act, role|
# Get the override defined for the role on the channel
channel_allow = permission_overwrite(action, channel, role.id)
can_act = if channel_allow
# If the channel has an override, check whether it is an allow - if yes,
# the user can act, if not, it can't
channel_allow == :allow
else
# Otherwise defer to the role
role.permissions.instance_variable_get("@#{action}") || can_act
end
can_act
end
end
def permission_overwrite(action, channel, id)
# If no overwrites are defined, or no channel is set, no overwrite will be present
return nil unless channel && channel.permission_overwrites[id]
# Otherwise, check the allow and deny objects
allow = channel.permission_overwrites[id].allow
deny = channel.permission_overwrites[id].deny
if allow.instance_variable_get("@#{action}")
:allow
elsif deny.instance_variable_get("@#{action}")
:deny
end
# If there's no variable defined, nil will implicitly be returned
end
end
# A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like
# that.
class Member < DelegateClass(User)
include MemberAttributes
# @!visibility private
def initialize(data, server, bot)
@bot = bot
@user = bot.ensure_user(data['user'])
super @user # Initialize the delegate class
# Somehow, Discord doesn't send the server ID in the standard member format...
raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil?
@server = server || bot.server(data['guild_id'].to_i)
# Initialize the roles by getting the roles from the server one-by-one
update_roles(data['roles'])
@nick = data['nick']
@deaf = data['deaf']
@mute = data['mute']
@joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil
end
# @return [true, false] whether this member is the server owner.
def owner?
@server.owner == self
end
# @param role [Role, Integer, #resolve_id] the role to check or its ID.
# @return [true, false] whether this member has the specified role.
def role?(role)
role = role.resolve_id
@roles.any? { |e| e.id == role }
end
# Adds one or more roles to this member.
# @param role [Role, Array<Role>] The role(s) to add.
def add_role(role)
role_ids = role_id_array(role)
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids + role_ids).uniq
API.update_user_roles(@bot.token, @server.id, @user.id, new_role_ids)
end
# Removes one or more roles from this member.
# @param role [Role, Array<Role>] The role(s) to remove.
def remove_role(role)
old_role_ids = @roles.map(&:id)
role_ids = role_id_array(role)
new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) }
API.update_user_roles(@bot.token, @server.id, @user.id, new_role_ids)
end
# Server deafens this member.
def server_deafen
API.update_user_deafen(@bot.token, @server.id, @user.id, true)
end
# Server undeafens this member.
def server_undeafen
API.update_user_deafen(@bot.token, @server.id, @user.id, false)
end
# Server mutes this member.
def server_mute
API.update_user_mute(@bot.token, @server.id, @user.id, true)
end
# Server unmutes this member.
def server_unmute
API.update_user_mute(@bot.token, @server.id, @user.id, false)
end
# Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage
# Nicknames for other users.
# @param nick [String, nil] The string to set the nickname to, or nil if it should be reset.
def nick=(nick)
# Discord uses the empty string to signify 'no nickname' so we convert nil into that
nick ||= ''
API.change_nickname(@bot.token, @server.id, @user.id, nick)
end
alias_method :nickname=, :nick=
# @return [String] the name the user displays as (nickname if they have one, username otherwise)
def display_name
nickname || username
end
# Update this member's roles
# @note For internal use only.
# @!visibility private
def update_roles(roles)
@roles = roles.map do |role|
role.is_a?(Role) ? role : @server.role(role.to_i)
end
end
# Update this member's nick
# @note For internal use only.
# @!visibility private
def update_nick(nick)
@nick = nick
end
# Update this member's voice state
# @note For internal use only.
# @!visibility private
def update_voice_state(channel, mute, deaf, self_mute, self_deaf)
@voice_channel = channel
@mute = mute
@deaf = deaf
@self_mute = self_mute
@self_deaf = self_deaf
end
include PermissionCalculator
# Overwriting inspect for debug purposes
def inspect
"<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>"
end
private
# Utility method to get a list of role IDs from one role or an array of roles
def role_id_array(role)
if role.is_a? Array
role.map(&:resolve_id)
else
[role.resolve_id]
end
end
end
# Recipients are members on private channels - they exist for completeness purposes, but all
# the attributes will be empty.
class Recipient < DelegateClass(User)
include MemberAttributes
# @return [Channel] the private channel this recipient is the recipient of.
attr_reader :channel
# @!visibility private
def initialize(user, channel, bot)
@bot = bot
@channel = channel
raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private?
@user = user
super @user
# Member attributes
@mute = @deaf = @self_mute = @self_deaf = false
@voice_channel = nil
@server = nil
@roles = []
@joined_at = @channel.creation_time
end
# Overwriting inspect for debug purposes
def inspect
"<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>"
end
end
# This class is a special variant of User that represents the bot's user profile (things like email addresses and the avatar).
# It can be accessed using {Bot#profile}.
class Profile < User
def initialize(data, bot, email, password)
super(data, bot)
@email = email
@password = password
end
# Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true.
# @return [true]
def current_bot?
true
end
# Sets the bot's username.
# @param username [String] The new username.
def username=(username)
update_profile_data(username: username)
end
# Sets the bot's email address. If you use this method, make sure that the login email in the script matches this
# one afterwards, so the bot doesn't have any trouble logging in in the future.
# @param email [String] The new email address.
def email=(email)
update_profile_data(email: email)
end
# Changes the bot's password. This will invalidate all tokens so you will have to relog the bot.
# @param password [String] The new password.
def password=(password)
update_profile_data(new_password: password)
end
# Changes the bot's avatar.
# @param avatar [String, #read] A JPG file to be used as the avatar, either
# something readable (e. g. File) or as a data URL.
def avatar=(avatar)
if avatar.respond_to? :read
# Set the file to binary mode if supported, so we don't get problems with Windows
avatar.binmode if avatar.respond_to?(:binmode)
avatar_string = 'data:image/jpg;base64,'
avatar_string += Base64.strict_encode64(avatar.read)
update_profile_data(avatar: avatar_string)
else
update_profile_data(avatar: avatar)
end
end
# Updates the cached profile data with the new one.
# @note For internal use only.
# @!visibility private
def update_data(new_data)
@email = new_data[:email] || @email
@password = new_data[:new_password] || @password
@username = new_data[:username] || @username
@avatar_id = new_data[:avatar_id] || @avatar_id
end
# The inspect method is overwritten to give more useful output
def inspect
"<Profile email=#{@email} user=#{super}>"
end
private
def update_profile_data(new_data)
API.update_user(@bot.token,
new_data[:email] || @email,
@password,
new_data[:username] || @username,
new_data[:avatar],
new_data[:new_password] || nil)
update_data(new_data)
end
end
# A Discord role that contains permissions and applies to certain users
class Role
include IDObject
# @return [Permissions] this role's permissions.
attr_reader :permissions
# @return [String] this role's name ("new role" if it hasn't been changed)
attr_reader :name
# @return [true, false] whether or not this role should be displayed separately from other users
attr_reader :hoist
# @return [true, false] whether this role can be mentioned using a role mention
attr_reader :mentionable
alias_method :mentionable?, :mentionable
# @return [ColourRGB] the role colour
attr_reader :colour
alias_method :color, :colour
# This class is used internally as a wrapper to a Role object that allows easy writing of permission data.
class RoleWriter
# @!visibility private
def initialize(role, token)
@role = role
@token = token
end
# Write the specified permission data to the role, without updating the permission cache
# @param bits [Integer] The packed permissions to write.
def write(bits)
@role.send(:packed=, bits, false)
end
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
@server = server
@permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token))
@name = data['name']
@id = data['id'].to_i
@hoist = data['hoist']
@mentionable = data['mentionable']
@colour = ColourRGB.new(data['color'])
end
# @return [String] a string that will mention this role, if it is mentionable.
def mention
"<@&#{@id}>"
end
# @return [Array<Member>] an array of members who have this role.
# @note This requests a member chunk if it hasn't for the server before, which may be slow initially
def members
@server.members.select { |m| m.role? role }
end
alias_method :users, :members
# Updates the data cache from another Role object
# @note For internal use only
# @!visibility private
def update_from(other)
@permissions = other.permissions
@name = other.name
@hoist = other.hoist
@colour = other.colour
end
# Updates the data cache from a hash containing data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@hoist = new_data['hoist'] unless new_data['hoist'].nil?
@hoist = new_data[:hoist] unless new_data[:hoist].nil?
@colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour)
end
# Sets the role name to something new
# @param name [String] The name that should be set
def name=(name)
update_role_data(name: name)
end
# Changes whether or not this role is displayed at the top of the user list
# @param hoist [true, false] The value it should be changed to
def hoist=(hoist)
update_role_data(hoist: hoist)
end
# Sets the role colour to something new
# @param colour [ColourRGB] The new colour
def colour=(colour)
update_role_data(colour: colour)
end
alias_method :color=, :colour=
# Changes the internal packed permissions
# @note For internal use only
# @!visibility private
def packed=(packed, update_perms = true)
update_role_data(permissions: packed)
@permissions.bits = packed if update_perms
end
# Delets this role. This cannot be undone without recreating the role!
def delete
API.delete_role(@bot.token, @server.id, @id)
@server.delete_role(@id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>"
end
private
def update_role_data(new_data)
API.update_role(@bot.token, @server.id, @id,
new_data[:name] || @name,
(new_data[:colour] || @colour).combined,
new_data[:hoist].nil? ? false : !@hoist.nil?,
new_data[:permissions] || @permissions.bits)
update_data(new_data)
end
end
# A channel referenced by an invite. It has less data than regular channels, so it's a separate class
class InviteChannel
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [String] this channel's type (text or voice)
attr_reader :type
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@type = data['type']
end
end
# A server referenced to by an invite
class InviteServer
include IDObject
# @return [String] this server's name.
attr_reader :name
# @return [String, nil] the hash of the server's invite splash screen (for partnered servers) or nil if none is
# present
attr_reader :splash_hash
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@splash_hash = data['splash_hash']
end
end
# A Discord invite to a channel
class Invite
# @return [InviteChannel] the channel this invite references.
attr_reader :channel
# @return [InviteServer] the server this invite references.
attr_reader :server
# @return [Integer] the amount of uses left on this invite.
attr_reader :uses
# @return [User, nil] the user that made this invite. May also be nil if the user can't be determined.
attr_reader :inviter
# @return [true, false] whether or not this invite is temporary.
attr_reader :temporary
# @return [true, false] whether this invite is still valid.
attr_reader :revoked
# @return [true, false] whether this invite is in xkcd format (i. e. "Human readable" in the invite settings)
attr_reader :xkcd
# @return [String] this invite's code
attr_reader :code
alias_method :max_uses, :uses
alias_method :user, :inviter
alias_method :temporary?, :temporary
alias_method :revoked?, :revoked
alias_method :xkcd?, :xkcd
# @!visibility private
def initialize(data, bot)
@bot = bot
@channel = InviteChannel.new(data['channel'], bot)
@server = InviteServer.new(data['guild'], bot)
@uses = data['uses']
@inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil
@temporary = data['temporary']
@revoked = data['revoked']
@xkcd = data['xkcdpass']
@code = data['code']
end
# Code based comparison
def ==(other)
other.respond_to?(:code) ? (@code == other.code) : (@code == other)
end
# Deletes this invite
def delete
API.delete_invite(@bot.token, @code)
end
alias_method :revoke, :delete
# The inspect method is overwritten to give more useful output
def inspect
"<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked} xkcd=#{@xkcd}>"
end
# Creates an invite URL.
def url
"https://discord.gg/#{@code}"
end
end
# A Discord channel, including data like the topic
class Channel
# The type string that stands for a text channel
# @see Channel#type
TEXT_TYPE = 'text'.freeze
# The type string that stands for a voice channel
# @see Channel#type
VOICE_TYPE = 'voice'.freeze
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil.
attr_reader :server
# @return [String] the type of this channel (currently either 'text' or 'voice')
attr_reader :type
# @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel
attr_reader :recipient
# @return [String] the channel's topic
attr_reader :topic
# @return [Integer] the channel's position on the channel list
attr_reader :position
# This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the
# `allow` and `deny` properties which are {Permissions} objects respectively.
# @return [Hash<Integer => OpenStruct>] the channel's permission overwrites
attr_reader :permission_overwrites
# @return [true, false] whether or not this channel is a PM channel.
def private?
@server.nil?
end
# @return [String] a string that will mention the channel as a clickable link on Discord.
def mention
"<##{@id}>"
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
# data is a sometimes a Hash and othertimes an array of Hashes, you only want the last one if it's an array
data = data[-1] if data.is_a?(Array)
@id = data['id'].to_i
@type = data['type'] || TEXT_TYPE
@topic = data['topic']
@position = data['position']
@is_private = data['is_private']
if @is_private
recipient_user = bot.ensure_user(data['recipient'])
@recipient = Recipient.new(recipient_user, self, bot)
@name = @recipient.username
else
@name = data['name']
@server = if server
server
else
bot.server(data['guild_id'].to_i)
end
end
# Populate permission overwrites
@permission_overwrites = {}
return unless data['permission_overwrites']
data['permission_overwrites'].each do |element|
role_id = element['id'].to_i
deny = Permissions.new(element['deny'])
allow = Permissions.new(element['allow'])
@permission_overwrites[role_id] = OpenStruct.new
@permission_overwrites[role_id].deny = deny
@permission_overwrites[role_id].allow = allow
end
end
# @return [true, false] whether or not this channel is a text channel
def text?
@type == TEXT_TYPE
end
# @return [true, false] whether or not this channel is a voice channel
def voice?
@type == VOICE_TYPE
end
# Sends a message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
# @return [Message] the message that was sent.
def send_message(content, tts = false)
@bot.send_message(@id, content, tts, @server && @server.id)
end
# Sends a temporary message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param timeout [Float] The amount of time in seconds after which the message sent will be deleted.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
def send_temporary_message(content, timeout, tts = false)
@bot.send_temporary_message(@id, content, timeout, tts, @server && @server.id)
end
# Sends multiple messages to a channel
# @param content [Array<String>] The messages to send.
def send_multiple(content)
content.each { |e| send_message(e) }
end
# Splits a message into chunks whose length is at most the Discord character limit, then sends them individually.
# Useful for sending long messages, but be wary of rate limits!
def split_send(content)
send_multiple(Discordrb.split_message(content))
end
# Sends a file to this channel. If it is an image, it will be embedded.
# @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed)
def send_file(file)
@bot.send_file(@id, file)
end
# Permanently deletes this channel
def delete
API.delete_channel(@bot.token, @id)
end
# Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations)
# @param name [String] The new name.
def name=(name)
@name = name
update_channel_data
end
# Sets this channel's topic.
# @param topic [String] The new topic.
def topic=(topic)
@topic = topic
update_channel_data
end
# Sets this channel's position in the list.
# @param position [Integer] The new position.
def position=(position)
@position = position
update_channel_data
end
# Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny
# permission sets, or change an existing one.
# @param thing [User, Role] What to define an overwrite for.
# @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a
# green checkmark on Discord)
# @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red
# cross on Discord)
# @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites
# allow = Discordrb::Permissions.new
# allow.can_mention_everyone = true
# allow.can_send_tts_messages = true
#
# deny = Discordrb::Permissions.new
# deny.can_create_instant_invite = true
#
# channel.define_overwrite(user, allow, deny)
def define_overwrite(thing, allow, deny)
allow_bits = allow.respond_to?(:bits) ? allow.bits : allow
deny_bits = deny.respond_to?(:bits) ? deny.bits : deny
# TODO: Be more flexible about what classes are allowed here
if thing.is_a?(User) || thing.is_a?(Member) || thing.is_a?(Recipient)
API.update_user_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits)
elsif thing.is_a? Role
API.update_role_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits)
end
end
# Updates the cached data from another channel.
# @note For internal use only
# @!visibility private
def update_from(other)
@topic = other.topic
@name = other.name
@recipient = other.recipient
@permission_overwrites = other.permission_overwrites
end
# The list of users currently in this channel. This is mostly useful for a voice channel, for a text channel it will
# just return the users on the server that are online.
# @return [Array<Member>] the users in this channel
def users
if @type == 'text'
@server.online_members(include_idle: true).select { |u| u.status != :offline }
else
@server.online_members(include_idle: true).select do |user|
user.voice_channel.id == @id if user.voice_channel
end
end
end
# Retrieves some of this channel's message history.
# @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher
# than 100 it will be treated as 100 on Discord's side.
# @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should
# start at the current message.
# @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start
# as soon as possible with the specified amount.
# @return [Array<Message>] the retrieved messages.
def history(amount, before_id = nil, after_id = nil)
logs = API.channel_log(@bot.token, @id, amount, before_id, after_id)
JSON.parse(logs).map { |message| Message.new(message, @bot) }
end
# Requests all pinned messages of a channel.
# @return [Array<Message>] the received messages.
def pins
msgs = API.pins(@bot.token, @id)
JSON.parse(msgs).map { |msg| Message.new(msg, @bot) }
end
# Delete the last N messages on this channel.
# @param amount [Integer] How many messages to delete. Must be a value between 2 and 100 (Discord limitation)
# @raise [ArgumentError] if the amount of messages is not a value between 2 and 100
def prune(amount)
raise ArgumentError, 'Can only prune between 2 and 100 messages!' unless amount.between?(2, 100)
messages = history(amount).map(&:id)
API.bulk_delete(@bot.token, @id, messages)
end
# Updates the cached permission overwrites
# @note For internal use only
# @!visibility private
def update_overwrites(overwrites)
@permission_overwrites = overwrites
end
# Add an {Await} for a message in this channel. This is identical in functionality to adding a
# {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block)
end
# Creates a new invite to this channel.
# @param max_age [Integer] How many seconds this invite should last.
# @param max_uses [Integer] How many times this invite should be able to be used.
# @param temporary [true, false] Whether membership should be temporary (kicked after going offline).
# @param xkcd [true, false] Whether or not the invite should be human-readable.
# @return [Invite] the created invite.
def make_invite(max_age = 0, max_uses = 0, temporary = false, xkcd = false)
response = API.create_invite(@bot.token, @id, max_age, max_uses, temporary, xkcd)
Invite.new(JSON.parse(response), @bot)
end
# Starts typing, which displays the typing indicator on the client for five seconds.
# If you want to keep typing you'll have to resend this every five seconds. (An abstraction
# for this will eventually be coming)
def start_typing
API.start_typing(@bot.token, @id)
end
alias_method :send, :send_message
alias_method :message, :send_message
alias_method :invite, :make_invite
# The inspect method is overwritten to give more useful output
def inspect
"<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>"
end
private
def update_channel_data
API.update_channel(@bot.token, @id, @name, @topic, @position)
end
end
# An attachment to a message
class Attachment
include IDObject
# @return [Message] the message this attachment belongs to.
attr_reader :message
# @return [String] the CDN URL this attachment can be downloaded at.
attr_reader :url
# @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to
# do with CDNs
attr_reader :proxy_url
# @return [String] the attachment's filename.
attr_reader :filename
# @return [Integer] the attachment's file size in bytes.
attr_reader :size
# @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image.
attr_reader :width
# @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image.
attr_reader :height
# @!visibility private
def initialize(data, message, bot)
@bot = bot
@message = message
@url = data['url']
@proxy_url = data['proxy_url']
@filename = data['filename']
@size = data['size']
@width = data['width']
@height = data['height']
end
# @return [true, false] whether this file is an image file.
def image?
!(@width.nil? || @height.nil?)
end
end
# A message on Discord that was sent to a text channel
class Message
include IDObject
# @return [String] the content of this message.
attr_reader :content
# @return [Member] the user that sent this message.
attr_reader :author
# @return [Channel] the channel in which this message was sent.
attr_reader :channel
# @return [Time] the timestamp at which this message was sent.
attr_reader :timestamp
# @return [Array<User>] the users that were mentioned in this message.
attr_reader :mentions
# @return [Array<Role>] the roles that were mentioned in this message.
attr_reader :role_mentions
# @return [Array<Attachment>] the files attached to this message.
attr_reader :attachments
# @return [true, false] whether themesage is pinned or not.
attr_reader :pinned
alias_method :pinned?, :pinned
alias_method :user, :author
alias_method :text, :content
alias_method :to_s, :content
# @!visibility private
def initialize(data, bot)
@bot = bot
@content = data['content']
@channel = bot.channel(data['channel_id'].to_i)
@pinned = data['pinned']
@author = if data['author']
if @channel.private?
# Turn the message user into a recipient - we can't use the channel recipient
# directly because the bot may also send messages to the channel
Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot)
else
member = @channel.server.member(data['author']['id'].to_i, false)
Discordrb::LOGGER.warn("Member with ID #{data['author']['id']} not cached even though it should be.") unless member
member
end
end
@timestamp = Time.parse(data['timestamp']) if data['timestamp']
@id = data['id'].to_i
@mentions = []
data['mentions'].each do |element|
@mentions << bot.ensure_user(element)
end if data['mentions']
@role_mentions = []
# Role mentions can only happen on public servers so make sure we only parse them there
unless @channel.private?
data['mention_roles'].each do |element|
@role_mentions << @channel.server.role(element.to_i)
end if data['mention_roles']
end
@attachments = []
@attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } if data['attachments']
end
# Replies to this message with the specified content.
# @see Channel#send_message
def reply(content)
@channel.send_message(content)
end
# Edits this message to have the specified content instead.
# @param new_content [String] the new content the message should have.
# @return [Message] the resulting message.
def edit(new_content)
response = API.edit_message(@bot.token, @channel.id, @id, new_content)
Message.new(JSON.parse(response), @bot)
end
# Deletes this message.
def delete
API.delete_message(@bot.token, @channel.id, @id)
nil
end
# Pins this message
def pin
API.pin_message(@bot.token, @channel.id, @id)
@pinned = true
nil
end
# Unpins this message
def unpin
API.unpin_message(@bot.token, @channel.id, @id)
@pinned = false
nil
end
# Add an {Await} for a message with the same user and channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block)
end
# @return [true, false] whether this message was sent by the current {Bot}.
def from_bot?
@author && @author.current_bot?
end
# The inspect method is overwritten to give more useful output
def inspect
"<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>"
end
end
# Basic attributes a server should have
module ServerAttributes
# @return [String] this server's name.
attr_reader :name
# @return [String] the hexadecimal ID used to identify this server's icon.
attr_reader :icon_id
# Utility function to get the URL for the icon image
# @return [String] the URL to the icon image
def icon_url
API.icon_url(@id, @icon_id)
end
end
# A server on Discord
class Server
include IDObject
include ServerAttributes
# @return [String] the region the server is on (e. g. `amsterdam`).
attr_reader :region
# @return [Member] The server owner.
attr_reader :owner
# @return [Array<Channel>] an array of all the channels (text and voice) on this server.
attr_reader :channels
# @return [Array<Role>] an array of all the roles created on this server.
attr_reader :roles
# @return [true, false] whether or not this server is large (members > 100). If it is,
# it means the members list may be inaccurate for a couple seconds after starting up the bot.
attr_reader :large
alias_method :large?, :large
# @return [Integer] the absolute number of members on this server, offline or not.
attr_reader :member_count
# @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds.
attr_reader :afk_timeout
# @return [Channel, nil] the AFK voice channel of this server, or nil if none is set
attr_reader :afk_channel
# @!visibility private
def initialize(data, bot, exists = true)
@bot = bot
@owner_id = data['owner_id'].to_i
@id = data['id'].to_i
update_data(data)
@large = data['large']
@member_count = data['member_count']
@members = {}
process_roles(data['roles'])
process_members(data['members'])
process_presences(data['presences'])
process_channels(data['channels'])
process_voice_states(data['voice_states'])
# Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet
@chunked = false
@processed_chunk_members = 0
# Only get the owner of the server actually exists (i. e. not for ServerDeleteEvent)
@owner = member(@owner_id) if exists
end
# @return [Channel] The default channel on this server (usually called #general)
def default_channel
@bot.channel(@id)
end
alias_method :general_channel, :default_channel
# Gets a role on this server based on its ID.
# @param id [Integer] The role ID to look for.
def role(id)
@roles.find { |e| e.id == id }
end
# Gets a member on this server based on user ID
# @param id [Integer] The user ID to look for
# @param request [true, false] Whether the member should be requested from Discord if it's not cached
def member(id, request = true)
id = id.resolve_id
return @members[id] if member_cached?(id)
return nil unless request
member = @bot.member(@id, id)
@members[id] = member
rescue
nil
end
# @return [Array<Member>] an array of all the members on this server.
def members
return @members.values if @chunked
@bot.debug("Members for server #{@id} not chunked yet - initiating")
@bot.request_chunks(@id)
sleep 0.05 until @chunked
@members.values
end
alias_method :users, :members
# @param include_idle [true, false] Whether to count idle members as online.
# @param include_bots [true, false] Whether to include bot accounts in the count.
# @return [Array<Member>] an array of online members on this server.
def online_members(include_idle: false, include_bots: true)
@members.values.select do |e|
((include_idle ? e.idle? : false) || e.online?) && (include_bots ? true : !e.bot_account?)
end
end
alias_method :online_users, :online_members
# @return [Array<Channel>] an array of text channels on this server
def text_channels
@channels.select(&:text?)
end
# @return [Array<Channel>] an array of voice channels on this server
def voice_channels
@channels.select(&:voice?)
end
# Adds a role to the role cache
# @note For internal use only
# @!visibility private
def add_role(role)
@roles << role
end
# Removes a role from the role cache
# @note For internal use only
# @!visibility private
def delete_role(role_id)
@roles.reject! { |r| r.id == role_id }
@members.each do |_, member|
new_roles = member.roles.reject { |r| r.id == role_id }
member.update_roles(new_roles)
end
@channels.each do |channel|
overwrites = channel.permission_overwrites.reject { |id, _| id == role_id }
channel.update_overwrites(overwrites)
end
end
# Adds a member to the member cache.
# @note For internal use only
# @!visibility private
def add_member(member)
@members[member.id] = member
@member_count += 1
end
# Removes a member from the member cache.
# @note For internal use only
# @!visibility private
def delete_member(user_id)
@members.delete(user_id)
@member_count -= 1
end
# Checks whether a member is cached
# @note For internal use only
# @!visibility private
def member_cached?(user_id)
@members.include?(user_id)
end
# Adds a member to the cache
# @note For internal use only
# @!visibility private
def cache_member(member)
@members[member.id] = member
end
# Creates a channel on this server with the given name.
# @return [Channel] the created channel.
def create_channel(name, type = 'text')
response = API.create_channel(@bot.token, @id, name, type)
Channel.new(JSON.parse(response), @bot)
end
# Creates a role on this server which can then be modified. It will be initialized (on Discord's side)
# with the regular role defaults the client uses, i. e. name is "new role", permissions are the default,
# colour is the default etc.
# @return [Role] the created role.
def create_role
response = API.create_role(@bot.token, @id)
role = Role.new(JSON.parse(response), @bot, self)
@roles << role
role
end
# @return [Array<User>] a list of banned users on this server.
def bans
users = JSON.parse(API.bans(@bot.token, @id))
users.map { |e| User.new(e['user'], @bot) }
end
# Bans a user from this server.
# @param user [User, #resolve_id] The user to ban.
# @param message_days [Integer] How many days worth of messages sent by the user should be deleted.
def ban(user, message_days = 0)
API.ban_user(@bot.token, @id, user.resolve_id, message_days)
end
# Unbans a previously banned user from this server.
# @param user [User, #resolve_id] The user to unban.
def unban(user)
API.unban_user(@bot.token, @id, user.resolve_id)
end
# Kicks a user from this server.
# @param user [User, #resolve_id] The user to kick.
def kick(user)
API.kick_user(@bot.token, @id, user.resolve_id)
end
# Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed.
# @param user [User] The user to move.
# @param channel [Channel] The voice channel to move into.
def move(user, channel)
API.move_user(@bot.token, @id, user.id, channel.id)
end
# Deletes this server. Be aware that this is permanent and impossible to undo, so be careful!
def delete
API.delete_server(@bot.token, @id)
end
# Leave the server
def leave
API.leave_server(@bot.token, @id)
end
# Transfers server ownership to another user.
# @param user [User] The user who should become the new owner.
def owner=(user)
API.transfer_ownership(@bot.token, @id, user.id)
end
# Sets the server's name.
# @param name [String] The new server name.
def name=(name)
update_server_data(name: name)
end
# Moves the server to another region. This will cause a voice interruption of at most a second.
# @param region [String] The new region the server should be in.
def region=(region)
update_server_data(region: region.to_s)
end
# Sets the server's icon.
# @param icon [String, #read] The new icon, in base64-encoded JPG format.
def icon=(icon)
if icon.respond_to? :read
icon_string = 'data:image/jpg;base64,'
icon_string += Base64.strict_encode64(icon.read)
update_server_data(icon: icon_string)
else
update_server_data(icon: icon)
end
end
# Sets the server's AFK channel.
# @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set.
def afk_channel=(afk_channel)
update_server_data(afk_channel_id: afk_channel.resolve_id)
end
# Sets the amount of time after which a user gets moved into the AFK channel.
# @param afk_timeout [Integer] The AFK timeout, in seconds.
def afk_timeout=(afk_timeout)
update_server_data(afk_timeout: afk_timeout)
end
# Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field
# @note For internal use only
# @!visibility private
def process_chunk(members)
process_members(members)
@processed_chunk_members += members.length
LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}")
# Don't bother with the rest of the method if it's not truly the last packet
return unless @processed_chunk_members == @member_count
LOGGER.debug("Finished chunking server #{@id}")
# Reset everything to normal
@chunked = true
@processed_chunk_members = 0
end
# Updates the cached data with new data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@region = new_data[:region] || new_data['region'] || @region
@icon_id = new_data[:icon] || new_data['icon'] || @icon_id
@afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout
@afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id
@afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id != 0 && (!@afk_channel || @afk_channel_id != @afk_channel.id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>"
end
private
def update_server_data(new_data)
API.update_server(@bot.token, @id,
new_data[:name] || @name,
new_data[:region] || @region,
new_data[:icon_id] || @icon_id,
new_data[:afk_channel_id] || @afk_channel_id,
new_data[:afk_timeout] || @afk_timeout)
update_data(new_data)
end
def process_roles(roles)
# Create roles
@roles = []
@roles_by_id = {}
return unless roles
roles.each do |element|
role = Role.new(element, @bot, self)
@roles << role
@roles_by_id[role.id] = role
end
end
def process_members(members)
return unless members
members.each do |element|
member = Member.new(element, self, @bot)
if @members[member.id] && @members[member.id].voice_channel
@bot.debug("Preserving voice state of member #{member.id} while chunking")
old_member = @members[member.id]
member.update_voice_state(
old_member.voice_channel,
old_member.mute,
old_member.deaf,
old_member.self_mute,
old_member.self_deaf
)
end
@members[member.id] = member
end
end
def process_presences(presences)
# Update user statuses with presence info
return unless presences
presences.each do |element|
next unless element['user']
user_id = element['user']['id'].to_i
user = @members[user_id]
if user
user.status = element['status'].to_sym
user.game = element['game'] ? element['game']['name'] : nil
end
end
end
def process_channels(channels)
@channels = []
@channels_by_id = {}
return unless channels
channels.each do |element|
channel = @bot.ensure_channel(element, self)
@channels << channel
@channels_by_id[channel.id] = channel
end
end
def process_voice_states(voice_states)
return unless voice_states
voice_states.each do |element|
user_id = element['user_id'].to_i
member = @members[user_id]
next unless member
channel_id = element['channel_id'].to_i
channel = channel_id ? @channels_by_id[channel_id] : nil
member.update_voice_state(
channel,
element['mute'],
element['deaf'],
element['self_mute'],
element['self_deaf'])
end
end
end
# A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias
# {ColorRGB} is also available.
class ColourRGB
# @return [Integer] the red part of this colour (0-255).
attr_reader :red
# @return [Integer] the green part of this colour (0-255).
attr_reader :green
# @return [Integer] the blue part of this colour (0-255).
attr_reader :blue
# @return [Integer] the colour's RGB values combined into one integer.
attr_reader :combined
# Make a new colour from the combined value.
# @param combined [Integer] The colour's RGB values combined into one integer
def initialize(combined)
@combined = combined
@red = (combined >> 16) & 0xFF
@green = (combined >> 8) & 0xFF
@blue = combined & 0xFF
end
end
# Alias for the class {ColourRGB}
ColorRGB = ColourRGB
end
Use change_own_nickname when changing the current_bot's nickname, fixes #158
# frozen_string_literal: true
# These classes hold relevant Discord data, such as messages or channels.
require 'ostruct'
require 'discordrb/permissions'
require 'discordrb/api'
require 'discordrb/events/message'
require 'time'
require 'base64'
# Discordrb module
module Discordrb
# The unix timestamp Discord IDs are based on
DISCORD_EPOCH = 1_420_070_400_000
# Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID.
def self.id_compare(one_id, other)
other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other)
end
# The maximum length a Discord message can have
CHARACTER_LIMIT = 2000
# Splits a message into chunks of 2000 characters. Attempts to split by lines if possible.
# @param msg [String] The message to split.
# @return [Array<String>] the message split into chunks
def self.split_message(msg)
# If the messages is empty, return an empty array
return [] if msg.empty?
# Split the message into lines
lines = msg.lines
# Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become
# [
# [1],
# [1, 2],
# [1, 2, 3],
# [1, 2, 3, 4]
# ]
tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first }
# Join the individual elements together to get an array of strings with consecutively more lines
joined = tri.map(&:join)
# Find the largest element that is still below the character limit, or if none such element exists return the first
ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length }
# If it's still larger than the character limit (none was smaller than it) split it into slices with the length
# being the character limit, otherwise just return an array with one element
ideal_ary = (ideal.length > CHARACTER_LIMIT) ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal]
# Slice off the ideal part and strip newlines
rest = msg[ideal.length..-1].strip
# If none remains, return an empty array -> we're done
return [] unless rest
# Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array
ideal_ary + split_message(rest)
end
# Mixin for objects that have IDs
module IDObject
# @return [Integer] the ID which uniquely identifies this object across Discord.
attr_reader :id
alias_method :resolve_id, :id
# ID based comparison
def ==(other)
Discordrb.id_compare(@id, other)
end
# Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but
# shouldn't be relied on as Discord might change its algorithm at any time
# @return [Time] when this object was created at
def creation_time
# Milliseconds
ms = (@id >> 22) + DISCORD_EPOCH
Time.at(ms / 1000.0)
end
end
# Mixin for the attributes users should have
module UserAttributes
# @return [String] this user's username
attr_reader :username
alias_method :name, :username
# @return [String] this user's discriminator which is used internally to identify users with identical usernames.
attr_reader :discriminator
alias_method :discrim, :discriminator
alias_method :tag, :discriminator
alias_method :discord_tag, :discriminator
# @return [true, false] whether this user is a Discord bot account
attr_reader :bot_account
alias_method :bot_account?, :bot_account
# @return [String] the ID of this user's current avatar, can be used to generate an avatar URL.
# @see #avatar_url
attr_reader :avatar_id
# Utility function to mention users in messages
# @return [String] the mention code in the form of <@id>
def mention
"<@#{@id}>"
end
# Utility function to get Discord's distinct representation of a user, i. e. username + discriminator
# @return [String] distinct representation of user
def distinct
"#{@username}##{@discriminator}"
end
# Utility function to get a user's avatar URL.
# @return [String] the URL to the avatar image.
def avatar_url
API.avatar_url(@id, @avatar_id)
end
end
# User on Discord, including internal data like discriminators
class User
include IDObject
include UserAttributes
# @!attribute [r] status
# @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`)
attr_accessor :status
# @!attribute [r] game
# @return [String, nil] the game the user is currently playing, or `nil` if none is being played.
attr_accessor :game
def initialize(data, bot)
@bot = bot
@username = data['username']
@id = data['id'].to_i
@discriminator = data['discriminator']
@avatar_id = data['avatar']
@roles = {}
@bot_account = false
@bot_account = true if data['bot']
@status = :offline
end
# Get a user's PM channel or send them a PM
# @overload pm
# Creates a private message channel for this user or returns an existing one if it already exists
# @return [Channel] the PM channel to this user.
# @overload pm(content)
# Sends a private to this user.
# @param content [String] The content to send.
# @return [Message] the message sent to this user.
def pm(content = nil)
if content
# Recursively call pm to get the channel, then send a message to it
channel = pm
channel.send_message(content)
else
# If no message was specified, return the PM channel
@bot.private_channel(@id)
end
end
# Set the user's name
# @note for internal use only
# @!visibility private
def update_username(username)
@username = username
end
# Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this
# user's ID as a :from attribute.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block)
end
# Gets the member this user is on a server
# @param server [Server] The server to get the member for
# @return [Member] this user as a member on a particular server
def on(server)
id = server.resolve_id
@bot.server(id).member(@id)
end
# Is the user the bot?
# @return [true, false] whether this user is the bot
def current_bot?
@bot.profile.id == @id
end
[:offline, :idle, :online].each do |e|
define_method(e.to_s + '?') do
@status.to_sym == e
end
end
# The inspect method is overwritten to give more useful output
def inspect
"<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>"
end
end
# Mixin for the attributes members and private members should have
module MemberAttributes
# @return [true, false] whether this member is muted server-wide.
attr_reader :mute
alias_method :muted?, :mute
# @return [true, false] whether this member is deafened server-wide.
attr_reader :deaf
alias_method :deafened?, :deaf
# @return [true, false] whether this member has muted themselves.
attr_reader :self_mute
alias_method :self_muted?, :self_mute
# @return [true, false] whether this member has deafened themselves.
attr_reader :self_deaf
alias_method :self_deafened?, :self_deaf
# @return [Time] when this member joined the server.
attr_reader :joined_at
# @return [String, nil] the nickname this member has, or nil if it has none.
attr_reader :nick
alias_method :nickname, :nick
# @return [Array<Role>] the roles this member has.
attr_reader :roles
# @return [Server] the server this member is on.
attr_reader :server
# @return [Channel] the voice channel the user is in.
attr_reader :voice_channel
end
# Mixin to calculate resulting permissions from overrides etc.
module PermissionCalculator
# Checks whether this user can do the particular action, regardless of whether it has the permission defined,
# through for example being the server owner or having the Manage Roles permission
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @return [true, false] whether or not this user has the permission.
def permission?(action, channel = nil)
# If the member is the server owner, it irrevocably has all permissions.
return true if owner?
# First, check whether the user has Manage Roles defined.
# (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a
# Manage Permissions deny overwrite will override Manage Roles, so we can just check for
# Manage Roles once and call it a day.)
return true if defined_permission?(:manage_roles, channel)
# Otherwise, defer to defined_permission
defined_permission?(action, channel)
end
# Checks whether this user has a particular permission defined (i. e. not implicit, through for example
# Manage Roles)
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @return [true, false] whether or not this user has the permission defined.
def defined_permission?(action, channel = nil)
# Get the permission the user's roles have
role_permission = defined_role_permission?(action, channel)
# Once we have checked the role permission, we have to check the channel overrides for the
# specific user
user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable
# Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role
return role_permission unless user_specific_override
user_specific_override == :allow
end
# Define methods for querying permissions
Discordrb::Permissions::Flags.each_value do |flag|
define_method "can_#{flag}?" do |channel = nil|
permission? flag, channel
end
end
private
def defined_role_permission?(action, channel)
# For each role, check if
# (1) the channel explicitly allows or permits an action for the role and
# (2) if the user is allowed to do the action if the channel doesn't specify
@roles.reduce(false) do |can_act, role|
# Get the override defined for the role on the channel
channel_allow = permission_overwrite(action, channel, role.id)
can_act = if channel_allow
# If the channel has an override, check whether it is an allow - if yes,
# the user can act, if not, it can't
channel_allow == :allow
else
# Otherwise defer to the role
role.permissions.instance_variable_get("@#{action}") || can_act
end
can_act
end
end
def permission_overwrite(action, channel, id)
# If no overwrites are defined, or no channel is set, no overwrite will be present
return nil unless channel && channel.permission_overwrites[id]
# Otherwise, check the allow and deny objects
allow = channel.permission_overwrites[id].allow
deny = channel.permission_overwrites[id].deny
if allow.instance_variable_get("@#{action}")
:allow
elsif deny.instance_variable_get("@#{action}")
:deny
end
# If there's no variable defined, nil will implicitly be returned
end
end
# A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like
# that.
class Member < DelegateClass(User)
include MemberAttributes
# @!visibility private
def initialize(data, server, bot)
@bot = bot
@user = bot.ensure_user(data['user'])
super @user # Initialize the delegate class
# Somehow, Discord doesn't send the server ID in the standard member format...
raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil?
@server = server || bot.server(data['guild_id'].to_i)
# Initialize the roles by getting the roles from the server one-by-one
update_roles(data['roles'])
@nick = data['nick']
@deaf = data['deaf']
@mute = data['mute']
@joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil
end
# @return [true, false] whether this member is the server owner.
def owner?
@server.owner == self
end
# @param role [Role, Integer, #resolve_id] the role to check or its ID.
# @return [true, false] whether this member has the specified role.
def role?(role)
role = role.resolve_id
@roles.any? { |e| e.id == role }
end
# Adds one or more roles to this member.
# @param role [Role, Array<Role>] The role(s) to add.
def add_role(role)
role_ids = role_id_array(role)
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids + role_ids).uniq
API.update_user_roles(@bot.token, @server.id, @user.id, new_role_ids)
end
# Removes one or more roles from this member.
# @param role [Role, Array<Role>] The role(s) to remove.
def remove_role(role)
old_role_ids = @roles.map(&:id)
role_ids = role_id_array(role)
new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) }
API.update_user_roles(@bot.token, @server.id, @user.id, new_role_ids)
end
# Server deafens this member.
def server_deafen
API.update_user_deafen(@bot.token, @server.id, @user.id, true)
end
# Server undeafens this member.
def server_undeafen
API.update_user_deafen(@bot.token, @server.id, @user.id, false)
end
# Server mutes this member.
def server_mute
API.update_user_mute(@bot.token, @server.id, @user.id, true)
end
# Server unmutes this member.
def server_unmute
API.update_user_mute(@bot.token, @server.id, @user.id, false)
end
# Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage
# Nicknames for other users.
# @param nick [String, nil] The string to set the nickname to, or nil if it should be reset.
def nick=(nick)
# Discord uses the empty string to signify 'no nickname' so we convert nil into that
nick ||= ''
if @user.current_bot?
API.change_own_nickname(@bot.token, @server.id, nick)
else
API.change_nickname(@bot.token, @server.id, @user.id, nick)
end
end
alias_method :nickname=, :nick=
# @return [String] the name the user displays as (nickname if they have one, username otherwise)
def display_name
nickname || username
end
# Update this member's roles
# @note For internal use only.
# @!visibility private
def update_roles(roles)
@roles = roles.map do |role|
role.is_a?(Role) ? role : @server.role(role.to_i)
end
end
# Update this member's nick
# @note For internal use only.
# @!visibility private
def update_nick(nick)
@nick = nick
end
# Update this member's voice state
# @note For internal use only.
# @!visibility private
def update_voice_state(channel, mute, deaf, self_mute, self_deaf)
@voice_channel = channel
@mute = mute
@deaf = deaf
@self_mute = self_mute
@self_deaf = self_deaf
end
include PermissionCalculator
# Overwriting inspect for debug purposes
def inspect
"<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>"
end
private
# Utility method to get a list of role IDs from one role or an array of roles
def role_id_array(role)
if role.is_a? Array
role.map(&:resolve_id)
else
[role.resolve_id]
end
end
end
# Recipients are members on private channels - they exist for completeness purposes, but all
# the attributes will be empty.
class Recipient < DelegateClass(User)
include MemberAttributes
# @return [Channel] the private channel this recipient is the recipient of.
attr_reader :channel
# @!visibility private
def initialize(user, channel, bot)
@bot = bot
@channel = channel
raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private?
@user = user
super @user
# Member attributes
@mute = @deaf = @self_mute = @self_deaf = false
@voice_channel = nil
@server = nil
@roles = []
@joined_at = @channel.creation_time
end
# Overwriting inspect for debug purposes
def inspect
"<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>"
end
end
# This class is a special variant of User that represents the bot's user profile (things like email addresses and the avatar).
# It can be accessed using {Bot#profile}.
class Profile < User
def initialize(data, bot, email, password)
super(data, bot)
@email = email
@password = password
end
# Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true.
# @return [true]
def current_bot?
true
end
# Sets the bot's username.
# @param username [String] The new username.
def username=(username)
update_profile_data(username: username)
end
# Sets the bot's email address. If you use this method, make sure that the login email in the script matches this
# one afterwards, so the bot doesn't have any trouble logging in in the future.
# @param email [String] The new email address.
def email=(email)
update_profile_data(email: email)
end
# Changes the bot's password. This will invalidate all tokens so you will have to relog the bot.
# @param password [String] The new password.
def password=(password)
update_profile_data(new_password: password)
end
# Changes the bot's avatar.
# @param avatar [String, #read] A JPG file to be used as the avatar, either
# something readable (e. g. File) or as a data URL.
def avatar=(avatar)
if avatar.respond_to? :read
# Set the file to binary mode if supported, so we don't get problems with Windows
avatar.binmode if avatar.respond_to?(:binmode)
avatar_string = 'data:image/jpg;base64,'
avatar_string += Base64.strict_encode64(avatar.read)
update_profile_data(avatar: avatar_string)
else
update_profile_data(avatar: avatar)
end
end
# Updates the cached profile data with the new one.
# @note For internal use only.
# @!visibility private
def update_data(new_data)
@email = new_data[:email] || @email
@password = new_data[:new_password] || @password
@username = new_data[:username] || @username
@avatar_id = new_data[:avatar_id] || @avatar_id
end
# The inspect method is overwritten to give more useful output
def inspect
"<Profile email=#{@email} user=#{super}>"
end
private
def update_profile_data(new_data)
API.update_user(@bot.token,
new_data[:email] || @email,
@password,
new_data[:username] || @username,
new_data[:avatar],
new_data[:new_password] || nil)
update_data(new_data)
end
end
# A Discord role that contains permissions and applies to certain users
class Role
include IDObject
# @return [Permissions] this role's permissions.
attr_reader :permissions
# @return [String] this role's name ("new role" if it hasn't been changed)
attr_reader :name
# @return [true, false] whether or not this role should be displayed separately from other users
attr_reader :hoist
# @return [true, false] whether this role can be mentioned using a role mention
attr_reader :mentionable
alias_method :mentionable?, :mentionable
# @return [ColourRGB] the role colour
attr_reader :colour
alias_method :color, :colour
# This class is used internally as a wrapper to a Role object that allows easy writing of permission data.
class RoleWriter
# @!visibility private
def initialize(role, token)
@role = role
@token = token
end
# Write the specified permission data to the role, without updating the permission cache
# @param bits [Integer] The packed permissions to write.
def write(bits)
@role.send(:packed=, bits, false)
end
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
@server = server
@permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token))
@name = data['name']
@id = data['id'].to_i
@hoist = data['hoist']
@mentionable = data['mentionable']
@colour = ColourRGB.new(data['color'])
end
# @return [String] a string that will mention this role, if it is mentionable.
def mention
"<@&#{@id}>"
end
# @return [Array<Member>] an array of members who have this role.
# @note This requests a member chunk if it hasn't for the server before, which may be slow initially
def members
@server.members.select { |m| m.role? role }
end
alias_method :users, :members
# Updates the data cache from another Role object
# @note For internal use only
# @!visibility private
def update_from(other)
@permissions = other.permissions
@name = other.name
@hoist = other.hoist
@colour = other.colour
end
# Updates the data cache from a hash containing data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@hoist = new_data['hoist'] unless new_data['hoist'].nil?
@hoist = new_data[:hoist] unless new_data[:hoist].nil?
@colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour)
end
# Sets the role name to something new
# @param name [String] The name that should be set
def name=(name)
update_role_data(name: name)
end
# Changes whether or not this role is displayed at the top of the user list
# @param hoist [true, false] The value it should be changed to
def hoist=(hoist)
update_role_data(hoist: hoist)
end
# Sets the role colour to something new
# @param colour [ColourRGB] The new colour
def colour=(colour)
update_role_data(colour: colour)
end
alias_method :color=, :colour=
# Changes the internal packed permissions
# @note For internal use only
# @!visibility private
def packed=(packed, update_perms = true)
update_role_data(permissions: packed)
@permissions.bits = packed if update_perms
end
# Delets this role. This cannot be undone without recreating the role!
def delete
API.delete_role(@bot.token, @server.id, @id)
@server.delete_role(@id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>"
end
private
def update_role_data(new_data)
API.update_role(@bot.token, @server.id, @id,
new_data[:name] || @name,
(new_data[:colour] || @colour).combined,
new_data[:hoist].nil? ? false : !@hoist.nil?,
new_data[:permissions] || @permissions.bits)
update_data(new_data)
end
end
# A channel referenced by an invite. It has less data than regular channels, so it's a separate class
class InviteChannel
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [String] this channel's type (text or voice)
attr_reader :type
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@type = data['type']
end
end
# A server referenced to by an invite
class InviteServer
include IDObject
# @return [String] this server's name.
attr_reader :name
# @return [String, nil] the hash of the server's invite splash screen (for partnered servers) or nil if none is
# present
attr_reader :splash_hash
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@splash_hash = data['splash_hash']
end
end
# A Discord invite to a channel
class Invite
# @return [InviteChannel] the channel this invite references.
attr_reader :channel
# @return [InviteServer] the server this invite references.
attr_reader :server
# @return [Integer] the amount of uses left on this invite.
attr_reader :uses
# @return [User, nil] the user that made this invite. May also be nil if the user can't be determined.
attr_reader :inviter
# @return [true, false] whether or not this invite is temporary.
attr_reader :temporary
# @return [true, false] whether this invite is still valid.
attr_reader :revoked
# @return [true, false] whether this invite is in xkcd format (i. e. "Human readable" in the invite settings)
attr_reader :xkcd
# @return [String] this invite's code
attr_reader :code
alias_method :max_uses, :uses
alias_method :user, :inviter
alias_method :temporary?, :temporary
alias_method :revoked?, :revoked
alias_method :xkcd?, :xkcd
# @!visibility private
def initialize(data, bot)
@bot = bot
@channel = InviteChannel.new(data['channel'], bot)
@server = InviteServer.new(data['guild'], bot)
@uses = data['uses']
@inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil
@temporary = data['temporary']
@revoked = data['revoked']
@xkcd = data['xkcdpass']
@code = data['code']
end
# Code based comparison
def ==(other)
other.respond_to?(:code) ? (@code == other.code) : (@code == other)
end
# Deletes this invite
def delete
API.delete_invite(@bot.token, @code)
end
alias_method :revoke, :delete
# The inspect method is overwritten to give more useful output
def inspect
"<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked} xkcd=#{@xkcd}>"
end
# Creates an invite URL.
def url
"https://discord.gg/#{@code}"
end
end
# A Discord channel, including data like the topic
class Channel
# The type string that stands for a text channel
# @see Channel#type
TEXT_TYPE = 'text'.freeze
# The type string that stands for a voice channel
# @see Channel#type
VOICE_TYPE = 'voice'.freeze
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil.
attr_reader :server
# @return [String] the type of this channel (currently either 'text' or 'voice')
attr_reader :type
# @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel
attr_reader :recipient
# @return [String] the channel's topic
attr_reader :topic
# @return [Integer] the channel's position on the channel list
attr_reader :position
# This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the
# `allow` and `deny` properties which are {Permissions} objects respectively.
# @return [Hash<Integer => OpenStruct>] the channel's permission overwrites
attr_reader :permission_overwrites
# @return [true, false] whether or not this channel is a PM channel.
def private?
@server.nil?
end
# @return [String] a string that will mention the channel as a clickable link on Discord.
def mention
"<##{@id}>"
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
# data is a sometimes a Hash and othertimes an array of Hashes, you only want the last one if it's an array
data = data[-1] if data.is_a?(Array)
@id = data['id'].to_i
@type = data['type'] || TEXT_TYPE
@topic = data['topic']
@position = data['position']
@is_private = data['is_private']
if @is_private
recipient_user = bot.ensure_user(data['recipient'])
@recipient = Recipient.new(recipient_user, self, bot)
@name = @recipient.username
else
@name = data['name']
@server = if server
server
else
bot.server(data['guild_id'].to_i)
end
end
# Populate permission overwrites
@permission_overwrites = {}
return unless data['permission_overwrites']
data['permission_overwrites'].each do |element|
role_id = element['id'].to_i
deny = Permissions.new(element['deny'])
allow = Permissions.new(element['allow'])
@permission_overwrites[role_id] = OpenStruct.new
@permission_overwrites[role_id].deny = deny
@permission_overwrites[role_id].allow = allow
end
end
# @return [true, false] whether or not this channel is a text channel
def text?
@type == TEXT_TYPE
end
# @return [true, false] whether or not this channel is a voice channel
def voice?
@type == VOICE_TYPE
end
# Sends a message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
# @return [Message] the message that was sent.
def send_message(content, tts = false)
@bot.send_message(@id, content, tts, @server && @server.id)
end
# Sends a temporary message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param timeout [Float] The amount of time in seconds after which the message sent will be deleted.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
def send_temporary_message(content, timeout, tts = false)
@bot.send_temporary_message(@id, content, timeout, tts, @server && @server.id)
end
# Sends multiple messages to a channel
# @param content [Array<String>] The messages to send.
def send_multiple(content)
content.each { |e| send_message(e) }
end
# Splits a message into chunks whose length is at most the Discord character limit, then sends them individually.
# Useful for sending long messages, but be wary of rate limits!
def split_send(content)
send_multiple(Discordrb.split_message(content))
end
# Sends a file to this channel. If it is an image, it will be embedded.
# @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed)
def send_file(file)
@bot.send_file(@id, file)
end
# Permanently deletes this channel
def delete
API.delete_channel(@bot.token, @id)
end
# Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations)
# @param name [String] The new name.
def name=(name)
@name = name
update_channel_data
end
# Sets this channel's topic.
# @param topic [String] The new topic.
def topic=(topic)
@topic = topic
update_channel_data
end
# Sets this channel's position in the list.
# @param position [Integer] The new position.
def position=(position)
@position = position
update_channel_data
end
# Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny
# permission sets, or change an existing one.
# @param thing [User, Role] What to define an overwrite for.
# @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a
# green checkmark on Discord)
# @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red
# cross on Discord)
# @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites
# allow = Discordrb::Permissions.new
# allow.can_mention_everyone = true
# allow.can_send_tts_messages = true
#
# deny = Discordrb::Permissions.new
# deny.can_create_instant_invite = true
#
# channel.define_overwrite(user, allow, deny)
def define_overwrite(thing, allow, deny)
allow_bits = allow.respond_to?(:bits) ? allow.bits : allow
deny_bits = deny.respond_to?(:bits) ? deny.bits : deny
# TODO: Be more flexible about what classes are allowed here
if thing.is_a?(User) || thing.is_a?(Member) || thing.is_a?(Recipient)
API.update_user_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits)
elsif thing.is_a? Role
API.update_role_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits)
end
end
# Updates the cached data from another channel.
# @note For internal use only
# @!visibility private
def update_from(other)
@topic = other.topic
@name = other.name
@recipient = other.recipient
@permission_overwrites = other.permission_overwrites
end
# The list of users currently in this channel. This is mostly useful for a voice channel, for a text channel it will
# just return the users on the server that are online.
# @return [Array<Member>] the users in this channel
def users
if @type == 'text'
@server.online_members(include_idle: true).select { |u| u.status != :offline }
else
@server.online_members(include_idle: true).select do |user|
user.voice_channel.id == @id if user.voice_channel
end
end
end
# Retrieves some of this channel's message history.
# @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher
# than 100 it will be treated as 100 on Discord's side.
# @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should
# start at the current message.
# @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start
# as soon as possible with the specified amount.
# @return [Array<Message>] the retrieved messages.
def history(amount, before_id = nil, after_id = nil)
logs = API.channel_log(@bot.token, @id, amount, before_id, after_id)
JSON.parse(logs).map { |message| Message.new(message, @bot) }
end
# Requests all pinned messages of a channel.
# @return [Array<Message>] the received messages.
def pins
msgs = API.pins(@bot.token, @id)
JSON.parse(msgs).map { |msg| Message.new(msg, @bot) }
end
# Delete the last N messages on this channel.
# @param amount [Integer] How many messages to delete. Must be a value between 2 and 100 (Discord limitation)
# @raise [ArgumentError] if the amount of messages is not a value between 2 and 100
def prune(amount)
raise ArgumentError, 'Can only prune between 2 and 100 messages!' unless amount.between?(2, 100)
messages = history(amount).map(&:id)
API.bulk_delete(@bot.token, @id, messages)
end
# Updates the cached permission overwrites
# @note For internal use only
# @!visibility private
def update_overwrites(overwrites)
@permission_overwrites = overwrites
end
# Add an {Await} for a message in this channel. This is identical in functionality to adding a
# {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block)
end
# Creates a new invite to this channel.
# @param max_age [Integer] How many seconds this invite should last.
# @param max_uses [Integer] How many times this invite should be able to be used.
# @param temporary [true, false] Whether membership should be temporary (kicked after going offline).
# @param xkcd [true, false] Whether or not the invite should be human-readable.
# @return [Invite] the created invite.
def make_invite(max_age = 0, max_uses = 0, temporary = false, xkcd = false)
response = API.create_invite(@bot.token, @id, max_age, max_uses, temporary, xkcd)
Invite.new(JSON.parse(response), @bot)
end
# Starts typing, which displays the typing indicator on the client for five seconds.
# If you want to keep typing you'll have to resend this every five seconds. (An abstraction
# for this will eventually be coming)
def start_typing
API.start_typing(@bot.token, @id)
end
alias_method :send, :send_message
alias_method :message, :send_message
alias_method :invite, :make_invite
# The inspect method is overwritten to give more useful output
def inspect
"<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>"
end
private
def update_channel_data
API.update_channel(@bot.token, @id, @name, @topic, @position)
end
end
# An attachment to a message
class Attachment
include IDObject
# @return [Message] the message this attachment belongs to.
attr_reader :message
# @return [String] the CDN URL this attachment can be downloaded at.
attr_reader :url
# @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to
# do with CDNs
attr_reader :proxy_url
# @return [String] the attachment's filename.
attr_reader :filename
# @return [Integer] the attachment's file size in bytes.
attr_reader :size
# @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image.
attr_reader :width
# @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image.
attr_reader :height
# @!visibility private
def initialize(data, message, bot)
@bot = bot
@message = message
@url = data['url']
@proxy_url = data['proxy_url']
@filename = data['filename']
@size = data['size']
@width = data['width']
@height = data['height']
end
# @return [true, false] whether this file is an image file.
def image?
!(@width.nil? || @height.nil?)
end
end
# A message on Discord that was sent to a text channel
class Message
include IDObject
# @return [String] the content of this message.
attr_reader :content
# @return [Member] the user that sent this message.
attr_reader :author
# @return [Channel] the channel in which this message was sent.
attr_reader :channel
# @return [Time] the timestamp at which this message was sent.
attr_reader :timestamp
# @return [Array<User>] the users that were mentioned in this message.
attr_reader :mentions
# @return [Array<Role>] the roles that were mentioned in this message.
attr_reader :role_mentions
# @return [Array<Attachment>] the files attached to this message.
attr_reader :attachments
# @return [true, false] whether themesage is pinned or not.
attr_reader :pinned
alias_method :pinned?, :pinned
alias_method :user, :author
alias_method :text, :content
alias_method :to_s, :content
# @!visibility private
def initialize(data, bot)
@bot = bot
@content = data['content']
@channel = bot.channel(data['channel_id'].to_i)
@pinned = data['pinned']
@author = if data['author']
if @channel.private?
# Turn the message user into a recipient - we can't use the channel recipient
# directly because the bot may also send messages to the channel
Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot)
else
member = @channel.server.member(data['author']['id'].to_i, false)
Discordrb::LOGGER.warn("Member with ID #{data['author']['id']} not cached even though it should be.") unless member
member
end
end
@timestamp = Time.parse(data['timestamp']) if data['timestamp']
@id = data['id'].to_i
@mentions = []
data['mentions'].each do |element|
@mentions << bot.ensure_user(element)
end if data['mentions']
@role_mentions = []
# Role mentions can only happen on public servers so make sure we only parse them there
unless @channel.private?
data['mention_roles'].each do |element|
@role_mentions << @channel.server.role(element.to_i)
end if data['mention_roles']
end
@attachments = []
@attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } if data['attachments']
end
# Replies to this message with the specified content.
# @see Channel#send_message
def reply(content)
@channel.send_message(content)
end
# Edits this message to have the specified content instead.
# @param new_content [String] the new content the message should have.
# @return [Message] the resulting message.
def edit(new_content)
response = API.edit_message(@bot.token, @channel.id, @id, new_content)
Message.new(JSON.parse(response), @bot)
end
# Deletes this message.
def delete
API.delete_message(@bot.token, @channel.id, @id)
nil
end
# Pins this message
def pin
API.pin_message(@bot.token, @channel.id, @id)
@pinned = true
nil
end
# Unpins this message
def unpin
API.unpin_message(@bot.token, @channel.id, @id)
@pinned = false
nil
end
# Add an {Await} for a message with the same user and channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block)
end
# @return [true, false] whether this message was sent by the current {Bot}.
def from_bot?
@author && @author.current_bot?
end
# The inspect method is overwritten to give more useful output
def inspect
"<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>"
end
end
# Basic attributes a server should have
module ServerAttributes
# @return [String] this server's name.
attr_reader :name
# @return [String] the hexadecimal ID used to identify this server's icon.
attr_reader :icon_id
# Utility function to get the URL for the icon image
# @return [String] the URL to the icon image
def icon_url
API.icon_url(@id, @icon_id)
end
end
# A server on Discord
class Server
include IDObject
include ServerAttributes
# @return [String] the region the server is on (e. g. `amsterdam`).
attr_reader :region
# @return [Member] The server owner.
attr_reader :owner
# @return [Array<Channel>] an array of all the channels (text and voice) on this server.
attr_reader :channels
# @return [Array<Role>] an array of all the roles created on this server.
attr_reader :roles
# @return [true, false] whether or not this server is large (members > 100). If it is,
# it means the members list may be inaccurate for a couple seconds after starting up the bot.
attr_reader :large
alias_method :large?, :large
# @return [Integer] the absolute number of members on this server, offline or not.
attr_reader :member_count
# @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds.
attr_reader :afk_timeout
# @return [Channel, nil] the AFK voice channel of this server, or nil if none is set
attr_reader :afk_channel
# @!visibility private
def initialize(data, bot, exists = true)
@bot = bot
@owner_id = data['owner_id'].to_i
@id = data['id'].to_i
update_data(data)
@large = data['large']
@member_count = data['member_count']
@members = {}
process_roles(data['roles'])
process_members(data['members'])
process_presences(data['presences'])
process_channels(data['channels'])
process_voice_states(data['voice_states'])
# Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet
@chunked = false
@processed_chunk_members = 0
# Only get the owner of the server actually exists (i. e. not for ServerDeleteEvent)
@owner = member(@owner_id) if exists
end
# @return [Channel] The default channel on this server (usually called #general)
def default_channel
@bot.channel(@id)
end
alias_method :general_channel, :default_channel
# Gets a role on this server based on its ID.
# @param id [Integer] The role ID to look for.
def role(id)
@roles.find { |e| e.id == id }
end
# Gets a member on this server based on user ID
# @param id [Integer] The user ID to look for
# @param request [true, false] Whether the member should be requested from Discord if it's not cached
def member(id, request = true)
id = id.resolve_id
return @members[id] if member_cached?(id)
return nil unless request
member = @bot.member(@id, id)
@members[id] = member
rescue
nil
end
# @return [Array<Member>] an array of all the members on this server.
def members
return @members.values if @chunked
@bot.debug("Members for server #{@id} not chunked yet - initiating")
@bot.request_chunks(@id)
sleep 0.05 until @chunked
@members.values
end
alias_method :users, :members
# @param include_idle [true, false] Whether to count idle members as online.
# @param include_bots [true, false] Whether to include bot accounts in the count.
# @return [Array<Member>] an array of online members on this server.
def online_members(include_idle: false, include_bots: true)
@members.values.select do |e|
((include_idle ? e.idle? : false) || e.online?) && (include_bots ? true : !e.bot_account?)
end
end
alias_method :online_users, :online_members
# @return [Array<Channel>] an array of text channels on this server
def text_channels
@channels.select(&:text?)
end
# @return [Array<Channel>] an array of voice channels on this server
def voice_channels
@channels.select(&:voice?)
end
# Adds a role to the role cache
# @note For internal use only
# @!visibility private
def add_role(role)
@roles << role
end
# Removes a role from the role cache
# @note For internal use only
# @!visibility private
def delete_role(role_id)
@roles.reject! { |r| r.id == role_id }
@members.each do |_, member|
new_roles = member.roles.reject { |r| r.id == role_id }
member.update_roles(new_roles)
end
@channels.each do |channel|
overwrites = channel.permission_overwrites.reject { |id, _| id == role_id }
channel.update_overwrites(overwrites)
end
end
# Adds a member to the member cache.
# @note For internal use only
# @!visibility private
def add_member(member)
@members[member.id] = member
@member_count += 1
end
# Removes a member from the member cache.
# @note For internal use only
# @!visibility private
def delete_member(user_id)
@members.delete(user_id)
@member_count -= 1
end
# Checks whether a member is cached
# @note For internal use only
# @!visibility private
def member_cached?(user_id)
@members.include?(user_id)
end
# Adds a member to the cache
# @note For internal use only
# @!visibility private
def cache_member(member)
@members[member.id] = member
end
# Creates a channel on this server with the given name.
# @return [Channel] the created channel.
def create_channel(name, type = 'text')
response = API.create_channel(@bot.token, @id, name, type)
Channel.new(JSON.parse(response), @bot)
end
# Creates a role on this server which can then be modified. It will be initialized (on Discord's side)
# with the regular role defaults the client uses, i. e. name is "new role", permissions are the default,
# colour is the default etc.
# @return [Role] the created role.
def create_role
response = API.create_role(@bot.token, @id)
role = Role.new(JSON.parse(response), @bot, self)
@roles << role
role
end
# @return [Array<User>] a list of banned users on this server.
def bans
users = JSON.parse(API.bans(@bot.token, @id))
users.map { |e| User.new(e['user'], @bot) }
end
# Bans a user from this server.
# @param user [User, #resolve_id] The user to ban.
# @param message_days [Integer] How many days worth of messages sent by the user should be deleted.
def ban(user, message_days = 0)
API.ban_user(@bot.token, @id, user.resolve_id, message_days)
end
# Unbans a previously banned user from this server.
# @param user [User, #resolve_id] The user to unban.
def unban(user)
API.unban_user(@bot.token, @id, user.resolve_id)
end
# Kicks a user from this server.
# @param user [User, #resolve_id] The user to kick.
def kick(user)
API.kick_user(@bot.token, @id, user.resolve_id)
end
# Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed.
# @param user [User] The user to move.
# @param channel [Channel] The voice channel to move into.
def move(user, channel)
API.move_user(@bot.token, @id, user.id, channel.id)
end
# Deletes this server. Be aware that this is permanent and impossible to undo, so be careful!
def delete
API.delete_server(@bot.token, @id)
end
# Leave the server
def leave
API.leave_server(@bot.token, @id)
end
# Transfers server ownership to another user.
# @param user [User] The user who should become the new owner.
def owner=(user)
API.transfer_ownership(@bot.token, @id, user.id)
end
# Sets the server's name.
# @param name [String] The new server name.
def name=(name)
update_server_data(name: name)
end
# Moves the server to another region. This will cause a voice interruption of at most a second.
# @param region [String] The new region the server should be in.
def region=(region)
update_server_data(region: region.to_s)
end
# Sets the server's icon.
# @param icon [String, #read] The new icon, in base64-encoded JPG format.
def icon=(icon)
if icon.respond_to? :read
icon_string = 'data:image/jpg;base64,'
icon_string += Base64.strict_encode64(icon.read)
update_server_data(icon: icon_string)
else
update_server_data(icon: icon)
end
end
# Sets the server's AFK channel.
# @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set.
def afk_channel=(afk_channel)
update_server_data(afk_channel_id: afk_channel.resolve_id)
end
# Sets the amount of time after which a user gets moved into the AFK channel.
# @param afk_timeout [Integer] The AFK timeout, in seconds.
def afk_timeout=(afk_timeout)
update_server_data(afk_timeout: afk_timeout)
end
# Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field
# @note For internal use only
# @!visibility private
def process_chunk(members)
process_members(members)
@processed_chunk_members += members.length
LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}")
# Don't bother with the rest of the method if it's not truly the last packet
return unless @processed_chunk_members == @member_count
LOGGER.debug("Finished chunking server #{@id}")
# Reset everything to normal
@chunked = true
@processed_chunk_members = 0
end
# Updates the cached data with new data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@region = new_data[:region] || new_data['region'] || @region
@icon_id = new_data[:icon] || new_data['icon'] || @icon_id
@afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout
@afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id
@afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id != 0 && (!@afk_channel || @afk_channel_id != @afk_channel.id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>"
end
private
def update_server_data(new_data)
API.update_server(@bot.token, @id,
new_data[:name] || @name,
new_data[:region] || @region,
new_data[:icon_id] || @icon_id,
new_data[:afk_channel_id] || @afk_channel_id,
new_data[:afk_timeout] || @afk_timeout)
update_data(new_data)
end
def process_roles(roles)
# Create roles
@roles = []
@roles_by_id = {}
return unless roles
roles.each do |element|
role = Role.new(element, @bot, self)
@roles << role
@roles_by_id[role.id] = role
end
end
def process_members(members)
return unless members
members.each do |element|
member = Member.new(element, self, @bot)
if @members[member.id] && @members[member.id].voice_channel
@bot.debug("Preserving voice state of member #{member.id} while chunking")
old_member = @members[member.id]
member.update_voice_state(
old_member.voice_channel,
old_member.mute,
old_member.deaf,
old_member.self_mute,
old_member.self_deaf
)
end
@members[member.id] = member
end
end
def process_presences(presences)
# Update user statuses with presence info
return unless presences
presences.each do |element|
next unless element['user']
user_id = element['user']['id'].to_i
user = @members[user_id]
if user
user.status = element['status'].to_sym
user.game = element['game'] ? element['game']['name'] : nil
end
end
end
def process_channels(channels)
@channels = []
@channels_by_id = {}
return unless channels
channels.each do |element|
channel = @bot.ensure_channel(element, self)
@channels << channel
@channels_by_id[channel.id] = channel
end
end
def process_voice_states(voice_states)
return unless voice_states
voice_states.each do |element|
user_id = element['user_id'].to_i
member = @members[user_id]
next unless member
channel_id = element['channel_id'].to_i
channel = channel_id ? @channels_by_id[channel_id] : nil
member.update_voice_state(
channel,
element['mute'],
element['deaf'],
element['self_mute'],
element['self_deaf'])
end
end
end
# A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias
# {ColorRGB} is also available.
class ColourRGB
# @return [Integer] the red part of this colour (0-255).
attr_reader :red
# @return [Integer] the green part of this colour (0-255).
attr_reader :green
# @return [Integer] the blue part of this colour (0-255).
attr_reader :blue
# @return [Integer] the colour's RGB values combined into one integer.
attr_reader :combined
# Make a new colour from the combined value.
# @param combined [Integer] The colour's RGB values combined into one integer
def initialize(combined)
@combined = combined
@red = (combined >> 16) & 0xFF
@green = (combined >> 8) & 0xFF
@blue = combined & 0xFF
end
end
# Alias for the class {ColourRGB}
ColorRGB = ColourRGB
end
|
# frozen_string_literal: true
# These classes hold relevant Discord data, such as messages or channels.
require 'ostruct'
require 'discordrb/permissions'
require 'discordrb/api'
require 'discordrb/events/message'
require 'time'
require 'base64'
# Discordrb module
module Discordrb
# The unix timestamp Discord IDs are based on
DISCORD_EPOCH = 1_420_070_400_000
# Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID.
def self.id_compare(one_id, other)
other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other)
end
# The maximum length a Discord message can have
CHARACTER_LIMIT = 2000
# Splits a message into chunks of 2000 characters. Attempts to split by lines if possible.
# @param msg [String] The message to split.
# @return [Array<String>] the message split into chunks
def self.split_message(msg)
# If the messages is empty, return an empty array
return [] if msg.empty?
# Split the message into lines
lines = msg.lines
# Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become
# [
# [1],
# [1, 2],
# [1, 2, 3],
# [1, 2, 3, 4]
# ]
tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first }
# Join the individual elements together to get an array of strings with consecutively more lines
joined = tri.map(&:join)
# Find the largest element that is still below the character limit, or if none such element exists return the first
ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length }
# If it's still larger than the character limit (none was smaller than it) split it into slices with the length
# being the character limit, otherwise just return an array with one element
ideal_ary = (ideal.length > CHARACTER_LIMIT) ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal]
# Slice off the ideal part and strip newlines
rest = msg[ideal.length..-1].strip
# If none remains, return an empty array -> we're done
return [] unless rest
# Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array
ideal_ary + split_message(rest)
end
# Mixin for objects that have IDs
module IDObject
# @return [Integer] the ID which uniquely identifies this object across Discord.
attr_reader :id
alias_method :resolve_id, :id
# ID based comparison
def ==(other)
Discordrb.id_compare(@id, other)
end
# Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but
# shouldn't be relied on as Discord might change its algorithm at any time
# @return [Time] when this object was created at
def creation_time
# Milliseconds
ms = (@id >> 22) + DISCORD_EPOCH
Time.at(ms / 1000.0)
end
end
# Mixin for the attributes users should have
module UserAttributes
# @return [String] this user's username
attr_reader :username
alias_method :name, :username
# @return [String] this user's discriminator which is used internally to identify users with identical usernames.
attr_reader :discriminator
alias_method :discrim, :discriminator
alias_method :tag, :discriminator
alias_method :discord_tag, :discriminator
# @return [true, false] whether this user is a Discord bot account
attr_reader :bot_account
alias_method :bot_account?, :bot_account
# @return [String] the ID of this user's current avatar, can be used to generate an avatar URL.
# @see #avatar_url
attr_reader :avatar_id
# Utility function to mention users in messages
# @return [String] the mention code in the form of <@id>
def mention
"<@#{@id}>"
end
# Utility function to get Discord's distinct representation of a user, i. e. username + discriminator
# @return [String] distinct representation of user
def distinct
"#{@username}##{@discriminator}"
end
# Utility function to get a user's avatar URL.
# @return [String] the URL to the avatar image.
def avatar_url
API.avatar_url(@id, @avatar_id)
end
end
# User on Discord, including internal data like discriminators
class User
include IDObject
include UserAttributes
# @!attribute [r] status
# @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`)
attr_accessor :status
# @!attribute [r] game
# @return [String, nil] the game the user is currently playing, or `nil` if none is being played.
attr_accessor :game
def initialize(data, bot)
@bot = bot
@username = data['username']
@id = data['id'].to_i
@discriminator = data['discriminator']
@avatar_id = data['avatar']
@roles = {}
@bot_account = false
@bot_account = true if data['bot']
@status = :offline
end
# Get a user's PM channel or send them a PM
# @overload pm
# Creates a private message channel for this user or returns an existing one if it already exists
# @return [Channel] the PM channel to this user.
# @overload pm(content)
# Sends a private to this user.
# @param content [String] The content to send.
# @return [Message] the message sent to this user.
def pm(content = nil)
if content
# Recursively call pm to get the channel, then send a message to it
channel = pm
channel.send_message(content)
else
# If no message was specified, return the PM channel
@bot.private_channel(@id)
end
end
# Set the user's name
# @note for internal use only
# @!visibility private
def update_username(username)
@username = username
end
# Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this
# user's ID as a :from attribute.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block)
end
# Gets the member this user is on a server
# @param server [Server] The server to get the member for
# @return [Member] this user as a member on a particular server
def on(server)
id = server.resolve_id
@bot.server(id).member(@id)
end
# Is the user the bot?
# @return [true, false] whether this user is the bot
def current_bot?
@bot.profile.id == @id
end
[:offline, :idle, :online].each do |e|
define_method(e.to_s + '?') do
@status.to_sym == e
end
end
# The inspect method is overwritten to give more useful output
def inspect
"<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>"
end
end
# Mixin for the attributes members and private members should have
module MemberAttributes
# @return [true, false] whether this member is muted server-wide.
attr_reader :mute
alias_method :muted?, :mute
# @return [true, false] whether this member is deafened server-wide.
attr_reader :deaf
alias_method :deafened?, :deaf
# @return [true, false] whether this member has muted themselves.
attr_reader :self_mute
alias_method :self_muted?, :self_mute
# @return [true, false] whether this member has deafened themselves.
attr_reader :self_deaf
alias_method :self_deafened?, :self_deaf
# @return [Time] when this member joined the server.
attr_reader :joined_at
# @return [String, nil] the nickname this member has, or nil if it has none.
attr_reader :nick
alias_method :nickname, :nick
# @return [Array<Role>] the roles this member has.
attr_reader :roles
# @return [Server] the server this member is on.
attr_reader :server
# @return [Channel] the voice channel the user is in.
attr_reader :voice_channel
end
# Mixin to calculate resulting permissions from overrides etc.
module PermissionCalculator
# Checks whether this user can do the particular action, regardless of whether it has the permission defined,
# through for example being the server owner or having the Manage Roles permission
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @return [true, false] whether or not this user has the permission.
def permission?(action, channel = nil)
# If the member is the server owner, it irrevocably has all permissions.
return true if owner?
# First, check whether the user has Manage Roles defined.
# (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a
# Manage Permissions deny overwrite will override Manage Roles, so we can just check for
# Manage Roles once and call it a day.)
return true if defined_permission?(:manage_roles, channel)
# Otherwise, defer to defined_permission
defined_permission?(action, channel)
end
# Checks whether this user has a particular permission defined (i. e. not implicit, through for example
# Manage Roles)
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @return [true, false] whether or not this user has the permission defined.
def defined_permission?(action, channel = nil)
# Get the permission the user's roles have
role_permission = defined_role_permission?(action, channel)
# Once we have checked the role permission, we have to check the channel overrides for the
# specific user
user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable
# Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role
return role_permission unless user_specific_override
user_specific_override == :allow
end
# Define methods for querying permissions
Discordrb::Permissions::Flags.each_value do |flag|
define_method "can_#{flag}?" do |channel = nil|
permission? flag, channel
end
end
private
def defined_role_permission?(action, channel)
# For each role, check if
# (1) the channel explicitly allows or permits an action for the role and
# (2) if the user is allowed to do the action if the channel doesn't specify
@roles.reduce(false) do |can_act, role|
# Get the override defined for the role on the channel
channel_allow = permission_overwrite(action, channel, role.id)
can_act = if channel_allow
# If the channel has an override, check whether it is an allow - if yes,
# the user can act, if not, it can't
channel_allow == :allow
else
# Otherwise defer to the role
role.permissions.instance_variable_get("@#{action}") || can_act
end
can_act
end
end
def permission_overwrite(action, channel, id)
# If no overwrites are defined, or no channel is set, no overwrite will be present
return nil unless channel && channel.permission_overwrites[id]
# Otherwise, check the allow and deny objects
allow = channel.permission_overwrites[id].allow
deny = channel.permission_overwrites[id].deny
if allow.instance_variable_get("@#{action}")
:allow
elsif deny.instance_variable_get("@#{action}")
:deny
end
# If there's no variable defined, nil will implicitly be returned
end
end
# A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like
# that.
class Member < DelegateClass(User)
include MemberAttributes
# @!visibility private
def initialize(data, server, bot)
@bot = bot
@user = bot.ensure_user(data['user'])
super @user # Initialize the delegate class
# Somehow, Discord doesn't send the server ID in the standard member format...
raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil?
@server = server || bot.server(data['guild_id'].to_i)
# Initialize the roles by getting the roles from the server one-by-one
update_roles(data['roles'])
@nick = data['nick']
@deaf = data['deaf']
@mute = data['mute']
@joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil
end
# @return [true, false] whether this member is the server owner.
def owner?
@server.owner == self
end
# @param role [Role, Integer, #resolve_id] the role to check or its ID.
# @return [true, false] whether this member has the specified role.
def role?(role)
role = role.resolve_id
@roles.any? { |e| e.id == role }
end
# Adds one or more roles to this member.
# @param role [Role, Array<Role>] The role(s) to add.
def add_role(role)
role_ids = role_id_array(role)
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids + role_ids).uniq
API.update_user_roles(@bot.token, @server.id, @user.id, new_role_ids)
end
# Removes one or more roles from this member.
# @param role [Role, Array<Role>] The role(s) to remove.
def remove_role(role)
old_role_ids = @roles.map(&:id)
role_ids = role_id_array(role)
new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) }
API.update_user_roles(@bot.token, @server.id, @user.id, new_role_ids)
end
# Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage
# Nicknames for other users.
# @param nick [String, nil] The string to set the nickname to, or nil if it should be reset.
def nick=(nick)
# Discord uses the empty string to signify 'no nickname' so we convert nil into that
nick ||= ''
API.change_nickname(@bot.token, @server.id, @user.id, nick)
end
alias_method :nickname=, :nick=
# @return [String] the name the user displays as (nickname if they have one, username otherwise)
def display_name
nickname || username
end
# Update this member's roles
# @note For internal use only.
# @!visibility private
def update_roles(roles)
@roles = roles.map do |role|
role.is_a?(Role) ? role : @server.role(role.to_i)
end
end
# Update this member's nick
# @note For internal use only.
# @!visibility private
def update_nick(nick)
@nick = nick
end
# Update this member's voice state
# @note For internal use only.
# @!visibility private
def update_voice_state(channel, mute, deaf, self_mute, self_deaf)
@voice_channel = channel
@mute = mute
@deaf = deaf
@self_mute = self_mute
@self_deaf = self_deaf
end
include PermissionCalculator
# Overwriting inspect for debug purposes
def inspect
"<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>"
end
private
# Utility method to get a list of role IDs from one role or an array of roles
def role_id_array(role)
if role.is_a? Array
role.map(&:resolve_id)
else
[role.resolve_id]
end
end
end
# Recipients are members on private channels - they exist for completeness purposes, but all
# the attributes will be empty.
class Recipient < DelegateClass(User)
include MemberAttributes
# @return [Channel] the private channel this recipient is the recipient of.
attr_reader :channel
# @!visibility private
def initialize(user, channel, bot)
@bot = bot
@channel = channel
raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private?
@user = user
super @user
# Member attributes
@mute = @deaf = @self_mute = @self_deaf = false
@voice_channel = nil
@server = nil
@roles = []
@joined_at = @channel.creation_time
end
# Overwriting inspect for debug purposes
def inspect
"<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>"
end
end
# This class is a special variant of User that represents the bot's user profile (things like email addresses and the avatar).
# It can be accessed using {Bot#profile}.
class Profile < User
def initialize(data, bot, email, password)
super(data, bot)
@email = email
@password = password
end
# Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true.
# @return [true]
def current_bot?
true
end
# Sets the bot's username.
# @param username [String] The new username.
def username=(username)
update_profile_data(username: username)
end
# Sets the bot's email address. If you use this method, make sure that the login email in the script matches this
# one afterwards, so the bot doesn't have any trouble logging in in the future.
# @param email [String] The new email address.
def email=(email)
update_profile_data(email: email)
end
# Changes the bot's password. This will invalidate all tokens so you will have to relog the bot.
# @param password [String] The new password.
def password=(password)
update_profile_data(new_password: password)
end
# Changes the bot's avatar.
# @param avatar [String, #read] A JPG file to be used as the avatar, either
# something readable (e. g. File) or as a data URL.
def avatar=(avatar)
if avatar.respond_to? :read
# Set the file to binary mode if supported, so we don't get problems with Windows
avatar.binmode if avatar.respond_to?(:binmode)
avatar_string = 'data:image/jpg;base64,'
avatar_string += Base64.strict_encode64(avatar.read)
update_profile_data(avatar: avatar_string)
else
update_profile_data(avatar: avatar)
end
end
# Updates the cached profile data with the new one.
# @note For internal use only.
# @!visibility private
def update_data(new_data)
@email = new_data[:email] || @email
@password = new_data[:new_password] || @password
@username = new_data[:username] || @username
@avatar_id = new_data[:avatar_id] || @avatar_id
end
# The inspect method is overwritten to give more useful output
def inspect
"<Profile email=#{@email} user=#{super}>"
end
private
def update_profile_data(new_data)
API.update_user(@bot.token,
new_data[:email] || @email,
@password,
new_data[:username] || @username,
new_data[:avatar],
new_data[:new_password] || nil)
update_data(new_data)
end
end
# A Discord role that contains permissions and applies to certain users
class Role
include IDObject
# @return [Permissions] this role's permissions.
attr_reader :permissions
# @return [String] this role's name ("new role" if it hasn't been changed)
attr_reader :name
# @return [true, false] whether or not this role should be displayed separately from other users
attr_reader :hoist
# @return [true, false] whether this role can be mentioned using a role mention
attr_reader :mentionable
alias_method :mentionable?, :mentionable
# @return [ColourRGB] the role colour
attr_reader :colour
alias_method :color, :colour
# This class is used internally as a wrapper to a Role object that allows easy writing of permission data.
class RoleWriter
# @!visibility private
def initialize(role, token)
@role = role
@token = token
end
# Write the specified permission data to the role, without updating the permission cache
# @param bits [Integer] The packed permissions to write.
def write(bits)
@role.send(:packed=, bits, false)
end
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
@server = server
@permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token))
@name = data['name']
@id = data['id'].to_i
@hoist = data['hoist']
@mentionable = data['mentionable']
@colour = ColourRGB.new(data['color'])
end
# @return [String] a string that will mention this role, if it is mentionable.
def mention
"<@&#{@id}>"
end
# Updates the data cache from another Role object
# @note For internal use only
# @!visibility private
def update_from(other)
@permissions = other.permissions
@name = other.name
@hoist = other.hoist
@colour = other.colour
end
# Updates the data cache from a hash containing data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@hoist = new_data['hoist'] unless new_data['hoist'].nil?
@hoist = new_data[:hoist] unless new_data[:hoist].nil?
@colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour)
end
# Sets the role name to something new
# @param name [String] The name that should be set
def name=(name)
update_role_data(name: name)
end
# Changes whether or not this role is displayed at the top of the user list
# @param hoist [true, false] The value it should be changed to
def hoist=(hoist)
update_role_data(hoist: hoist)
end
# Sets the role colour to something new
# @param colour [ColourRGB] The new colour
def colour=(colour)
update_role_data(colour: colour)
end
alias_method :color=, :colour=
# Changes the internal packed permissions
# @note For internal use only
# @!visibility private
def packed=(packed, update_perms = true)
update_role_data(permissions: packed)
@permissions.bits = packed if update_perms
end
# Delets this role. This cannot be undone without recreating the role!
def delete
API.delete_role(@bot.token, @server.id, @id)
@server.delete_role(@id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>"
end
private
def update_role_data(new_data)
API.update_role(@bot.token, @server.id, @id,
new_data[:name] || @name,
(new_data[:colour] || @colour).combined,
new_data[:hoist].nil? ? false : !@hoist.nil?,
new_data[:permissions] || @permissions.bits)
update_data(new_data)
end
end
# A channel referenced by an invite. It has less data than regular channels, so it's a separate class
class InviteChannel
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [String] this channel's type (text or voice)
attr_reader :type
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@type = data['type']
end
end
# A server referenced to by an invite
class InviteServer
include IDObject
# @return [String] this server's name.
attr_reader :name
# @return [String, nil] the hash of the server's invite splash screen (for partnered servers) or nil if none is
# present
attr_reader :splash_hash
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@splash_hash = data['splash_hash']
end
end
# A Discord invite to a channel
class Invite
# @return [InviteChannel] the channel this invite references.
attr_reader :channel
# @return [InviteServer] the server this invite references.
attr_reader :server
# @return [Integer] the amount of uses left on this invite.
attr_reader :uses
# @return [User, nil] the user that made this invite. May also be nil if the user can't be determined.
attr_reader :inviter
# @return [true, false] whether or not this invite is temporary.
attr_reader :temporary
# @return [true, false] whether this invite is still valid.
attr_reader :revoked
# @return [true, false] whether this invite is in xkcd format (i. e. "Human readable" in the invite settings)
attr_reader :xkcd
# @return [String] this invite's code
attr_reader :code
alias_method :max_uses, :uses
alias_method :user, :inviter
alias_method :temporary?, :temporary
alias_method :revoked?, :revoked
alias_method :xkcd?, :xkcd
# @!visibility private
def initialize(data, bot)
@bot = bot
@channel = InviteChannel.new(data['channel'], bot)
@server = InviteServer.new(data['guild'], bot)
@uses = data['uses']
@inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil
@temporary = data['temporary']
@revoked = data['revoked']
@xkcd = data['xkcdpass']
@code = data['code']
end
# Code based comparison
def ==(other)
other.respond_to?(:code) ? (@code == other.code) : (@code == other)
end
# Deletes this invite
def delete
API.delete_invite(@bot.token, @code)
end
alias_method :revoke, :delete
# The inspect method is overwritten to give more useful output
def inspect
"<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked} xkcd=#{@xkcd}>"
end
# Creates an invite URL.
def url
"https://discord.gg/#{@code}"
end
end
# A Discord channel, including data like the topic
class Channel
# The type string that stands for a text channel
# @see Channel#type
TEXT_TYPE = 'text'.freeze
# The type string that stands for a voice channel
# @see Channel#type
VOICE_TYPE = 'voice'.freeze
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil.
attr_reader :server
# @return [String] the type of this channel (currently either 'text' or 'voice')
attr_reader :type
# @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel
attr_reader :recipient
# @return [String] the channel's topic
attr_reader :topic
# @return [Integer] the channel's position on the channel list
attr_reader :position
# This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the
# `allow` and `deny` properties which are {Permissions} objects respectively.
# @return [Hash<Integer => OpenStruct>] the channel's permission overwrites
attr_reader :permission_overwrites
# @return [true, false] whether or not this channel is a PM channel.
def private?
@server.nil?
end
# @return [String] a string that will mention the channel as a clickable link on Discord.
def mention
"<##{@id}>"
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
# data is a sometimes a Hash and othertimes an array of Hashes, you only want the last one if it's an array
data = data[-1] if data.is_a?(Array)
@id = data['id'].to_i
@type = data['type'] || TEXT_TYPE
@topic = data['topic']
@position = data['position']
@is_private = data['is_private']
if @is_private
recipient_user = bot.ensure_user(data['recipient'])
@recipient = Recipient.new(recipient_user, self, bot)
@name = @recipient.username
else
@name = data['name']
@server = if server
server
else
bot.server(data['guild_id'].to_i)
end
end
# Populate permission overwrites
@permission_overwrites = {}
return unless data['permission_overwrites']
data['permission_overwrites'].each do |element|
role_id = element['id'].to_i
deny = Permissions.new(element['deny'])
allow = Permissions.new(element['allow'])
@permission_overwrites[role_id] = OpenStruct.new
@permission_overwrites[role_id].deny = deny
@permission_overwrites[role_id].allow = allow
end
end
# @return [true, false] whether or not this channel is a text channel
def text?
@type == TEXT_TYPE
end
# @return [true, false] whether or not this channel is a voice channel
def voice?
@type == VOICE_TYPE
end
# Sends a message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
# @return [Message] the message that was sent.
def send_message(content, tts = false)
@bot.send_message(@id, content, tts, @server && @server.id)
end
# Sends multiple messages to a channel
# @param content [Array<String>] The messages to send.
def send_multiple(content)
content.each { |e| send_message(e) }
end
# Splits a message into chunks whose length is at most the Discord character limit, then sends them individually.
# Useful for sending long messages, but be wary of rate limits!
def split_send(content)
send_multiple(Discordrb.split_message(content))
end
# Sends a file to this channel. If it is an image, it will be embedded.
# @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed)
def send_file(file)
@bot.send_file(@id, file)
end
# Permanently deletes this channel
def delete
API.delete_channel(@bot.token, @id)
end
# Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations)
# @param name [String] The new name.
def name=(name)
@name = name
update_channel_data
end
# Sets this channel's topic.
# @param topic [String] The new topic.
def topic=(topic)
@topic = topic
update_channel_data
end
# Sets this channel's position in the list.
# @param position [Integer] The new position.
def position=(position)
@position = position
update_channel_data
end
# Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny
# permission sets, or change an existing one.
# @param thing [User, Role] What to define an overwrite for.
# @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a
# green checkmark on Discord)
# @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red
# cross on Discord)
# @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites
# allow = Discordrb::Permissions.new
# allow.can_mention_everyone = true
# allow.can_send_tts_messages = true
#
# deny = Discordrb::Permissions.new
# deny.can_create_instant_invite = true
#
# channel.define_overwrite(user, allow, deny)
def define_overwrite(thing, allow, deny)
allow_bits = allow.respond_to?(:bits) ? allow.bits : allow
deny_bits = deny.respond_to?(:bits) ? deny.bits : deny
if thing.is_a? User
API.update_user_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits)
elsif thing.is_a? Role
API.update_role_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits)
end
end
# Updates the cached data from another channel.
# @note For internal use only
# @!visibility private
def update_from(other)
@topic = other.topic
@name = other.name
@recipient = other.recipient
@permission_overwrites = other.permission_overwrites
end
# The list of users currently in this channel. This is mostly useful for a voice channel, for a text channel it will
# just return the users on the server that are online.
# @return [Array<Member>] the users in this channel
def users
if @type == 'text'
@server.members.select { |u| u.status != :offline }
else
@server.members.select do |user|
user.voice_channel.id == @id if user.voice_channel
end
end
end
# Retrieves some of this channel's message history.
# @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher
# than 100 it will be treated as 100 on Discord's side.
# @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should
# start at the current message.
# @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start
# as soon as possible with the specified amount.
# @return [Array<Message>] the retrieved messages.
def history(amount, before_id = nil, after_id = nil)
logs = API.channel_log(@bot.token, @id, amount, before_id, after_id)
JSON.parse(logs).map { |message| Message.new(message, @bot) }
end
# Requests all pinned messages of a channel.
# @return [Array<Message>] the received messages.
def pins
msgs = API.pins(@bot.token, @id)
JSON.parse(msgs).map { |msg| Message.new(msg, @bot) }
end
# Delete the last N messages on this channel.
# @param amount [Integer] How many messages to delete. Must be a value between 2 and 100 (Discord limitation)
# @raise [ArgumentError] if the amount of messages is not a value between 2 and 100
def prune(amount)
raise ArgumentError, 'Can only prune between 2 and 100 messages!' unless amount.between?(2, 100)
messages = history(amount).map(&:id)
API.bulk_delete(@bot.token, @id, messages)
end
# Updates the cached permission overwrites
# @note For internal use only
# @!visibility private
def update_overwrites(overwrites)
@permission_overwrites = overwrites
end
# Add an {Await} for a message in this channel. This is identical in functionality to adding a
# {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block)
end
# Creates a new invite to this channel.
# @param max_age [Integer] How many seconds this invite should last.
# @param max_uses [Integer] How many times this invite should be able to be used.
# @param temporary [true, false] Whether membership should be temporary (kicked after going offline).
# @param xkcd [true, false] Whether or not the invite should be human-readable.
# @return [Invite] the created invite.
def make_invite(max_age = 0, max_uses = 0, temporary = false, xkcd = false)
response = API.create_invite(@bot.token, @id, max_age, max_uses, temporary, xkcd)
Invite.new(JSON.parse(response), @bot)
end
# Starts typing, which displays the typing indicator on the client for five seconds.
# If you want to keep typing you'll have to resend this every five seconds. (An abstraction
# for this will eventually be coming)
def start_typing
API.start_typing(@bot.token, @id)
end
alias_method :send, :send_message
alias_method :message, :send_message
alias_method :invite, :make_invite
# The inspect method is overwritten to give more useful output
def inspect
"<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>"
end
private
def update_channel_data
API.update_channel(@bot.token, @id, @name, @topic, @position)
end
end
# An attachment to a message
class Attachment
include IDObject
# @return [Message] the message this attachment belongs to.
attr_reader :message
# @return [String] the CDN URL this attachment can be downloaded at.
attr_reader :url
# @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to
# do with CDNs
attr_reader :proxy_url
# @return [String] the attachment's filename.
attr_reader :filename
# @return [Integer] the attachment's file size in bytes.
attr_reader :size
# @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image.
attr_reader :width
# @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image.
attr_reader :height
# @!visibility private
def initialize(data, message, bot)
@bot = bot
@message = message
@url = data['url']
@proxy_url = data['proxy_url']
@filename = data['filename']
@size = data['size']
@width = data['width']
@height = data['height']
end
# @return [true, false] whether this file is an image file.
def image?
!(@width.nil? || @height.nil?)
end
end
# A message on Discord that was sent to a text channel
class Message
include IDObject
# @return [String] the content of this message.
attr_reader :content
# @return [Member] the user that sent this message.
attr_reader :author
# @return [Channel] the channel in which this message was sent.
attr_reader :channel
# @return [Time] the timestamp at which this message was sent.
attr_reader :timestamp
# @return [Array<User>] the users that were mentioned in this message.
attr_reader :mentions
# @return [Array<Role>] the roles that were mentioned in this message.
attr_reader :role_mentions
# @return [Array<Attachment>] the files attached to this message.
attr_reader :attachments
alias_method :user, :author
alias_method :text, :content
alias_method :to_s, :content
# @!visibility private
def initialize(data, bot)
@bot = bot
@content = data['content']
@channel = bot.channel(data['channel_id'].to_i)
@author = if data['author']
if @channel.private?
# Turn the message user into a recipient - we can't use the channel recipient
# directly because the bot may also send messages to the channel
Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot)
else
member = @channel.server.member(data['author']['id'].to_i, false)
Discordrb::LOGGER.warn("Member with ID #{data['author']['id']} not cached even though it should be.") unless member
member
end
end
@timestamp = Time.parse(data['timestamp']) if data['timestamp']
@id = data['id'].to_i
@mentions = []
data['mentions'].each do |element|
@mentions << bot.ensure_user(element)
end if data['mentions']
@role_mentions = []
# Role mentions can only happen on public servers so make sure we only parse them there
unless @channel.private?
data['mention_roles'].each do |element|
@role_mentions << @channel.server.role(element.to_i)
end if data['mention_roles']
end
@attachments = []
@attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } if data['attachments']
end
# Replies to this message with the specified content.
# @see Channel#send_message
def reply(content)
@channel.send_message(content)
end
# Edits this message to have the specified content instead.
# @param new_content [String] the new content the message should have.
# @return [Message] the resulting message.
def edit(new_content)
response = API.edit_message(@bot.token, @channel.id, @id, new_content)
Message.new(JSON.parse(response), @bot)
end
# Deletes this message.
def delete
API.delete_message(@bot.token, @channel.id, @id)
nil
end
# Pins this message
def pin
API.pin_message(@bot.token, @channel.id, @id)
nil
end
# Unpins this message
def unpin
API.unpin_message(@bot.token, @channel.id, @id)
nil
end
# Add an {Await} for a message with the same user and channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block)
end
# @return [true, false] whether this message was sent by the current {Bot}.
def from_bot?
@author && @author.current_bot?
end
# The inspect method is overwritten to give more useful output
def inspect
"<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>"
end
end
# Basic attributes a server should have
module ServerAttributes
# @return [String] this server's name.
attr_reader :name
# @return [String] the hexadecimal ID used to identify this server's icon.
attr_reader :icon_id
# Utility function to get the URL for the icon image
# @return [String] the URL to the icon image
def icon_url
API.icon_url(@id, @icon_id)
end
end
# A server on Discord
class Server
include IDObject
include ServerAttributes
# @return [String] the region the server is on (e. g. `amsterdam`).
attr_reader :region
# @return [Member] The server owner.
attr_reader :owner
# @return [Array<Channel>] an array of all the channels (text and voice) on this server.
attr_reader :channels
# @return [Array<Role>] an array of all the roles created on this server.
attr_reader :roles
# @return [true, false] whether or not this server is large (members > 100). If it is,
# it means the members list may be inaccurate for a couple seconds after starting up the bot.
attr_reader :large
alias_method :large?, :large
# @return [Integer] the absolute number of members on this server, offline or not.
attr_reader :member_count
# @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds.
attr_reader :afk_timeout
# @return [Channel, nil] the AFK voice channel of this server, or nil if none is set
attr_reader :afk_channel
# @!visibility private
def initialize(data, bot, exists = true)
@bot = bot
@owner_id = data['owner_id'].to_i
@id = data['id'].to_i
update_data(data)
@large = data['large']
@member_count = data['member_count']
@members = {}
process_roles(data['roles'])
process_members(data['members'])
process_presences(data['presences'])
process_channels(data['channels'])
process_voice_states(data['voice_states'])
# Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet
@chunked = false
@processed_chunk_members = 0
# Only get the owner of the server actually exists (i. e. not for ServerDeleteEvent)
@owner = member(@owner_id) if exists
end
# @return [Channel] The default channel on this server (usually called #general)
def default_channel
@bot.channel(@id)
end
alias_method :general_channel, :default_channel
# Gets a role on this server based on its ID.
# @param id [Integer] The role ID to look for.
def role(id)
@roles.find { |e| e.id == id }
end
# Gets a member on this server based on user ID
# @param id [Integer] The user ID to look for
# @param request [true, false] Whether the member should be requested from Discord if it's not cached
def member(id, request = true)
id = id.resolve_id
return @members[id] if member_cached?(id)
return nil unless request
member = @bot.member(@id, id)
@members[id] = member
rescue
nil
end
# @return [Array<Member>] an array of all the members on this server.
def members
return @members.values if @chunked
@bot.debug("Members for server #{@id} not chunked yet - initiating")
@bot.request_chunks(@id)
sleep 0.05 until @chunked
@members.values
end
alias_method :users, :members
# @param include_idle [true, false] Whether to count idle members as online.
# @param include_bots [true, false] Whether to include bot accounts in the count.
# @return [Array<Member>] an array of online members on this server.
def online_members(include_idle: false, include_bots: true)
@members.values.select do |e|
((include_idle ? e.idle? : false) || e.online?) && (include_bots ? true : !e.bot_account?)
end
end
alias_method :online_users, :online_members
# @return [Array<Channel>] an array of text channels on this server
def text_channels
@channels.select(&:text?)
end
# @return [Array<Channel>] an array of voice channels on this server
def voice_channels
@channels.select(&:voice?)
end
# Adds a role to the role cache
# @note For internal use only
# @!visibility private
def add_role(role)
@roles << role
end
# Removes a role from the role cache
# @note For internal use only
# @!visibility private
def delete_role(role_id)
@roles.reject! { |r| r.id == role_id }
@members.each do |_, member|
new_roles = member.roles.reject { |r| r.id == role_id }
member.update_roles(new_roles)
end
@channels.each do |channel|
overwrites = channel.permission_overwrites.reject { |id, _| id == role_id }
channel.update_overwrites(overwrites)
end
end
# Adds a member to the member cache.
# @note For internal use only
# @!visibility private
def add_member(member)
@members[member.id] = member
@member_count += 1
end
# Removes a member from the member cache.
# @note For internal use only
# @!visibility private
def delete_member(user_id)
@members.delete(user_id)
@member_count -= 1
end
# Checks whether a member is cached
# @note For internal use only
# @!visibility private
def member_cached?(user_id)
@members.include?(user_id)
end
# Adds a member to the cache
# @note For internal use only
# @!visibility private
def cache_member(member)
@members[member.id] = member
end
# Creates a channel on this server with the given name.
# @return [Channel] the created channel.
def create_channel(name, type = 'text')
response = API.create_channel(@bot.token, @id, name, type)
Channel.new(JSON.parse(response), @bot)
end
# Creates a role on this server which can then be modified. It will be initialized (on Discord's side)
# with the regular role defaults the client uses, i. e. name is "new role", permissions are the default,
# colour is the default etc.
# @return [Role] the created role.
def create_role
response = API.create_role(@bot.token, @id)
role = Role.new(JSON.parse(response), @bot, self)
@roles << role
role
end
# @return [Array<User>] a list of banned users on this server.
def bans
users = JSON.parse(API.bans(@bot.token, @id))
users.map { |e| User.new(e['user'], @bot) }
end
# Bans a user from this server.
# @param user [User, #resolve_id] The user to ban.
# @param message_days [Integer] How many days worth of messages sent by the user should be deleted.
def ban(user, message_days = 0)
API.ban_user(@bot.token, @id, user.resolve_id, message_days)
end
# Unbans a previously banned user from this server.
# @param user [User, #resolve_id] The user to unban.
def unban(user)
API.unban_user(@bot.token, @id, user.resolve_id)
end
# Kicks a user from this server.
# @param user [User, #resolve_id] The user to kick.
def kick(user)
API.kick_user(@bot.token, @id, user.resolve_id)
end
# Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed.
# @param user [User] The user to move.
# @param channel [Channel] The voice channel to move into.
def move(user, channel)
API.move_user(@bot.token, @id, user.id, channel.id)
end
# Deletes this server. Be aware that this is permanent and impossible to undo, so be careful!
def delete
API.delete_server(@bot.token, @id)
end
# Leave the server
def leave
API.leave_server(@bot.token, @id)
end
# Transfers server ownership to another user.
# @param user [User] The user who should become the new owner.
def owner=(user)
API.transfer_ownership(@bot.token, @id, user.id)
end
# Sets the server's name.
# @param name [String] The new server name.
def name=(name)
update_server_data(name: name)
end
# Moves the server to another region. This will cause a voice interruption of at most a second.
# @param region [String] The new region the server should be in.
def region=(region)
update_server_data(region: region.to_s)
end
# Sets the server's icon.
# @param icon [String, #read] The new icon, in base64-encoded JPG format.
def icon=(icon)
if icon.respond_to? :read
icon_string = 'data:image/jpg;base64,'
icon_string += Base64.strict_encode64(icon.read)
update_server_data(icon: icon_string)
else
update_server_data(icon: icon)
end
end
# Sets the server's AFK channel.
# @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set.
def afk_channel=(afk_channel)
update_server_data(afk_channel_id: afk_channel.resolve_id)
end
# Sets the amount of time after which a user gets moved into the AFK channel.
# @param afk_timeout [Integer] The AFK timeout, in seconds.
def afk_timeout=(afk_timeout)
update_server_data(afk_timeout: afk_timeout)
end
# Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field
# @note For internal use only
# @!visibility private
def process_chunk(members)
process_members(members)
@processed_chunk_members += members.length
LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}")
# Don't bother with the rest of the method if it's not truly the last packet
return unless @processed_chunk_members == @member_count
LOGGER.debug("Finished chunking server #{@id}")
# Reset everything to normal
@chunked = true
@processed_chunk_members = 0
end
# Updates the cached data with new data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@region = new_data[:region] || new_data['region'] || @region
@icon_id = new_data[:icon] || new_data['icon'] || @icon_id
@afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout
@afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id
@afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id != 0 && (!@afk_channel || @afk_channel_id != @afk_channel.id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>"
end
private
def update_server_data(new_data)
API.update_server(@bot.token, @id,
new_data[:name] || @name,
new_data[:region] || @region,
new_data[:icon_id] || @icon_id,
new_data[:afk_channel_id] || @afk_channel_id,
new_data[:afk_timeout] || @afk_timeout)
update_data(new_data)
end
def process_roles(roles)
# Create roles
@roles = []
@roles_by_id = {}
return unless roles
roles.each do |element|
role = Role.new(element, @bot, self)
@roles << role
@roles_by_id[role.id] = role
end
end
def process_members(members)
return unless members
members.each do |element|
member = Member.new(element, self, @bot)
if @members[member.id] && @members[member.id].voice_channel
@bot.debug("Preserving voice state of member #{member.id} while chunking")
old_member = @members[member.id]
member.update_voice_state(
old_member.voice_channel,
old_member.mute,
old_member.deaf,
old_member.self_mute,
old_member.self_deaf
)
end
@members[member.id] = member
end
end
def process_presences(presences)
# Update user statuses with presence info
return unless presences
presences.each do |element|
next unless element['user']
user_id = element['user']['id'].to_i
user = @members[user_id]
if user
user.status = element['status'].to_sym
user.game = element['game'] ? element['game']['name'] : nil
end
end
end
def process_channels(channels)
@channels = []
@channels_by_id = {}
return unless channels
channels.each do |element|
channel = @bot.ensure_channel(element, self)
@channels << channel
@channels_by_id[channel.id] = channel
end
end
def process_voice_states(voice_states)
return unless voice_states
voice_states.each do |element|
user_id = element['user_id'].to_i
member = @members[user_id]
next unless member
channel_id = element['channel_id'].to_i
channel = channel_id ? @channels_by_id[channel_id] : nil
member.update_voice_state(
channel,
element['mute'],
element['deaf'],
element['self_mute'],
element['self_deaf'])
end
end
end
# A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias
# {ColorRGB} is also available.
class ColourRGB
# @return [Integer] the red part of this colour (0-255).
attr_reader :red
# @return [Integer] the green part of this colour (0-255).
attr_reader :green
# @return [Integer] the blue part of this colour (0-255).
attr_reader :blue
# @return [Integer] the colour's RGB values combined into one integer.
attr_reader :combined
# Make a new colour from the combined value.
# @param combined [Integer] The colour's RGB values combined into one integer
def initialize(combined)
@combined = combined
@red = (combined >> 16) & 0xFF
@green = (combined >> 8) & 0xFF
@blue = combined & 0xFF
end
end
# Alias for the class {ColourRGB}
ColorRGB = ColourRGB
end
Add pinned attr to Message
# frozen_string_literal: true
# These classes hold relevant Discord data, such as messages or channels.
require 'ostruct'
require 'discordrb/permissions'
require 'discordrb/api'
require 'discordrb/events/message'
require 'time'
require 'base64'
# Discordrb module
module Discordrb
# The unix timestamp Discord IDs are based on
DISCORD_EPOCH = 1_420_070_400_000
# Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID.
def self.id_compare(one_id, other)
other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other)
end
# The maximum length a Discord message can have
CHARACTER_LIMIT = 2000
# Splits a message into chunks of 2000 characters. Attempts to split by lines if possible.
# @param msg [String] The message to split.
# @return [Array<String>] the message split into chunks
def self.split_message(msg)
# If the messages is empty, return an empty array
return [] if msg.empty?
# Split the message into lines
lines = msg.lines
# Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become
# [
# [1],
# [1, 2],
# [1, 2, 3],
# [1, 2, 3, 4]
# ]
tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first }
# Join the individual elements together to get an array of strings with consecutively more lines
joined = tri.map(&:join)
# Find the largest element that is still below the character limit, or if none such element exists return the first
ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length }
# If it's still larger than the character limit (none was smaller than it) split it into slices with the length
# being the character limit, otherwise just return an array with one element
ideal_ary = (ideal.length > CHARACTER_LIMIT) ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal]
# Slice off the ideal part and strip newlines
rest = msg[ideal.length..-1].strip
# If none remains, return an empty array -> we're done
return [] unless rest
# Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array
ideal_ary + split_message(rest)
end
# Mixin for objects that have IDs
module IDObject
# @return [Integer] the ID which uniquely identifies this object across Discord.
attr_reader :id
alias_method :resolve_id, :id
# ID based comparison
def ==(other)
Discordrb.id_compare(@id, other)
end
# Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but
# shouldn't be relied on as Discord might change its algorithm at any time
# @return [Time] when this object was created at
def creation_time
# Milliseconds
ms = (@id >> 22) + DISCORD_EPOCH
Time.at(ms / 1000.0)
end
end
# Mixin for the attributes users should have
module UserAttributes
# @return [String] this user's username
attr_reader :username
alias_method :name, :username
# @return [String] this user's discriminator which is used internally to identify users with identical usernames.
attr_reader :discriminator
alias_method :discrim, :discriminator
alias_method :tag, :discriminator
alias_method :discord_tag, :discriminator
# @return [true, false] whether this user is a Discord bot account
attr_reader :bot_account
alias_method :bot_account?, :bot_account
# @return [String] the ID of this user's current avatar, can be used to generate an avatar URL.
# @see #avatar_url
attr_reader :avatar_id
# Utility function to mention users in messages
# @return [String] the mention code in the form of <@id>
def mention
"<@#{@id}>"
end
# Utility function to get Discord's distinct representation of a user, i. e. username + discriminator
# @return [String] distinct representation of user
def distinct
"#{@username}##{@discriminator}"
end
# Utility function to get a user's avatar URL.
# @return [String] the URL to the avatar image.
def avatar_url
API.avatar_url(@id, @avatar_id)
end
end
# User on Discord, including internal data like discriminators
class User
include IDObject
include UserAttributes
# @!attribute [r] status
# @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`)
attr_accessor :status
# @!attribute [r] game
# @return [String, nil] the game the user is currently playing, or `nil` if none is being played.
attr_accessor :game
def initialize(data, bot)
@bot = bot
@username = data['username']
@id = data['id'].to_i
@discriminator = data['discriminator']
@avatar_id = data['avatar']
@roles = {}
@bot_account = false
@bot_account = true if data['bot']
@status = :offline
end
# Get a user's PM channel or send them a PM
# @overload pm
# Creates a private message channel for this user or returns an existing one if it already exists
# @return [Channel] the PM channel to this user.
# @overload pm(content)
# Sends a private to this user.
# @param content [String] The content to send.
# @return [Message] the message sent to this user.
def pm(content = nil)
if content
# Recursively call pm to get the channel, then send a message to it
channel = pm
channel.send_message(content)
else
# If no message was specified, return the PM channel
@bot.private_channel(@id)
end
end
# Set the user's name
# @note for internal use only
# @!visibility private
def update_username(username)
@username = username
end
# Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this
# user's ID as a :from attribute.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block)
end
# Gets the member this user is on a server
# @param server [Server] The server to get the member for
# @return [Member] this user as a member on a particular server
def on(server)
id = server.resolve_id
@bot.server(id).member(@id)
end
# Is the user the bot?
# @return [true, false] whether this user is the bot
def current_bot?
@bot.profile.id == @id
end
[:offline, :idle, :online].each do |e|
define_method(e.to_s + '?') do
@status.to_sym == e
end
end
# The inspect method is overwritten to give more useful output
def inspect
"<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>"
end
end
# Mixin for the attributes members and private members should have
module MemberAttributes
# @return [true, false] whether this member is muted server-wide.
attr_reader :mute
alias_method :muted?, :mute
# @return [true, false] whether this member is deafened server-wide.
attr_reader :deaf
alias_method :deafened?, :deaf
# @return [true, false] whether this member has muted themselves.
attr_reader :self_mute
alias_method :self_muted?, :self_mute
# @return [true, false] whether this member has deafened themselves.
attr_reader :self_deaf
alias_method :self_deafened?, :self_deaf
# @return [Time] when this member joined the server.
attr_reader :joined_at
# @return [String, nil] the nickname this member has, or nil if it has none.
attr_reader :nick
alias_method :nickname, :nick
# @return [Array<Role>] the roles this member has.
attr_reader :roles
# @return [Server] the server this member is on.
attr_reader :server
# @return [Channel] the voice channel the user is in.
attr_reader :voice_channel
end
# Mixin to calculate resulting permissions from overrides etc.
module PermissionCalculator
# Checks whether this user can do the particular action, regardless of whether it has the permission defined,
# through for example being the server owner or having the Manage Roles permission
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @return [true, false] whether or not this user has the permission.
def permission?(action, channel = nil)
# If the member is the server owner, it irrevocably has all permissions.
return true if owner?
# First, check whether the user has Manage Roles defined.
# (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a
# Manage Permissions deny overwrite will override Manage Roles, so we can just check for
# Manage Roles once and call it a day.)
return true if defined_permission?(:manage_roles, channel)
# Otherwise, defer to defined_permission
defined_permission?(action, channel)
end
# Checks whether this user has a particular permission defined (i. e. not implicit, through for example
# Manage Roles)
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @return [true, false] whether or not this user has the permission defined.
def defined_permission?(action, channel = nil)
# Get the permission the user's roles have
role_permission = defined_role_permission?(action, channel)
# Once we have checked the role permission, we have to check the channel overrides for the
# specific user
user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable
# Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role
return role_permission unless user_specific_override
user_specific_override == :allow
end
# Define methods for querying permissions
Discordrb::Permissions::Flags.each_value do |flag|
define_method "can_#{flag}?" do |channel = nil|
permission? flag, channel
end
end
private
def defined_role_permission?(action, channel)
# For each role, check if
# (1) the channel explicitly allows or permits an action for the role and
# (2) if the user is allowed to do the action if the channel doesn't specify
@roles.reduce(false) do |can_act, role|
# Get the override defined for the role on the channel
channel_allow = permission_overwrite(action, channel, role.id)
can_act = if channel_allow
# If the channel has an override, check whether it is an allow - if yes,
# the user can act, if not, it can't
channel_allow == :allow
else
# Otherwise defer to the role
role.permissions.instance_variable_get("@#{action}") || can_act
end
can_act
end
end
def permission_overwrite(action, channel, id)
# If no overwrites are defined, or no channel is set, no overwrite will be present
return nil unless channel && channel.permission_overwrites[id]
# Otherwise, check the allow and deny objects
allow = channel.permission_overwrites[id].allow
deny = channel.permission_overwrites[id].deny
if allow.instance_variable_get("@#{action}")
:allow
elsif deny.instance_variable_get("@#{action}")
:deny
end
# If there's no variable defined, nil will implicitly be returned
end
end
# A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like
# that.
class Member < DelegateClass(User)
include MemberAttributes
# @!visibility private
def initialize(data, server, bot)
@bot = bot
@user = bot.ensure_user(data['user'])
super @user # Initialize the delegate class
# Somehow, Discord doesn't send the server ID in the standard member format...
raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil?
@server = server || bot.server(data['guild_id'].to_i)
# Initialize the roles by getting the roles from the server one-by-one
update_roles(data['roles'])
@nick = data['nick']
@deaf = data['deaf']
@mute = data['mute']
@joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil
end
# @return [true, false] whether this member is the server owner.
def owner?
@server.owner == self
end
# @param role [Role, Integer, #resolve_id] the role to check or its ID.
# @return [true, false] whether this member has the specified role.
def role?(role)
role = role.resolve_id
@roles.any? { |e| e.id == role }
end
# Adds one or more roles to this member.
# @param role [Role, Array<Role>] The role(s) to add.
def add_role(role)
role_ids = role_id_array(role)
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids + role_ids).uniq
API.update_user_roles(@bot.token, @server.id, @user.id, new_role_ids)
end
# Removes one or more roles from this member.
# @param role [Role, Array<Role>] The role(s) to remove.
def remove_role(role)
old_role_ids = @roles.map(&:id)
role_ids = role_id_array(role)
new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) }
API.update_user_roles(@bot.token, @server.id, @user.id, new_role_ids)
end
# Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage
# Nicknames for other users.
# @param nick [String, nil] The string to set the nickname to, or nil if it should be reset.
def nick=(nick)
# Discord uses the empty string to signify 'no nickname' so we convert nil into that
nick ||= ''
API.change_nickname(@bot.token, @server.id, @user.id, nick)
end
alias_method :nickname=, :nick=
# @return [String] the name the user displays as (nickname if they have one, username otherwise)
def display_name
nickname || username
end
# Update this member's roles
# @note For internal use only.
# @!visibility private
def update_roles(roles)
@roles = roles.map do |role|
role.is_a?(Role) ? role : @server.role(role.to_i)
end
end
# Update this member's nick
# @note For internal use only.
# @!visibility private
def update_nick(nick)
@nick = nick
end
# Update this member's voice state
# @note For internal use only.
# @!visibility private
def update_voice_state(channel, mute, deaf, self_mute, self_deaf)
@voice_channel = channel
@mute = mute
@deaf = deaf
@self_mute = self_mute
@self_deaf = self_deaf
end
include PermissionCalculator
# Overwriting inspect for debug purposes
def inspect
"<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>"
end
private
# Utility method to get a list of role IDs from one role or an array of roles
def role_id_array(role)
if role.is_a? Array
role.map(&:resolve_id)
else
[role.resolve_id]
end
end
end
# Recipients are members on private channels - they exist for completeness purposes, but all
# the attributes will be empty.
class Recipient < DelegateClass(User)
include MemberAttributes
# @return [Channel] the private channel this recipient is the recipient of.
attr_reader :channel
# @!visibility private
def initialize(user, channel, bot)
@bot = bot
@channel = channel
raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private?
@user = user
super @user
# Member attributes
@mute = @deaf = @self_mute = @self_deaf = false
@voice_channel = nil
@server = nil
@roles = []
@joined_at = @channel.creation_time
end
# Overwriting inspect for debug purposes
def inspect
"<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>"
end
end
# This class is a special variant of User that represents the bot's user profile (things like email addresses and the avatar).
# It can be accessed using {Bot#profile}.
class Profile < User
def initialize(data, bot, email, password)
super(data, bot)
@email = email
@password = password
end
# Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true.
# @return [true]
def current_bot?
true
end
# Sets the bot's username.
# @param username [String] The new username.
def username=(username)
update_profile_data(username: username)
end
# Sets the bot's email address. If you use this method, make sure that the login email in the script matches this
# one afterwards, so the bot doesn't have any trouble logging in in the future.
# @param email [String] The new email address.
def email=(email)
update_profile_data(email: email)
end
# Changes the bot's password. This will invalidate all tokens so you will have to relog the bot.
# @param password [String] The new password.
def password=(password)
update_profile_data(new_password: password)
end
# Changes the bot's avatar.
# @param avatar [String, #read] A JPG file to be used as the avatar, either
# something readable (e. g. File) or as a data URL.
def avatar=(avatar)
if avatar.respond_to? :read
# Set the file to binary mode if supported, so we don't get problems with Windows
avatar.binmode if avatar.respond_to?(:binmode)
avatar_string = 'data:image/jpg;base64,'
avatar_string += Base64.strict_encode64(avatar.read)
update_profile_data(avatar: avatar_string)
else
update_profile_data(avatar: avatar)
end
end
# Updates the cached profile data with the new one.
# @note For internal use only.
# @!visibility private
def update_data(new_data)
@email = new_data[:email] || @email
@password = new_data[:new_password] || @password
@username = new_data[:username] || @username
@avatar_id = new_data[:avatar_id] || @avatar_id
end
# The inspect method is overwritten to give more useful output
def inspect
"<Profile email=#{@email} user=#{super}>"
end
private
def update_profile_data(new_data)
API.update_user(@bot.token,
new_data[:email] || @email,
@password,
new_data[:username] || @username,
new_data[:avatar],
new_data[:new_password] || nil)
update_data(new_data)
end
end
# A Discord role that contains permissions and applies to certain users
class Role
include IDObject
# @return [Permissions] this role's permissions.
attr_reader :permissions
# @return [String] this role's name ("new role" if it hasn't been changed)
attr_reader :name
# @return [true, false] whether or not this role should be displayed separately from other users
attr_reader :hoist
# @return [true, false] whether this role can be mentioned using a role mention
attr_reader :mentionable
alias_method :mentionable?, :mentionable
# @return [ColourRGB] the role colour
attr_reader :colour
alias_method :color, :colour
# This class is used internally as a wrapper to a Role object that allows easy writing of permission data.
class RoleWriter
# @!visibility private
def initialize(role, token)
@role = role
@token = token
end
# Write the specified permission data to the role, without updating the permission cache
# @param bits [Integer] The packed permissions to write.
def write(bits)
@role.send(:packed=, bits, false)
end
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
@server = server
@permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token))
@name = data['name']
@id = data['id'].to_i
@hoist = data['hoist']
@mentionable = data['mentionable']
@colour = ColourRGB.new(data['color'])
end
# @return [String] a string that will mention this role, if it is mentionable.
def mention
"<@&#{@id}>"
end
# Updates the data cache from another Role object
# @note For internal use only
# @!visibility private
def update_from(other)
@permissions = other.permissions
@name = other.name
@hoist = other.hoist
@colour = other.colour
end
# Updates the data cache from a hash containing data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@hoist = new_data['hoist'] unless new_data['hoist'].nil?
@hoist = new_data[:hoist] unless new_data[:hoist].nil?
@colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour)
end
# Sets the role name to something new
# @param name [String] The name that should be set
def name=(name)
update_role_data(name: name)
end
# Changes whether or not this role is displayed at the top of the user list
# @param hoist [true, false] The value it should be changed to
def hoist=(hoist)
update_role_data(hoist: hoist)
end
# Sets the role colour to something new
# @param colour [ColourRGB] The new colour
def colour=(colour)
update_role_data(colour: colour)
end
alias_method :color=, :colour=
# Changes the internal packed permissions
# @note For internal use only
# @!visibility private
def packed=(packed, update_perms = true)
update_role_data(permissions: packed)
@permissions.bits = packed if update_perms
end
# Delets this role. This cannot be undone without recreating the role!
def delete
API.delete_role(@bot.token, @server.id, @id)
@server.delete_role(@id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>"
end
private
def update_role_data(new_data)
API.update_role(@bot.token, @server.id, @id,
new_data[:name] || @name,
(new_data[:colour] || @colour).combined,
new_data[:hoist].nil? ? false : !@hoist.nil?,
new_data[:permissions] || @permissions.bits)
update_data(new_data)
end
end
# A channel referenced by an invite. It has less data than regular channels, so it's a separate class
class InviteChannel
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [String] this channel's type (text or voice)
attr_reader :type
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@type = data['type']
end
end
# A server referenced to by an invite
class InviteServer
include IDObject
# @return [String] this server's name.
attr_reader :name
# @return [String, nil] the hash of the server's invite splash screen (for partnered servers) or nil if none is
# present
attr_reader :splash_hash
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@splash_hash = data['splash_hash']
end
end
# A Discord invite to a channel
class Invite
# @return [InviteChannel] the channel this invite references.
attr_reader :channel
# @return [InviteServer] the server this invite references.
attr_reader :server
# @return [Integer] the amount of uses left on this invite.
attr_reader :uses
# @return [User, nil] the user that made this invite. May also be nil if the user can't be determined.
attr_reader :inviter
# @return [true, false] whether or not this invite is temporary.
attr_reader :temporary
# @return [true, false] whether this invite is still valid.
attr_reader :revoked
# @return [true, false] whether this invite is in xkcd format (i. e. "Human readable" in the invite settings)
attr_reader :xkcd
# @return [String] this invite's code
attr_reader :code
alias_method :max_uses, :uses
alias_method :user, :inviter
alias_method :temporary?, :temporary
alias_method :revoked?, :revoked
alias_method :xkcd?, :xkcd
# @!visibility private
def initialize(data, bot)
@bot = bot
@channel = InviteChannel.new(data['channel'], bot)
@server = InviteServer.new(data['guild'], bot)
@uses = data['uses']
@inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil
@temporary = data['temporary']
@revoked = data['revoked']
@xkcd = data['xkcdpass']
@code = data['code']
end
# Code based comparison
def ==(other)
other.respond_to?(:code) ? (@code == other.code) : (@code == other)
end
# Deletes this invite
def delete
API.delete_invite(@bot.token, @code)
end
alias_method :revoke, :delete
# The inspect method is overwritten to give more useful output
def inspect
"<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked} xkcd=#{@xkcd}>"
end
# Creates an invite URL.
def url
"https://discord.gg/#{@code}"
end
end
# A Discord channel, including data like the topic
class Channel
# The type string that stands for a text channel
# @see Channel#type
TEXT_TYPE = 'text'.freeze
# The type string that stands for a voice channel
# @see Channel#type
VOICE_TYPE = 'voice'.freeze
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil.
attr_reader :server
# @return [String] the type of this channel (currently either 'text' or 'voice')
attr_reader :type
# @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel
attr_reader :recipient
# @return [String] the channel's topic
attr_reader :topic
# @return [Integer] the channel's position on the channel list
attr_reader :position
# This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the
# `allow` and `deny` properties which are {Permissions} objects respectively.
# @return [Hash<Integer => OpenStruct>] the channel's permission overwrites
attr_reader :permission_overwrites
# @return [true, false] whether or not this channel is a PM channel.
def private?
@server.nil?
end
# @return [String] a string that will mention the channel as a clickable link on Discord.
def mention
"<##{@id}>"
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
# data is a sometimes a Hash and othertimes an array of Hashes, you only want the last one if it's an array
data = data[-1] if data.is_a?(Array)
@id = data['id'].to_i
@type = data['type'] || TEXT_TYPE
@topic = data['topic']
@position = data['position']
@is_private = data['is_private']
if @is_private
recipient_user = bot.ensure_user(data['recipient'])
@recipient = Recipient.new(recipient_user, self, bot)
@name = @recipient.username
else
@name = data['name']
@server = if server
server
else
bot.server(data['guild_id'].to_i)
end
end
# Populate permission overwrites
@permission_overwrites = {}
return unless data['permission_overwrites']
data['permission_overwrites'].each do |element|
role_id = element['id'].to_i
deny = Permissions.new(element['deny'])
allow = Permissions.new(element['allow'])
@permission_overwrites[role_id] = OpenStruct.new
@permission_overwrites[role_id].deny = deny
@permission_overwrites[role_id].allow = allow
end
end
# @return [true, false] whether or not this channel is a text channel
def text?
@type == TEXT_TYPE
end
# @return [true, false] whether or not this channel is a voice channel
def voice?
@type == VOICE_TYPE
end
# Sends a message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
# @return [Message] the message that was sent.
def send_message(content, tts = false)
@bot.send_message(@id, content, tts, @server && @server.id)
end
# Sends multiple messages to a channel
# @param content [Array<String>] The messages to send.
def send_multiple(content)
content.each { |e| send_message(e) }
end
# Splits a message into chunks whose length is at most the Discord character limit, then sends them individually.
# Useful for sending long messages, but be wary of rate limits!
def split_send(content)
send_multiple(Discordrb.split_message(content))
end
# Sends a file to this channel. If it is an image, it will be embedded.
# @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed)
def send_file(file)
@bot.send_file(@id, file)
end
# Permanently deletes this channel
def delete
API.delete_channel(@bot.token, @id)
end
# Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations)
# @param name [String] The new name.
def name=(name)
@name = name
update_channel_data
end
# Sets this channel's topic.
# @param topic [String] The new topic.
def topic=(topic)
@topic = topic
update_channel_data
end
# Sets this channel's position in the list.
# @param position [Integer] The new position.
def position=(position)
@position = position
update_channel_data
end
# Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny
# permission sets, or change an existing one.
# @param thing [User, Role] What to define an overwrite for.
# @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a
# green checkmark on Discord)
# @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red
# cross on Discord)
# @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites
# allow = Discordrb::Permissions.new
# allow.can_mention_everyone = true
# allow.can_send_tts_messages = true
#
# deny = Discordrb::Permissions.new
# deny.can_create_instant_invite = true
#
# channel.define_overwrite(user, allow, deny)
def define_overwrite(thing, allow, deny)
allow_bits = allow.respond_to?(:bits) ? allow.bits : allow
deny_bits = deny.respond_to?(:bits) ? deny.bits : deny
if thing.is_a? User
API.update_user_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits)
elsif thing.is_a? Role
API.update_role_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits)
end
end
# Updates the cached data from another channel.
# @note For internal use only
# @!visibility private
def update_from(other)
@topic = other.topic
@name = other.name
@recipient = other.recipient
@permission_overwrites = other.permission_overwrites
end
# The list of users currently in this channel. This is mostly useful for a voice channel, for a text channel it will
# just return the users on the server that are online.
# @return [Array<Member>] the users in this channel
def users
if @type == 'text'
@server.members.select { |u| u.status != :offline }
else
@server.members.select do |user|
user.voice_channel.id == @id if user.voice_channel
end
end
end
# Retrieves some of this channel's message history.
# @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher
# than 100 it will be treated as 100 on Discord's side.
# @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should
# start at the current message.
# @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start
# as soon as possible with the specified amount.
# @return [Array<Message>] the retrieved messages.
def history(amount, before_id = nil, after_id = nil)
logs = API.channel_log(@bot.token, @id, amount, before_id, after_id)
JSON.parse(logs).map { |message| Message.new(message, @bot) }
end
# Requests all pinned messages of a channel.
# @return [Array<Message>] the received messages.
def pins
msgs = API.pins(@bot.token, @id)
JSON.parse(msgs).map { |msg| Message.new(msg, @bot) }
end
# Delete the last N messages on this channel.
# @param amount [Integer] How many messages to delete. Must be a value between 2 and 100 (Discord limitation)
# @raise [ArgumentError] if the amount of messages is not a value between 2 and 100
def prune(amount)
raise ArgumentError, 'Can only prune between 2 and 100 messages!' unless amount.between?(2, 100)
messages = history(amount).map(&:id)
API.bulk_delete(@bot.token, @id, messages)
end
# Updates the cached permission overwrites
# @note For internal use only
# @!visibility private
def update_overwrites(overwrites)
@permission_overwrites = overwrites
end
# Add an {Await} for a message in this channel. This is identical in functionality to adding a
# {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block)
end
# Creates a new invite to this channel.
# @param max_age [Integer] How many seconds this invite should last.
# @param max_uses [Integer] How many times this invite should be able to be used.
# @param temporary [true, false] Whether membership should be temporary (kicked after going offline).
# @param xkcd [true, false] Whether or not the invite should be human-readable.
# @return [Invite] the created invite.
def make_invite(max_age = 0, max_uses = 0, temporary = false, xkcd = false)
response = API.create_invite(@bot.token, @id, max_age, max_uses, temporary, xkcd)
Invite.new(JSON.parse(response), @bot)
end
# Starts typing, which displays the typing indicator on the client for five seconds.
# If you want to keep typing you'll have to resend this every five seconds. (An abstraction
# for this will eventually be coming)
def start_typing
API.start_typing(@bot.token, @id)
end
alias_method :send, :send_message
alias_method :message, :send_message
alias_method :invite, :make_invite
# The inspect method is overwritten to give more useful output
def inspect
"<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>"
end
private
def update_channel_data
API.update_channel(@bot.token, @id, @name, @topic, @position)
end
end
# An attachment to a message
class Attachment
include IDObject
# @return [Message] the message this attachment belongs to.
attr_reader :message
# @return [String] the CDN URL this attachment can be downloaded at.
attr_reader :url
# @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to
# do with CDNs
attr_reader :proxy_url
# @return [String] the attachment's filename.
attr_reader :filename
# @return [Integer] the attachment's file size in bytes.
attr_reader :size
# @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image.
attr_reader :width
# @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image.
attr_reader :height
# @!visibility private
def initialize(data, message, bot)
@bot = bot
@message = message
@url = data['url']
@proxy_url = data['proxy_url']
@filename = data['filename']
@size = data['size']
@width = data['width']
@height = data['height']
end
# @return [true, false] whether this file is an image file.
def image?
!(@width.nil? || @height.nil?)
end
end
# A message on Discord that was sent to a text channel
class Message
include IDObject
# @return [String] the content of this message.
attr_reader :content
# @return [Member] the user that sent this message.
attr_reader :author
# @return [Channel] the channel in which this message was sent.
attr_reader :channel
# @return [Time] the timestamp at which this message was sent.
attr_reader :timestamp
# @return [Array<User>] the users that were mentioned in this message.
attr_reader :mentions
# @return [Array<Role>] the roles that were mentioned in this message.
attr_reader :role_mentions
# @return [Array<Attachment>] the files attached to this message.
attr_reader :attachments
# @return [true, false] whether themesage is pinned or not.
attr_reader :pinned
alias_method :user, :author
alias_method :text, :content
alias_method :to_s, :content
# @!visibility private
def initialize(data, bot)
@bot = bot
@content = data['content']
@channel = bot.channel(data['channel_id'].to_i)
@pinned = data['pinned']
@author = if data['author']
if @channel.private?
# Turn the message user into a recipient - we can't use the channel recipient
# directly because the bot may also send messages to the channel
Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot)
else
member = @channel.server.member(data['author']['id'].to_i, false)
Discordrb::LOGGER.warn("Member with ID #{data['author']['id']} not cached even though it should be.") unless member
member
end
end
@timestamp = Time.parse(data['timestamp']) if data['timestamp']
@id = data['id'].to_i
@mentions = []
data['mentions'].each do |element|
@mentions << bot.ensure_user(element)
end if data['mentions']
@role_mentions = []
# Role mentions can only happen on public servers so make sure we only parse them there
unless @channel.private?
data['mention_roles'].each do |element|
@role_mentions << @channel.server.role(element.to_i)
end if data['mention_roles']
end
@attachments = []
@attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } if data['attachments']
end
# Replies to this message with the specified content.
# @see Channel#send_message
def reply(content)
@channel.send_message(content)
end
# Edits this message to have the specified content instead.
# @param new_content [String] the new content the message should have.
# @return [Message] the resulting message.
def edit(new_content)
response = API.edit_message(@bot.token, @channel.id, @id, new_content)
Message.new(JSON.parse(response), @bot)
end
# Deletes this message.
def delete
API.delete_message(@bot.token, @channel.id, @id)
nil
end
# Pins this message
def pin
API.pin_message(@bot.token, @channel.id, @id)
@pinned = true
nil
end
# Unpins this message
def unpin
API.unpin_message(@bot.token, @channel.id, @id)
@pinned = false
nil
end
# Add an {Await} for a message with the same user and channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block)
end
# @return [true, false] whether this message was sent by the current {Bot}.
def from_bot?
@author && @author.current_bot?
end
# The inspect method is overwritten to give more useful output
def inspect
"<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>"
end
end
# Basic attributes a server should have
module ServerAttributes
# @return [String] this server's name.
attr_reader :name
# @return [String] the hexadecimal ID used to identify this server's icon.
attr_reader :icon_id
# Utility function to get the URL for the icon image
# @return [String] the URL to the icon image
def icon_url
API.icon_url(@id, @icon_id)
end
end
# A server on Discord
class Server
include IDObject
include ServerAttributes
# @return [String] the region the server is on (e. g. `amsterdam`).
attr_reader :region
# @return [Member] The server owner.
attr_reader :owner
# @return [Array<Channel>] an array of all the channels (text and voice) on this server.
attr_reader :channels
# @return [Array<Role>] an array of all the roles created on this server.
attr_reader :roles
# @return [true, false] whether or not this server is large (members > 100). If it is,
# it means the members list may be inaccurate for a couple seconds after starting up the bot.
attr_reader :large
alias_method :large?, :large
# @return [Integer] the absolute number of members on this server, offline or not.
attr_reader :member_count
# @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds.
attr_reader :afk_timeout
# @return [Channel, nil] the AFK voice channel of this server, or nil if none is set
attr_reader :afk_channel
# @!visibility private
def initialize(data, bot, exists = true)
@bot = bot
@owner_id = data['owner_id'].to_i
@id = data['id'].to_i
update_data(data)
@large = data['large']
@member_count = data['member_count']
@members = {}
process_roles(data['roles'])
process_members(data['members'])
process_presences(data['presences'])
process_channels(data['channels'])
process_voice_states(data['voice_states'])
# Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet
@chunked = false
@processed_chunk_members = 0
# Only get the owner of the server actually exists (i. e. not for ServerDeleteEvent)
@owner = member(@owner_id) if exists
end
# @return [Channel] The default channel on this server (usually called #general)
def default_channel
@bot.channel(@id)
end
alias_method :general_channel, :default_channel
# Gets a role on this server based on its ID.
# @param id [Integer] The role ID to look for.
def role(id)
@roles.find { |e| e.id == id }
end
# Gets a member on this server based on user ID
# @param id [Integer] The user ID to look for
# @param request [true, false] Whether the member should be requested from Discord if it's not cached
def member(id, request = true)
id = id.resolve_id
return @members[id] if member_cached?(id)
return nil unless request
member = @bot.member(@id, id)
@members[id] = member
rescue
nil
end
# @return [Array<Member>] an array of all the members on this server.
def members
return @members.values if @chunked
@bot.debug("Members for server #{@id} not chunked yet - initiating")
@bot.request_chunks(@id)
sleep 0.05 until @chunked
@members.values
end
alias_method :users, :members
# @param include_idle [true, false] Whether to count idle members as online.
# @param include_bots [true, false] Whether to include bot accounts in the count.
# @return [Array<Member>] an array of online members on this server.
def online_members(include_idle: false, include_bots: true)
@members.values.select do |e|
((include_idle ? e.idle? : false) || e.online?) && (include_bots ? true : !e.bot_account?)
end
end
alias_method :online_users, :online_members
# @return [Array<Channel>] an array of text channels on this server
def text_channels
@channels.select(&:text?)
end
# @return [Array<Channel>] an array of voice channels on this server
def voice_channels
@channels.select(&:voice?)
end
# Adds a role to the role cache
# @note For internal use only
# @!visibility private
def add_role(role)
@roles << role
end
# Removes a role from the role cache
# @note For internal use only
# @!visibility private
def delete_role(role_id)
@roles.reject! { |r| r.id == role_id }
@members.each do |_, member|
new_roles = member.roles.reject { |r| r.id == role_id }
member.update_roles(new_roles)
end
@channels.each do |channel|
overwrites = channel.permission_overwrites.reject { |id, _| id == role_id }
channel.update_overwrites(overwrites)
end
end
# Adds a member to the member cache.
# @note For internal use only
# @!visibility private
def add_member(member)
@members[member.id] = member
@member_count += 1
end
# Removes a member from the member cache.
# @note For internal use only
# @!visibility private
def delete_member(user_id)
@members.delete(user_id)
@member_count -= 1
end
# Checks whether a member is cached
# @note For internal use only
# @!visibility private
def member_cached?(user_id)
@members.include?(user_id)
end
# Adds a member to the cache
# @note For internal use only
# @!visibility private
def cache_member(member)
@members[member.id] = member
end
# Creates a channel on this server with the given name.
# @return [Channel] the created channel.
def create_channel(name, type = 'text')
response = API.create_channel(@bot.token, @id, name, type)
Channel.new(JSON.parse(response), @bot)
end
# Creates a role on this server which can then be modified. It will be initialized (on Discord's side)
# with the regular role defaults the client uses, i. e. name is "new role", permissions are the default,
# colour is the default etc.
# @return [Role] the created role.
def create_role
response = API.create_role(@bot.token, @id)
role = Role.new(JSON.parse(response), @bot, self)
@roles << role
role
end
# @return [Array<User>] a list of banned users on this server.
def bans
users = JSON.parse(API.bans(@bot.token, @id))
users.map { |e| User.new(e['user'], @bot) }
end
# Bans a user from this server.
# @param user [User, #resolve_id] The user to ban.
# @param message_days [Integer] How many days worth of messages sent by the user should be deleted.
def ban(user, message_days = 0)
API.ban_user(@bot.token, @id, user.resolve_id, message_days)
end
# Unbans a previously banned user from this server.
# @param user [User, #resolve_id] The user to unban.
def unban(user)
API.unban_user(@bot.token, @id, user.resolve_id)
end
# Kicks a user from this server.
# @param user [User, #resolve_id] The user to kick.
def kick(user)
API.kick_user(@bot.token, @id, user.resolve_id)
end
# Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed.
# @param user [User] The user to move.
# @param channel [Channel] The voice channel to move into.
def move(user, channel)
API.move_user(@bot.token, @id, user.id, channel.id)
end
# Deletes this server. Be aware that this is permanent and impossible to undo, so be careful!
def delete
API.delete_server(@bot.token, @id)
end
# Leave the server
def leave
API.leave_server(@bot.token, @id)
end
# Transfers server ownership to another user.
# @param user [User] The user who should become the new owner.
def owner=(user)
API.transfer_ownership(@bot.token, @id, user.id)
end
# Sets the server's name.
# @param name [String] The new server name.
def name=(name)
update_server_data(name: name)
end
# Moves the server to another region. This will cause a voice interruption of at most a second.
# @param region [String] The new region the server should be in.
def region=(region)
update_server_data(region: region.to_s)
end
# Sets the server's icon.
# @param icon [String, #read] The new icon, in base64-encoded JPG format.
def icon=(icon)
if icon.respond_to? :read
icon_string = 'data:image/jpg;base64,'
icon_string += Base64.strict_encode64(icon.read)
update_server_data(icon: icon_string)
else
update_server_data(icon: icon)
end
end
# Sets the server's AFK channel.
# @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set.
def afk_channel=(afk_channel)
update_server_data(afk_channel_id: afk_channel.resolve_id)
end
# Sets the amount of time after which a user gets moved into the AFK channel.
# @param afk_timeout [Integer] The AFK timeout, in seconds.
def afk_timeout=(afk_timeout)
update_server_data(afk_timeout: afk_timeout)
end
# Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field
# @note For internal use only
# @!visibility private
def process_chunk(members)
process_members(members)
@processed_chunk_members += members.length
LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}")
# Don't bother with the rest of the method if it's not truly the last packet
return unless @processed_chunk_members == @member_count
LOGGER.debug("Finished chunking server #{@id}")
# Reset everything to normal
@chunked = true
@processed_chunk_members = 0
end
# Updates the cached data with new data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@region = new_data[:region] || new_data['region'] || @region
@icon_id = new_data[:icon] || new_data['icon'] || @icon_id
@afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout
@afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id
@afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id != 0 && (!@afk_channel || @afk_channel_id != @afk_channel.id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>"
end
private
def update_server_data(new_data)
API.update_server(@bot.token, @id,
new_data[:name] || @name,
new_data[:region] || @region,
new_data[:icon_id] || @icon_id,
new_data[:afk_channel_id] || @afk_channel_id,
new_data[:afk_timeout] || @afk_timeout)
update_data(new_data)
end
def process_roles(roles)
# Create roles
@roles = []
@roles_by_id = {}
return unless roles
roles.each do |element|
role = Role.new(element, @bot, self)
@roles << role
@roles_by_id[role.id] = role
end
end
def process_members(members)
return unless members
members.each do |element|
member = Member.new(element, self, @bot)
if @members[member.id] && @members[member.id].voice_channel
@bot.debug("Preserving voice state of member #{member.id} while chunking")
old_member = @members[member.id]
member.update_voice_state(
old_member.voice_channel,
old_member.mute,
old_member.deaf,
old_member.self_mute,
old_member.self_deaf
)
end
@members[member.id] = member
end
end
def process_presences(presences)
# Update user statuses with presence info
return unless presences
presences.each do |element|
next unless element['user']
user_id = element['user']['id'].to_i
user = @members[user_id]
if user
user.status = element['status'].to_sym
user.game = element['game'] ? element['game']['name'] : nil
end
end
end
def process_channels(channels)
@channels = []
@channels_by_id = {}
return unless channels
channels.each do |element|
channel = @bot.ensure_channel(element, self)
@channels << channel
@channels_by_id[channel.id] = channel
end
end
def process_voice_states(voice_states)
return unless voice_states
voice_states.each do |element|
user_id = element['user_id'].to_i
member = @members[user_id]
next unless member
channel_id = element['channel_id'].to_i
channel = channel_id ? @channels_by_id[channel_id] : nil
member.update_voice_state(
channel,
element['mute'],
element['deaf'],
element['self_mute'],
element['self_deaf'])
end
end
end
# A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias
# {ColorRGB} is also available.
class ColourRGB
# @return [Integer] the red part of this colour (0-255).
attr_reader :red
# @return [Integer] the green part of this colour (0-255).
attr_reader :green
# @return [Integer] the blue part of this colour (0-255).
attr_reader :blue
# @return [Integer] the colour's RGB values combined into one integer.
attr_reader :combined
# Make a new colour from the combined value.
# @param combined [Integer] The colour's RGB values combined into one integer
def initialize(combined)
@combined = combined
@red = (combined >> 16) & 0xFF
@green = (combined >> 8) & 0xFF
@blue = combined & 0xFF
end
end
# Alias for the class {ColourRGB}
ColorRGB = ColourRGB
end
|
# frozen_string_literal: true
# These classes hold relevant Discord data, such as messages or channels.
require 'ostruct'
require 'discordrb/permissions'
require 'discordrb/api'
require 'discordrb/events/message'
require 'time'
require 'base64'
# Discordrb module
module Discordrb
# The unix timestamp Discord IDs are based on
DISCORD_EPOCH = 1_420_070_400_000
# Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID.
def self.id_compare(one_id, other)
other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other)
end
# The maximum length a Discord message can have
CHARACTER_LIMIT = 2000
# Splits a message into chunks of 2000 characters. Attempts to split by lines if possible.
# @param msg [String] The message to split.
# @return [Array<String>] the message split into chunks
def self.split_message(msg)
# If the messages is empty, return an empty array
return [] if msg.empty?
# Split the message into lines
lines = msg.lines
# Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become
# [
# [1],
# [1, 2],
# [1, 2, 3],
# [1, 2, 3, 4]
# ]
tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first }
# Join the individual elements together to get an array of strings with consecutively more lines
joined = tri.map(&:join)
# Find the largest element that is still below the character limit, or if none such element exists return the first
ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length }
# If it's still larger than the character limit (none was smaller than it) split it into slices with the length
# being the character limit, otherwise just return an array with one element
ideal_ary = ideal.length > CHARACTER_LIMIT ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal]
# Slice off the ideal part and strip newlines
rest = msg[ideal.length..-1].strip
# If none remains, return an empty array -> we're done
return [] unless rest
# Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array
ideal_ary + split_message(rest)
end
# Mixin for objects that have IDs
module IDObject
# @return [Integer] the ID which uniquely identifies this object across Discord.
attr_reader :id
alias_method :resolve_id, :id
# ID based comparison
def ==(other)
Discordrb.id_compare(@id, other)
end
# Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but
# shouldn't be relied on as Discord might change its algorithm at any time
# @return [Time] when this object was created at
def creation_time
# Milliseconds
ms = (@id >> 22) + DISCORD_EPOCH
Time.at(ms / 1000.0)
end
end
# Mixin for the attributes users should have
module UserAttributes
# @return [String] this user's username
attr_reader :username
alias_method :name, :username
# @return [String] this user's discriminator which is used internally to identify users with identical usernames.
attr_reader :discriminator
alias_method :discrim, :discriminator
alias_method :tag, :discriminator
alias_method :discord_tag, :discriminator
# @return [true, false] whether this user is a Discord bot account
attr_reader :bot_account
alias_method :bot_account?, :bot_account
# @return [String] the ID of this user's current avatar, can be used to generate an avatar URL.
# @see #avatar_url
attr_reader :avatar_id
# Utility function to mention users in messages
# @return [String] the mention code in the form of <@id>
def mention
"<@#{@id}>"
end
# Utility function to get Discord's distinct representation of a user, i. e. username + discriminator
# @return [String] distinct representation of user
def distinct
"#{@username}##{@discriminator}"
end
# Utility function to get a user's avatar URL.
# @return [String] the URL to the avatar image.
def avatar_url
API.avatar_url(@id, @avatar_id)
end
end
# User on Discord, including internal data like discriminators
class User
include IDObject
include UserAttributes
# @!attribute [r] status
# @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`)
attr_accessor :status
# @!attribute [r] game
# @return [String, nil] the game the user is currently playing, or `nil` if none is being played.
attr_accessor :game
def initialize(data, bot)
@bot = bot
@username = data['username']
@id = data['id'].to_i
@discriminator = data['discriminator']
@avatar_id = data['avatar']
@roles = {}
@bot_account = false
@bot_account = true if data['bot']
@status = :offline
end
# Get a user's PM channel or send them a PM
# @overload pm
# Creates a private message channel for this user or returns an existing one if it already exists
# @return [Channel] the PM channel to this user.
# @overload pm(content)
# Sends a private to this user.
# @param content [String] The content to send.
# @return [Message] the message sent to this user.
def pm(content = nil)
if content
# Recursively call pm to get the channel, then send a message to it
channel = pm
channel.send_message(content)
else
# If no message was specified, return the PM channel
@bot.private_channel(@id)
end
end
alias_method :dm, :pm
# Send the user a file.
# @param file [File] The file to send to the user
# @param caption [String] The caption of the file being sent
# @return [Message] the message sent to this user.
def send_file(file, caption = nil)
pm.send_file(file, caption: caption)
end
# Set the user's name
# @note for internal use only
# @!visibility private
def update_username(username)
@username = username
end
# Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this
# user's ID as a :from attribute.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block)
end
# Gets the member this user is on a server
# @param server [Server] The server to get the member for
# @return [Member] this user as a member on a particular server
def on(server)
id = server.resolve_id
@bot.server(id).member(@id)
end
# Is the user the bot?
# @return [true, false] whether this user is the bot
def current_bot?
@bot.profile.id == @id
end
[:offline, :idle, :online].each do |e|
define_method(e.to_s + '?') do
@status.to_sym == e
end
end
# The inspect method is overwritten to give more useful output
def inspect
"<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>"
end
end
# Mixin for the attributes members and private members should have
module MemberAttributes
# @return [Time] when this member joined the server.
attr_reader :joined_at
# @return [String, nil] the nickname this member has, or nil if it has none.
attr_reader :nick
alias_method :nickname, :nick
# @return [Array<Role>] the roles this member has.
attr_reader :roles
# @return [Server] the server this member is on.
attr_reader :server
end
# Mixin to calculate resulting permissions from overrides etc.
module PermissionCalculator
# Checks whether this user can do the particular action, regardless of whether it has the permission defined,
# through for example being the server owner or having the Manage Roles permission
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @return [true, false] whether or not this user has the permission.
def permission?(action, channel = nil)
# If the member is the server owner, it irrevocably has all permissions.
return true if owner?
# First, check whether the user has Manage Roles defined.
# (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a
# Manage Permissions deny overwrite will override Manage Roles, so we can just check for
# Manage Roles once and call it a day.)
return true if defined_permission?(:administrator, channel)
# Otherwise, defer to defined_permission
defined_permission?(action, channel)
end
# Checks whether this user has a particular permission defined (i. e. not implicit, through for example
# Manage Roles)
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @return [true, false] whether or not this user has the permission defined.
def defined_permission?(action, channel = nil)
# Get the permission the user's roles have
role_permission = defined_role_permission?(action, channel)
# Once we have checked the role permission, we have to check the channel overrides for the
# specific user
user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable
# Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role
return role_permission unless user_specific_override
user_specific_override == :allow
end
# Define methods for querying permissions
Discordrb::Permissions::Flags.each_value do |flag|
define_method "can_#{flag}?" do |channel = nil|
permission? flag, channel
end
end
alias_method :can_administrate?, :can_administrator?
private
def defined_role_permission?(action, channel)
# For each role, check if
# (1) the channel explicitly allows or permits an action for the role and
# (2) if the user is allowed to do the action if the channel doesn't specify
@roles.reduce(false) do |can_act, role|
# Get the override defined for the role on the channel
channel_allow = permission_overwrite(action, channel, role.id)
can_act = if channel_allow
# If the channel has an override, check whether it is an allow - if yes,
# the user can act, if not, it can't
channel_allow == :allow
else
# Otherwise defer to the role
role.permissions.instance_variable_get("@#{action}") || can_act
end
can_act
end
end
def permission_overwrite(action, channel, id)
# If no overwrites are defined, or no channel is set, no overwrite will be present
return nil unless channel && channel.permission_overwrites[id]
# Otherwise, check the allow and deny objects
allow = channel.permission_overwrites[id].allow
deny = channel.permission_overwrites[id].deny
if allow.instance_variable_get("@#{action}")
:allow
elsif deny.instance_variable_get("@#{action}")
:deny
end
# If there's no variable defined, nil will implicitly be returned
end
end
# A voice state represents the state of a member's connection to a voice channel. It includes data like the voice
# channel the member is connected to and mute/deaf flags.
class VoiceState
# @return [Integer] the ID of the user whose voice state is represented by this object.
attr_reader :user_id
# @return [true, false] whether this voice state's member is muted server-wide.
attr_reader :mute
# @return [true, false] whether this voice state's member is deafened server-wide.
attr_reader :deaf
# @return [true, false] whether this voice state's member has muted themselves.
attr_reader :self_mute
# @return [true, false] whether this voice state's member has deafened themselves.
attr_reader :self_deaf
# @return [Channel] the voice channel this voice state's member is in.
attr_reader :voice_channel
# @!visibility private
def initialize(user_id)
@user_id = user_id
end
# Update this voice state with new data from Discord
# @note For internal use only.
# @!visibility private
def update(channel, mute, deaf, self_mute, self_deaf)
@voice_channel = channel
@mute = mute
@deaf = deaf
@self_mute = self_mute
@self_deaf = self_deaf
end
end
# A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like
# that.
class Member < DelegateClass(User)
# @return [true, false] whether this member is muted server-wide.
def mute
voice_state_attribute(:mute)
end
# @return [true, false] whether this member is deafened server-wide.
def deaf
voice_state_attribute(:deaf)
end
# @return [true, false] whether this member has muted themselves.
def self_mute
voice_state_attribute(:self_mute)
end
# @return [true, false] whether this member has deafened themselves.
def self_deaf
voice_state_attribute(:self_deaf)
end
# @return [Channel] the voice channel this member is in.
def voice_channel
voice_state_attribute(:voice_channel)
end
alias_method :muted?, :mute
alias_method :deafened?, :deaf
alias_method :self_muted?, :self_mute
alias_method :self_deafened?, :self_deaf
include MemberAttributes
# @!visibility private
def initialize(data, server, bot)
@bot = bot
@user = bot.ensure_user(data['user'])
super @user # Initialize the delegate class
# Somehow, Discord doesn't send the server ID in the standard member format...
raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil?
@server = server || bot.server(data['guild_id'].to_i)
# Initialize the roles by getting the roles from the server one-by-one
update_roles(data['roles'])
@nick = data['nick']
@joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil
end
# @return [true, false] whether this member is the server owner.
def owner?
@server.owner == self
end
# @param role [Role, Integer, #resolve_id] the role to check or its ID.
# @return [true, false] whether this member has the specified role.
def role?(role)
role = role.resolve_id
@roles.any? { |e| e.id == role }
end
# Adds one or more roles to this member.
# @param role [Role, Array<Role>] The role(s) to add.
def add_role(role)
role_ids = role_id_array(role)
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids + role_ids).uniq
API.update_user_roles(@bot.token, @server.id, @user.id, new_role_ids)
end
# Removes one or more roles from this member.
# @param role [Role, Array<Role>] The role(s) to remove.
def remove_role(role)
old_role_ids = @roles.map(&:id)
role_ids = role_id_array(role)
new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) }
API.update_user_roles(@bot.token, @server.id, @user.id, new_role_ids)
end
# Server deafens this member.
def server_deafen
API.update_user_deafen(@bot.token, @server.id, @user.id, true)
end
# Server undeafens this member.
def server_undeafen
API.update_user_deafen(@bot.token, @server.id, @user.id, false)
end
# Server mutes this member.
def server_mute
API.update_user_mute(@bot.token, @server.id, @user.id, true)
end
# Server unmutes this member.
def server_unmute
API.update_user_mute(@bot.token, @server.id, @user.id, false)
end
# Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage
# Nicknames for other users.
# @param nick [String, nil] The string to set the nickname to, or nil if it should be reset.
def nick=(nick)
# Discord uses the empty string to signify 'no nickname' so we convert nil into that
nick ||= ''
if @user.current_bot?
API.change_own_nickname(@bot.token, @server.id, nick)
else
API.change_nickname(@bot.token, @server.id, @user.id, nick)
end
end
alias_method :nickname=, :nick=
# @return [String] the name the user displays as (nickname if they have one, username otherwise)
def display_name
nickname || username
end
# Update this member's roles
# @note For internal use only.
# @!visibility private
def update_roles(roles)
@roles = roles.map do |role|
role.is_a?(Role) ? role : @server.role(role.to_i)
end
end
# Update this member's nick
# @note For internal use only.
# @!visibility private
def update_nick(nick)
@nick = nick
end
include PermissionCalculator
# Overwriting inspect for debug purposes
def inspect
"<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>"
end
private
# Utility method to get a list of role IDs from one role or an array of roles
def role_id_array(role)
if role.is_a? Array
role.map(&:resolve_id)
else
[role.resolve_id]
end
end
# Utility method to get data out of this member's voice state
def voice_state_attribute(name)
voice_state = @server.voice_states[@user.id]
voice_state.send name if voice_state
end
end
# Recipients are members on private channels - they exist for completeness purposes, but all
# the attributes will be empty.
class Recipient < DelegateClass(User)
include MemberAttributes
# @return [Channel] the private channel this recipient is the recipient of.
attr_reader :channel
# @!visibility private
def initialize(user, channel, bot)
@bot = bot
@channel = channel
raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private?
@user = user
super @user
# Member attributes
@mute = @deaf = @self_mute = @self_deaf = false
@voice_channel = nil
@server = nil
@roles = []
@joined_at = @channel.creation_time
end
# Overwriting inspect for debug purposes
def inspect
"<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>"
end
end
# This class is a special variant of User that represents the bot's user profile (things like email addresses and the avatar).
# It can be accessed using {Bot#profile}.
class Profile < User
def initialize(data, bot, email, password)
super(data, bot)
@email = email
@password = password
end
# Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true.
# @return [true]
def current_bot?
true
end
# Sets the bot's username.
# @param username [String] The new username.
def username=(username)
update_profile_data(username: username)
end
alias_method :name=, :username=
# Sets the bot's email address. If you use this method, make sure that the login email in the script matches this
# one afterwards, so the bot doesn't have any trouble logging in in the future.
# @param email [String] The new email address.
def email=(email)
update_profile_data(email: email)
end
# Changes the bot's password. This will invalidate all tokens so you will have to relog the bot.
# @param password [String] The new password.
def password=(password)
update_profile_data(new_password: password)
end
# Changes the bot's avatar.
# @param avatar [String, #read] A JPG file to be used as the avatar, either
# something readable (e. g. File) or as a data URL.
def avatar=(avatar)
if avatar.respond_to? :read
# Set the file to binary mode if supported, so we don't get problems with Windows
avatar.binmode if avatar.respond_to?(:binmode)
avatar_string = 'data:image/jpg;base64,'
avatar_string += Base64.strict_encode64(avatar.read)
update_profile_data(avatar: avatar_string)
else
update_profile_data(avatar: avatar)
end
end
# Updates the cached profile data with the new one.
# @note For internal use only.
# @!visibility private
def update_data(new_data)
@email = new_data[:email] || @email
@password = new_data[:new_password] || @password
@username = new_data[:username] || @username
@avatar_id = new_data[:avatar_id] || @avatar_id
end
# The inspect method is overwritten to give more useful output
def inspect
"<Profile email=#{@email} user=#{super}>"
end
private
def update_profile_data(new_data)
API.update_user(@bot.token,
new_data[:email] || @email,
@password,
new_data[:username] || @username,
new_data[:avatar],
new_data[:new_password] || nil)
update_data(new_data)
end
end
# A Discord role that contains permissions and applies to certain users
class Role
include IDObject
# @return [Permissions] this role's permissions.
attr_reader :permissions
# @return [String] this role's name ("new role" if it hasn't been changed)
attr_reader :name
# @return [true, false] whether or not this role should be displayed separately from other users
attr_reader :hoist
# @return [true, false] whether this role can be mentioned using a role mention
attr_reader :mentionable
alias_method :mentionable?, :mentionable
# @return [ColourRGB] the role colour
attr_reader :colour
alias_method :color, :colour
# This class is used internally as a wrapper to a Role object that allows easy writing of permission data.
class RoleWriter
# @!visibility private
def initialize(role, token)
@role = role
@token = token
end
# Write the specified permission data to the role, without updating the permission cache
# @param bits [Integer] The packed permissions to write.
def write(bits)
@role.send(:packed=, bits, false)
end
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
@server = server
@permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token))
@name = data['name']
@id = data['id'].to_i
@position = data['position']
@hoist = data['hoist']
@mentionable = data['mentionable']
@colour = ColourRGB.new(data['color'])
end
# @return [String] a string that will mention this role, if it is mentionable.
def mention
"<@&#{@id}>"
end
# @return [Array<Member>] an array of members who have this role.
# @note This requests a member chunk if it hasn't for the server before, which may be slow initially
def members
@server.members.select { |m| m.role? role }
end
alias_method :users, :members
# Updates the data cache from another Role object
# @note For internal use only
# @!visibility private
def update_from(other)
@permissions = other.permissions
@name = other.name
@hoist = other.hoist
@colour = other.colour
end
# Updates the data cache from a hash containing data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@hoist = new_data['hoist'] unless new_data['hoist'].nil?
@hoist = new_data[:hoist] unless new_data[:hoist].nil?
@colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour)
end
# Sets the role name to something new
# @param name [String] The name that should be set
def name=(name)
update_role_data(name: name)
end
# Changes whether or not this role is displayed at the top of the user list
# @param hoist [true, false] The value it should be changed to
def hoist=(hoist)
update_role_data(hoist: hoist)
end
# Changes whether or not this role can be mentioned
# @param mentionable [true, false] The value it should be changed to
def mentionable=(mentionable)
update_role_data(mentionable: mentionable)
end
# Sets the role colour to something new
# @param colour [ColourRGB] The new colour
def colour=(colour)
update_role_data(colour: colour)
end
alias_method :color=, :colour=
# Changes this role's permissions to a fixed bitfield. This allows setting multiple permissions at once with just
# one API call.
#
# Information on how this bitfield is structured can be found at
# https://discordapp.com/developers/docs/topics/permissions.
# @example Remove all permissions from a role
# role.packed = 0
# @param packed [Integer] A bitfield with the desired permissions value.
# @param update_perms [true, false] Whether the internal data should also be updated. This should always be true
# when calling externally.
def packed=(packed, update_perms = true)
update_role_data(permissions: packed)
@permissions.bits = packed if update_perms
end
# Delets this role. This cannot be undone without recreating the role!
def delete
API.delete_role(@bot.token, @server.id, @id)
@server.delete_role(@id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>"
end
private
def update_role_data(new_data)
API.update_role(@bot.token, @server.id, @id,
new_data[:name] || @name,
(new_data[:colour] || @colour).combined,
new_data[:hoist].nil? ? @hoist : new_data[:hoist],
new_data[:mentionable].nil? ? @mentionable : new_data[:mentionable],
new_data[:permissions] || @permissions.bits)
update_data(new_data)
end
end
# A channel referenced by an invite. It has less data than regular channels, so it's a separate class
class InviteChannel
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [String] this channel's type (text or voice)
attr_reader :type
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@type = data['type']
end
end
# A server referenced to by an invite
class InviteServer
include IDObject
# @return [String] this server's name.
attr_reader :name
# @return [String, nil] the hash of the server's invite splash screen (for partnered servers) or nil if none is
# present
attr_reader :splash_hash
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@splash_hash = data['splash_hash']
end
end
# A Discord invite to a channel
class Invite
# @return [InviteChannel] the channel this invite references.
attr_reader :channel
# @return [InviteServer] the server this invite references.
attr_reader :server
# @return [Integer] the amount of uses left on this invite.
attr_reader :uses
# @return [User, nil] the user that made this invite. May also be nil if the user can't be determined.
attr_reader :inviter
# @return [true, false] whether or not this invite is temporary.
attr_reader :temporary
# @return [true, false] whether this invite is still valid.
attr_reader :revoked
# @return [String] this invite's code
attr_reader :code
alias_method :max_uses, :uses
alias_method :user, :inviter
alias_method :temporary?, :temporary
alias_method :revoked?, :revoked
# @!visibility private
def initialize(data, bot)
@bot = bot
@channel = InviteChannel.new(data['channel'], bot)
@server = InviteServer.new(data['guild'], bot)
@uses = data['uses']
@inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil
@temporary = data['temporary']
@revoked = data['revoked']
@code = data['code']
end
# Code based comparison
def ==(other)
other.respond_to?(:code) ? (@code == other.code) : (@code == other)
end
# Deletes this invite
def delete
API.delete_invite(@bot.token, @code)
end
alias_method :revoke, :delete
# The inspect method is overwritten to give more useful output
def inspect
"<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked}>"
end
# Creates an invite URL.
def url
"https://discord.gg/#{@code}"
end
end
# A Discord channel, including data like the topic
class Channel
# The type string that stands for a text channel
# @see Channel#type
TEXT_TYPE = 'text'.freeze
# The type string that stands for a voice channel
# @see Channel#type
VOICE_TYPE = 'voice'.freeze
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil.
attr_reader :server
# @return [String] the type of this channel (currently either 'text' or 'voice')
attr_reader :type
# @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel
attr_reader :recipient
# @return [String] the channel's topic
attr_reader :topic
# @return [Integer] the channel's position on the channel list
attr_reader :position
# This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the
# `allow` and `deny` properties which are {Permissions} objects respectively.
# @return [Hash<Integer => OpenStruct>] the channel's permission overwrites
attr_reader :permission_overwrites
# @return [true, false] whether or not this channel is a PM channel.
def private?
@server.nil?
end
# @return [String] a string that will mention the channel as a clickable link on Discord.
def mention
"<##{@id}>"
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
# data is a sometimes a Hash and othertimes an array of Hashes, you only want the last one if it's an array
data = data[-1] if data.is_a?(Array)
@id = data['id'].to_i
@type = data['type'] || TEXT_TYPE
@topic = data['topic']
@position = data['position']
@is_private = data['is_private']
if @is_private
recipient_user = bot.ensure_user(data['recipient'])
@recipient = Recipient.new(recipient_user, self, bot)
@name = @recipient.username
else
@name = data['name']
@server = if server
server
else
bot.server(data['guild_id'].to_i)
end
end
# Populate permission overwrites
@permission_overwrites = {}
return unless data['permission_overwrites']
data['permission_overwrites'].each do |element|
role_id = element['id'].to_i
deny = Permissions.new(element['deny'])
allow = Permissions.new(element['allow'])
@permission_overwrites[role_id] = OpenStruct.new
@permission_overwrites[role_id].deny = deny
@permission_overwrites[role_id].allow = allow
end
end
# @return [true, false] whether or not this channel is a text channel
def text?
@type == TEXT_TYPE
end
# @return [true, false] whether or not this channel is a voice channel
def voice?
@type == VOICE_TYPE
end
# Sends a message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
# @return [Message] the message that was sent.
def send_message(content, tts = false)
@bot.send_message(@id, content, tts, @server && @server.id)
end
# Sends a temporary message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param timeout [Float] The amount of time in seconds after which the message sent will be deleted.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
def send_temporary_message(content, timeout, tts = false)
@bot.send_temporary_message(@id, content, timeout, tts, @server && @server.id)
end
# Sends multiple messages to a channel
# @param content [Array<String>] The messages to send.
def send_multiple(content)
content.each { |e| send_message(e) }
end
# Splits a message into chunks whose length is at most the Discord character limit, then sends them individually.
# Useful for sending long messages, but be wary of rate limits!
def split_send(content)
send_multiple(Discordrb.split_message(content))
end
# Sends a file to this channel. If it is an image, it will be embedded.
# @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed)
# @param caption [string] The caption for the file.
# @param tts [true, false] Whether or not this file's caption should be sent using Discord text-to-speech.
def send_file(file, caption: nil, tts: false)
@bot.send_file(@id, file, caption: caption, tts: tts)
end
# Permanently deletes this channel
def delete
API.delete_channel(@bot.token, @id)
end
# Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations)
# @param name [String] The new name.
def name=(name)
@name = name
update_channel_data
end
# Sets this channel's topic.
# @param topic [String] The new topic.
def topic=(topic)
@topic = topic
update_channel_data
end
# Sets this channel's position in the list.
# @param position [Integer] The new position.
def position=(position)
@position = position
update_channel_data
end
# Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny
# permission sets, or change an existing one.
# @param thing [User, Role] What to define an overwrite for.
# @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a
# green checkmark on Discord)
# @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red
# cross on Discord)
# @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites
# allow = Discordrb::Permissions.new
# allow.can_mention_everyone = true
# allow.can_send_tts_messages = true
#
# deny = Discordrb::Permissions.new
# deny.can_create_instant_invite = true
#
# channel.define_overwrite(user, allow, deny)
def define_overwrite(thing, allow, deny)
allow_bits = allow.respond_to?(:bits) ? allow.bits : allow
deny_bits = deny.respond_to?(:bits) ? deny.bits : deny
# TODO: Be more flexible about what classes are allowed here
if thing.is_a?(User) || thing.is_a?(Member) || thing.is_a?(Recipient)
API.update_user_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits)
elsif thing.is_a? Role
API.update_role_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits)
end
end
# Updates the cached data from another channel.
# @note For internal use only
# @!visibility private
def update_from(other)
@topic = other.topic
@name = other.name
@recipient = other.recipient
@permission_overwrites = other.permission_overwrites
end
# The list of users currently in this channel. This is mostly useful for a voice channel, for a text channel it will
# just return the users on the server that are online.
# @return [Array<Member>] the users in this channel
def users
if @type == 'text'
@server.online_members(include_idle: true).select { |u| u.status != :offline }
else
@server.voice_states.map { |id, voice_state| @server.member(id) if !voice_state.voice_channel.nil? && voice_state.voice_channel.id == @id }.compact
end
end
# Retrieves some of this channel's message history.
# @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher
# than 100 it will be treated as 100 on Discord's side.
# @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should
# start at the current message.
# @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start
# as soon as possible with the specified amount.
# @return [Array<Message>] the retrieved messages.
def history(amount, before_id = nil, after_id = nil)
logs = API.channel_log(@bot.token, @id, amount, before_id, after_id)
JSON.parse(logs).map { |message| Message.new(message, @bot) }
end
# Returns a single message from this channel's history by ID.
# @param message_id [Integer] The ID of the message to retrieve.
# @return [Message] the retrieved message.
def load_message(message_id)
response = API.channel_message(@bot.token, @id, message_id)
return Message.new(JSON.parse(response), @bot)
rescue RestClient::ResourceNotFound
return nil
end
# Requests all pinned messages of a channel.
# @return [Array<Message>] the received messages.
def pins
msgs = API.pins(@bot.token, @id)
JSON.parse(msgs).map { |msg| Message.new(msg, @bot) }
end
# Delete the last N messages on this channel.
# @param amount [Integer] How many messages to delete. Must be a value between 2 and 100 (Discord limitation)
# @raise [ArgumentError] if the amount of messages is not a value between 2 and 100
def prune(amount)
raise ArgumentError, 'Can only prune between 2 and 100 messages!' unless amount.between?(2, 100)
messages = history(amount).map(&:id)
API.bulk_delete(@bot.token, @id, messages)
end
# Updates the cached permission overwrites
# @note For internal use only
# @!visibility private
def update_overwrites(overwrites)
@permission_overwrites = overwrites
end
# Add an {Await} for a message in this channel. This is identical in functionality to adding a
# {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block)
end
# Creates a new invite to this channel.
# @param max_age [Integer] How many seconds this invite should last.
# @param max_uses [Integer] How many times this invite should be able to be used.
# @param temporary [true, false] Whether membership should be temporary (kicked after going offline).
# @return [Invite] the created invite.
def make_invite(max_age = 0, max_uses = 0, temporary = false)
response = API.create_invite(@bot.token, @id, max_age, max_uses, temporary)
Invite.new(JSON.parse(response), @bot)
end
# Starts typing, which displays the typing indicator on the client for five seconds.
# If you want to keep typing you'll have to resend this every five seconds. (An abstraction
# for this will eventually be coming)
def start_typing
API.start_typing(@bot.token, @id)
end
alias_method :send, :send_message
alias_method :message, :send_message
alias_method :invite, :make_invite
# The inspect method is overwritten to give more useful output
def inspect
"<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>"
end
private
def update_channel_data
API.update_channel(@bot.token, @id, @name, @topic, @position)
end
end
# An attachment to a message
class Attachment
include IDObject
# @return [Message] the message this attachment belongs to.
attr_reader :message
# @return [String] the CDN URL this attachment can be downloaded at.
attr_reader :url
# @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to
# do with CDNs
attr_reader :proxy_url
# @return [String] the attachment's filename.
attr_reader :filename
# @return [Integer] the attachment's file size in bytes.
attr_reader :size
# @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image.
attr_reader :width
# @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image.
attr_reader :height
# @!visibility private
def initialize(data, message, bot)
@bot = bot
@message = message
@url = data['url']
@proxy_url = data['proxy_url']
@filename = data['filename']
@size = data['size']
@width = data['width']
@height = data['height']
end
# @return [true, false] whether this file is an image file.
def image?
!(@width.nil? || @height.nil?)
end
end
# A message on Discord that was sent to a text channel
class Message
include IDObject
# @return [String] the content of this message.
attr_reader :content
# @return [Member] the user that sent this message.
attr_reader :author
# @return [Channel] the channel in which this message was sent.
attr_reader :channel
# @return [Time] the timestamp at which this message was sent.
attr_reader :timestamp
# @return [Array<User>] the users that were mentioned in this message.
attr_reader :mentions
# @return [Array<Role>] the roles that were mentioned in this message.
attr_reader :role_mentions
# @return [Array<Attachment>] the files attached to this message.
attr_reader :attachments
# @return [true, false] whether themesage is pinned or not.
attr_reader :pinned
alias_method :pinned?, :pinned
alias_method :user, :author
alias_method :text, :content
alias_method :to_s, :content
# @!visibility private
def initialize(data, bot)
@bot = bot
@content = data['content']
@channel = bot.channel(data['channel_id'].to_i)
@pinned = data['pinned']
@author = if data['author']
if @channel.private?
# Turn the message user into a recipient - we can't use the channel recipient
# directly because the bot may also send messages to the channel
Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot)
else
member = @channel.server.member(data['author']['id'].to_i, false)
Discordrb::LOGGER.warn("Member with ID #{data['author']['id']} not cached even though it should be.") unless member
member
end
end
@timestamp = Time.parse(data['timestamp']) if data['timestamp']
@id = data['id'].to_i
@mentions = []
data['mentions'].each do |element|
@mentions << bot.ensure_user(element)
end if data['mentions']
@role_mentions = []
# Role mentions can only happen on public servers so make sure we only parse them there
unless @channel.private?
data['mention_roles'].each do |element|
@role_mentions << @channel.server.role(element.to_i)
end if data['mention_roles']
end
@attachments = []
@attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } if data['attachments']
end
# Replies to this message with the specified content.
# @see Channel#send_message
def reply(content)
@channel.send_message(content)
end
# Edits this message to have the specified content instead.
# @param new_content [String] the new content the message should have.
# @return [Message] the resulting message.
def edit(new_content)
response = API.edit_message(@bot.token, @channel.id, @id, new_content)
Message.new(JSON.parse(response), @bot)
end
# Deletes this message.
def delete
API.delete_message(@bot.token, @channel.id, @id)
nil
end
# Pins this message
def pin
API.pin_message(@bot.token, @channel.id, @id)
@pinned = true
nil
end
# Unpins this message
def unpin
API.unpin_message(@bot.token, @channel.id, @id)
@pinned = false
nil
end
# Add an {Await} for a message with the same user and channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block)
end
# @return [true, false] whether this message was sent by the current {Bot}.
def from_bot?
@author && @author.current_bot?
end
# The inspect method is overwritten to give more useful output
def inspect
"<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>"
end
end
# Basic attributes a server should have
module ServerAttributes
# @return [String] this server's name.
attr_reader :name
# @return [String] the hexadecimal ID used to identify this server's icon.
attr_reader :icon_id
# Utility function to get the URL for the icon image
# @return [String] the URL to the icon image
def icon_url
API.icon_url(@id, @icon_id)
end
end
# A server on Discord
class Server
include IDObject
include ServerAttributes
# @return [String] the region the server is on (e. g. `amsterdam`).
attr_reader :region
# @return [Member] The server owner.
attr_reader :owner
# @return [Array<Channel>] an array of all the channels (text and voice) on this server.
attr_reader :channels
# @return [Array<Role>] an array of all the roles created on this server.
attr_reader :roles
# @return [true, false] whether or not this server is large (members > 100). If it is,
# it means the members list may be inaccurate for a couple seconds after starting up the bot.
attr_reader :large
alias_method :large?, :large
# @return [Integer] the absolute number of members on this server, offline or not.
attr_reader :member_count
# @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds.
attr_reader :afk_timeout
# @return [Channel, nil] the AFK voice channel of this server, or nil if none is set
attr_reader :afk_channel
# @return [Hash<Integer => VoiceState>] the hash (user ID => voice state) of voice states of members on this server
attr_reader :voice_states
# @!visibility private
def initialize(data, bot, exists = true)
@bot = bot
@owner_id = data['owner_id'].to_i
@id = data['id'].to_i
update_data(data)
@large = data['large']
@member_count = data['member_count']
@members = {}
@voice_states = {}
process_roles(data['roles'])
process_members(data['members'])
process_presences(data['presences'])
process_channels(data['channels'])
process_voice_states(data['voice_states'])
# Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet
@chunked = false
@processed_chunk_members = 0
# Only get the owner of the server actually exists (i. e. not for ServerDeleteEvent)
@owner = member(@owner_id) if exists
end
# @return [Channel] The default channel on this server (usually called #general)
def default_channel
@bot.channel(@id)
end
alias_method :general_channel, :default_channel
# Gets a role on this server based on its ID.
# @param id [Integer] The role ID to look for.
def role(id)
@roles.find { |e| e.id == id }
end
# Gets a member on this server based on user ID
# @param id [Integer] The user ID to look for
# @param request [true, false] Whether the member should be requested from Discord if it's not cached
def member(id, request = true)
id = id.resolve_id
return @members[id] if member_cached?(id)
return nil unless request
member = @bot.member(self, id)
@members[id] = member
rescue
nil
end
# @return [Array<Member>] an array of all the members on this server.
def members
return @members.values if @chunked
@bot.debug("Members for server #{@id} not chunked yet - initiating")
@bot.request_chunks(@id)
sleep 0.05 until @chunked
@members.values
end
alias_method :users, :members
# @param include_idle [true, false] Whether to count idle members as online.
# @param include_bots [true, false] Whether to include bot accounts in the count.
# @return [Array<Member>] an array of online members on this server.
def online_members(include_idle: false, include_bots: true)
@members.values.select do |e|
((include_idle ? e.idle? : false) || e.online?) && (include_bots ? true : !e.bot_account?)
end
end
alias_method :online_users, :online_members
# @return [Array<Channel>] an array of text channels on this server
def text_channels
@channels.select(&:text?)
end
# @return [Array<Channel>] an array of voice channels on this server
def voice_channels
@channels.select(&:voice?)
end
# Adds a role to the role cache
# @note For internal use only
# @!visibility private
def add_role(role)
@roles << role
end
# Removes a role from the role cache
# @note For internal use only
# @!visibility private
def delete_role(role_id)
@roles.reject! { |r| r.id == role_id }
@members.each do |_, member|
new_roles = member.roles.reject { |r| r.id == role_id }
member.update_roles(new_roles)
end
@channels.each do |channel|
overwrites = channel.permission_overwrites.reject { |id, _| id == role_id }
channel.update_overwrites(overwrites)
end
end
# Adds a member to the member cache.
# @note For internal use only
# @!visibility private
def add_member(member)
@members[member.id] = member
@member_count += 1
end
# Removes a member from the member cache.
# @note For internal use only
# @!visibility private
def delete_member(user_id)
@members.delete(user_id)
@member_count -= 1
end
# Checks whether a member is cached
# @note For internal use only
# @!visibility private
def member_cached?(user_id)
@members.include?(user_id)
end
# Adds a member to the cache
# @note For internal use only
# @!visibility private
def cache_member(member)
@members[member.id] = member
end
# Updates a member's voice state
# @note For internal use only
# @!visibility private
def update_voice_state(data)
user_id = data['user_id'].to_i
if data['channel_id']
unless @voice_states[user_id]
# Create a new voice state for the user
@voice_states[user_id] = VoiceState.new(user_id)
end
# Update the existing voice state (or the one we just created)
channel = @channels_by_id[data['channel_id'].to_i]
@voice_states[user_id].update(
channel,
data['mute'],
data['deaf'],
data['self_mute'],
data['self_deaf']
)
else
# The user is not in a voice channel anymore, so delete its voice state
@voice_states.delete(user_id)
end
end
# Creates a channel on this server with the given name.
# @return [Channel] the created channel.
def create_channel(name, type = 'text')
response = API.create_channel(@bot.token, @id, name, type)
Channel.new(JSON.parse(response), @bot)
end
# Creates a role on this server which can then be modified. It will be initialized (on Discord's side)
# with the regular role defaults the client uses, i. e. name is "new role", permissions are the default,
# colour is the default etc.
# @return [Role] the created role.
def create_role
response = API.create_role(@bot.token, @id)
role = Role.new(JSON.parse(response), @bot, self)
@roles << role
role
end
# @return [Array<User>] a list of banned users on this server.
def bans
users = JSON.parse(API.bans(@bot.token, @id))
users.map { |e| User.new(e['user'], @bot) }
end
# Bans a user from this server.
# @param user [User, #resolve_id] The user to ban.
# @param message_days [Integer] How many days worth of messages sent by the user should be deleted.
def ban(user, message_days = 0)
API.ban_user(@bot.token, @id, user.resolve_id, message_days)
end
# Unbans a previously banned user from this server.
# @param user [User, #resolve_id] The user to unban.
def unban(user)
API.unban_user(@bot.token, @id, user.resolve_id)
end
# Kicks a user from this server.
# @param user [User, #resolve_id] The user to kick.
def kick(user)
API.kick_user(@bot.token, @id, user.resolve_id)
end
# Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed.
# @param user [User] The user to move.
# @param channel [Channel] The voice channel to move into.
def move(user, channel)
API.move_user(@bot.token, @id, user.id, channel.id)
end
# Deletes this server. Be aware that this is permanent and impossible to undo, so be careful!
def delete
API.delete_server(@bot.token, @id)
end
# Leave the server
def leave
API.leave_server(@bot.token, @id)
end
# Transfers server ownership to another user.
# @param user [User] The user who should become the new owner.
def owner=(user)
API.transfer_ownership(@bot.token, @id, user.id)
end
# Sets the server's name.
# @param name [String] The new server name.
def name=(name)
update_server_data(name: name)
end
# Moves the server to another region. This will cause a voice interruption of at most a second.
# @param region [String] The new region the server should be in.
def region=(region)
update_server_data(region: region.to_s)
end
# Sets the server's icon.
# @param icon [String, #read] The new icon, in base64-encoded JPG format.
def icon=(icon)
if icon.respond_to? :read
icon_string = 'data:image/jpg;base64,'
icon_string += Base64.strict_encode64(icon.read)
update_server_data(icon: icon_string)
else
update_server_data(icon: icon)
end
end
# Sets the server's AFK channel.
# @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set.
def afk_channel=(afk_channel)
update_server_data(afk_channel_id: afk_channel.resolve_id)
end
# Sets the amount of time after which a user gets moved into the AFK channel.
# @param afk_timeout [Integer] The AFK timeout, in seconds.
def afk_timeout=(afk_timeout)
update_server_data(afk_timeout: afk_timeout)
end
# Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field
# @note For internal use only
# @!visibility private
def process_chunk(members)
process_members(members)
@processed_chunk_members += members.length
LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}")
# Don't bother with the rest of the method if it's not truly the last packet
return unless @processed_chunk_members == @member_count
LOGGER.debug("Finished chunking server #{@id}")
# Reset everything to normal
@chunked = true
@processed_chunk_members = 0
end
# Updates the cached data with new data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@region = new_data[:region] || new_data['region'] || @region
@icon_id = new_data[:icon] || new_data['icon'] || @icon_id
@afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout
@afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id
@afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id.nonzero? && (!@afk_channel || @afk_channel_id != @afk_channel.id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>"
end
private
def update_server_data(new_data)
API.update_server(@bot.token, @id,
new_data[:name] || @name,
new_data[:region] || @region,
new_data[:icon_id] || @icon_id,
new_data[:afk_channel_id] || @afk_channel_id,
new_data[:afk_timeout] || @afk_timeout)
update_data(new_data)
end
def process_roles(roles)
# Create roles
@roles = []
@roles_by_id = {}
return unless roles
roles.each do |element|
role = Role.new(element, @bot, self)
@roles << role
@roles_by_id[role.id] = role
end
end
def process_members(members)
return unless members
members.each do |element|
member = Member.new(element, self, @bot)
@members[member.id] = member
end
end
def process_presences(presences)
# Update user statuses with presence info
return unless presences
presences.each do |element|
next unless element['user']
user_id = element['user']['id'].to_i
user = @members[user_id]
if user
user.status = element['status'].to_sym
user.game = element['game'] ? element['game']['name'] : nil
end
end
end
def process_channels(channels)
@channels = []
@channels_by_id = {}
return unless channels
channels.each do |element|
channel = @bot.ensure_channel(element, self)
@channels << channel
@channels_by_id[channel.id] = channel
end
end
def process_voice_states(voice_states)
return unless voice_states
voice_states.each do |element|
update_voice_state(element)
end
end
end
# A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias
# {ColorRGB} is also available.
class ColourRGB
# @return [Integer] the red part of this colour (0-255).
attr_reader :red
# @return [Integer] the green part of this colour (0-255).
attr_reader :green
# @return [Integer] the blue part of this colour (0-255).
attr_reader :blue
# @return [Integer] the colour's RGB values combined into one integer.
attr_reader :combined
# Make a new colour from the combined value.
# @param combined [Integer] The colour's RGB values combined into one integer
def initialize(combined)
@combined = combined
@red = (combined >> 16) & 0xFF
@green = (combined >> 8) & 0xFF
@blue = combined & 0xFF
end
end
# Alias for the class {ColourRGB}
ColorRGB = ColourRGB
end
Update a role's position in update_from
# frozen_string_literal: true
# These classes hold relevant Discord data, such as messages or channels.
require 'ostruct'
require 'discordrb/permissions'
require 'discordrb/api'
require 'discordrb/events/message'
require 'time'
require 'base64'
# Discordrb module
module Discordrb
# The unix timestamp Discord IDs are based on
DISCORD_EPOCH = 1_420_070_400_000
# Compares two objects based on IDs - either the objects' IDs are equal, or one object is equal to the other's ID.
def self.id_compare(one_id, other)
other.respond_to?(:resolve_id) ? (one_id.resolve_id == other.resolve_id) : (one_id == other)
end
# The maximum length a Discord message can have
CHARACTER_LIMIT = 2000
# Splits a message into chunks of 2000 characters. Attempts to split by lines if possible.
# @param msg [String] The message to split.
# @return [Array<String>] the message split into chunks
def self.split_message(msg)
# If the messages is empty, return an empty array
return [] if msg.empty?
# Split the message into lines
lines = msg.lines
# Turn the message into a "triangle" of consecutively longer slices, for example the array [1,2,3,4] would become
# [
# [1],
# [1, 2],
# [1, 2, 3],
# [1, 2, 3, 4]
# ]
tri = [*0..(lines.length - 1)].map { |i| lines.combination(i + 1).first }
# Join the individual elements together to get an array of strings with consecutively more lines
joined = tri.map(&:join)
# Find the largest element that is still below the character limit, or if none such element exists return the first
ideal = joined.max_by { |e| e.length > CHARACTER_LIMIT ? -1 : e.length }
# If it's still larger than the character limit (none was smaller than it) split it into slices with the length
# being the character limit, otherwise just return an array with one element
ideal_ary = ideal.length > CHARACTER_LIMIT ? ideal.chars.each_slice(CHARACTER_LIMIT).map(&:join) : [ideal]
# Slice off the ideal part and strip newlines
rest = msg[ideal.length..-1].strip
# If none remains, return an empty array -> we're done
return [] unless rest
# Otherwise, call the method recursively to split the rest of the string and add it onto the ideal array
ideal_ary + split_message(rest)
end
# Mixin for objects that have IDs
module IDObject
# @return [Integer] the ID which uniquely identifies this object across Discord.
attr_reader :id
alias_method :resolve_id, :id
# ID based comparison
def ==(other)
Discordrb.id_compare(@id, other)
end
# Estimates the time this object was generated on based on the beginning of the ID. This is fairly accurate but
# shouldn't be relied on as Discord might change its algorithm at any time
# @return [Time] when this object was created at
def creation_time
# Milliseconds
ms = (@id >> 22) + DISCORD_EPOCH
Time.at(ms / 1000.0)
end
end
# Mixin for the attributes users should have
module UserAttributes
# @return [String] this user's username
attr_reader :username
alias_method :name, :username
# @return [String] this user's discriminator which is used internally to identify users with identical usernames.
attr_reader :discriminator
alias_method :discrim, :discriminator
alias_method :tag, :discriminator
alias_method :discord_tag, :discriminator
# @return [true, false] whether this user is a Discord bot account
attr_reader :bot_account
alias_method :bot_account?, :bot_account
# @return [String] the ID of this user's current avatar, can be used to generate an avatar URL.
# @see #avatar_url
attr_reader :avatar_id
# Utility function to mention users in messages
# @return [String] the mention code in the form of <@id>
def mention
"<@#{@id}>"
end
# Utility function to get Discord's distinct representation of a user, i. e. username + discriminator
# @return [String] distinct representation of user
def distinct
"#{@username}##{@discriminator}"
end
# Utility function to get a user's avatar URL.
# @return [String] the URL to the avatar image.
def avatar_url
API.avatar_url(@id, @avatar_id)
end
end
# User on Discord, including internal data like discriminators
class User
include IDObject
include UserAttributes
# @!attribute [r] status
# @return [Symbol] the current online status of the user (`:online`, `:offline` or `:idle`)
attr_accessor :status
# @!attribute [r] game
# @return [String, nil] the game the user is currently playing, or `nil` if none is being played.
attr_accessor :game
def initialize(data, bot)
@bot = bot
@username = data['username']
@id = data['id'].to_i
@discriminator = data['discriminator']
@avatar_id = data['avatar']
@roles = {}
@bot_account = false
@bot_account = true if data['bot']
@status = :offline
end
# Get a user's PM channel or send them a PM
# @overload pm
# Creates a private message channel for this user or returns an existing one if it already exists
# @return [Channel] the PM channel to this user.
# @overload pm(content)
# Sends a private to this user.
# @param content [String] The content to send.
# @return [Message] the message sent to this user.
def pm(content = nil)
if content
# Recursively call pm to get the channel, then send a message to it
channel = pm
channel.send_message(content)
else
# If no message was specified, return the PM channel
@bot.private_channel(@id)
end
end
alias_method :dm, :pm
# Send the user a file.
# @param file [File] The file to send to the user
# @param caption [String] The caption of the file being sent
# @return [Message] the message sent to this user.
def send_file(file, caption = nil)
pm.send_file(file, caption: caption)
end
# Set the user's name
# @note for internal use only
# @!visibility private
def update_username(username)
@username = username
end
# Add an await for a message from this user. Specifically, this adds a global await for a MessageEvent with this
# user's ID as a :from attribute.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @id }.merge(attributes), &block)
end
# Gets the member this user is on a server
# @param server [Server] The server to get the member for
# @return [Member] this user as a member on a particular server
def on(server)
id = server.resolve_id
@bot.server(id).member(@id)
end
# Is the user the bot?
# @return [true, false] whether this user is the bot
def current_bot?
@bot.profile.id == @id
end
[:offline, :idle, :online].each do |e|
define_method(e.to_s + '?') do
@status.to_sym == e
end
end
# The inspect method is overwritten to give more useful output
def inspect
"<User username=#{@username} id=#{@id} discriminator=#{@discriminator}>"
end
end
# Mixin for the attributes members and private members should have
module MemberAttributes
# @return [Time] when this member joined the server.
attr_reader :joined_at
# @return [String, nil] the nickname this member has, or nil if it has none.
attr_reader :nick
alias_method :nickname, :nick
# @return [Array<Role>] the roles this member has.
attr_reader :roles
# @return [Server] the server this member is on.
attr_reader :server
end
# Mixin to calculate resulting permissions from overrides etc.
module PermissionCalculator
# Checks whether this user can do the particular action, regardless of whether it has the permission defined,
# through for example being the server owner or having the Manage Roles permission
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @return [true, false] whether or not this user has the permission.
def permission?(action, channel = nil)
# If the member is the server owner, it irrevocably has all permissions.
return true if owner?
# First, check whether the user has Manage Roles defined.
# (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a
# Manage Permissions deny overwrite will override Manage Roles, so we can just check for
# Manage Roles once and call it a day.)
return true if defined_permission?(:administrator, channel)
# Otherwise, defer to defined_permission
defined_permission?(action, channel)
end
# Checks whether this user has a particular permission defined (i. e. not implicit, through for example
# Manage Roles)
# @param action [Symbol] The permission that should be checked. See also {Permissions::Flags} for a list.
# @param channel [Channel, nil] If channel overrides should be checked too, this channel specifies where the overrides should be checked.
# @return [true, false] whether or not this user has the permission defined.
def defined_permission?(action, channel = nil)
# Get the permission the user's roles have
role_permission = defined_role_permission?(action, channel)
# Once we have checked the role permission, we have to check the channel overrides for the
# specific user
user_specific_override = permission_overwrite(action, channel, id) # Use the ID reader as members have no ID instance variable
# Merge the two permissions - if an override is defined, it has to be allow, otherwise we only care about the role
return role_permission unless user_specific_override
user_specific_override == :allow
end
# Define methods for querying permissions
Discordrb::Permissions::Flags.each_value do |flag|
define_method "can_#{flag}?" do |channel = nil|
permission? flag, channel
end
end
alias_method :can_administrate?, :can_administrator?
private
def defined_role_permission?(action, channel)
# For each role, check if
# (1) the channel explicitly allows or permits an action for the role and
# (2) if the user is allowed to do the action if the channel doesn't specify
@roles.reduce(false) do |can_act, role|
# Get the override defined for the role on the channel
channel_allow = permission_overwrite(action, channel, role.id)
can_act = if channel_allow
# If the channel has an override, check whether it is an allow - if yes,
# the user can act, if not, it can't
channel_allow == :allow
else
# Otherwise defer to the role
role.permissions.instance_variable_get("@#{action}") || can_act
end
can_act
end
end
def permission_overwrite(action, channel, id)
# If no overwrites are defined, or no channel is set, no overwrite will be present
return nil unless channel && channel.permission_overwrites[id]
# Otherwise, check the allow and deny objects
allow = channel.permission_overwrites[id].allow
deny = channel.permission_overwrites[id].deny
if allow.instance_variable_get("@#{action}")
:allow
elsif deny.instance_variable_get("@#{action}")
:deny
end
# If there's no variable defined, nil will implicitly be returned
end
end
# A voice state represents the state of a member's connection to a voice channel. It includes data like the voice
# channel the member is connected to and mute/deaf flags.
class VoiceState
# @return [Integer] the ID of the user whose voice state is represented by this object.
attr_reader :user_id
# @return [true, false] whether this voice state's member is muted server-wide.
attr_reader :mute
# @return [true, false] whether this voice state's member is deafened server-wide.
attr_reader :deaf
# @return [true, false] whether this voice state's member has muted themselves.
attr_reader :self_mute
# @return [true, false] whether this voice state's member has deafened themselves.
attr_reader :self_deaf
# @return [Channel] the voice channel this voice state's member is in.
attr_reader :voice_channel
# @!visibility private
def initialize(user_id)
@user_id = user_id
end
# Update this voice state with new data from Discord
# @note For internal use only.
# @!visibility private
def update(channel, mute, deaf, self_mute, self_deaf)
@voice_channel = channel
@mute = mute
@deaf = deaf
@self_mute = self_mute
@self_deaf = self_deaf
end
end
# A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like
# that.
class Member < DelegateClass(User)
# @return [true, false] whether this member is muted server-wide.
def mute
voice_state_attribute(:mute)
end
# @return [true, false] whether this member is deafened server-wide.
def deaf
voice_state_attribute(:deaf)
end
# @return [true, false] whether this member has muted themselves.
def self_mute
voice_state_attribute(:self_mute)
end
# @return [true, false] whether this member has deafened themselves.
def self_deaf
voice_state_attribute(:self_deaf)
end
# @return [Channel] the voice channel this member is in.
def voice_channel
voice_state_attribute(:voice_channel)
end
alias_method :muted?, :mute
alias_method :deafened?, :deaf
alias_method :self_muted?, :self_mute
alias_method :self_deafened?, :self_deaf
include MemberAttributes
# @!visibility private
def initialize(data, server, bot)
@bot = bot
@user = bot.ensure_user(data['user'])
super @user # Initialize the delegate class
# Somehow, Discord doesn't send the server ID in the standard member format...
raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil?
@server = server || bot.server(data['guild_id'].to_i)
# Initialize the roles by getting the roles from the server one-by-one
update_roles(data['roles'])
@nick = data['nick']
@joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil
end
# @return [true, false] whether this member is the server owner.
def owner?
@server.owner == self
end
# @param role [Role, Integer, #resolve_id] the role to check or its ID.
# @return [true, false] whether this member has the specified role.
def role?(role)
role = role.resolve_id
@roles.any? { |e| e.id == role }
end
# Adds one or more roles to this member.
# @param role [Role, Array<Role>] The role(s) to add.
def add_role(role)
role_ids = role_id_array(role)
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids + role_ids).uniq
API.update_user_roles(@bot.token, @server.id, @user.id, new_role_ids)
end
# Removes one or more roles from this member.
# @param role [Role, Array<Role>] The role(s) to remove.
def remove_role(role)
old_role_ids = @roles.map(&:id)
role_ids = role_id_array(role)
new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) }
API.update_user_roles(@bot.token, @server.id, @user.id, new_role_ids)
end
# Server deafens this member.
def server_deafen
API.update_user_deafen(@bot.token, @server.id, @user.id, true)
end
# Server undeafens this member.
def server_undeafen
API.update_user_deafen(@bot.token, @server.id, @user.id, false)
end
# Server mutes this member.
def server_mute
API.update_user_mute(@bot.token, @server.id, @user.id, true)
end
# Server unmutes this member.
def server_unmute
API.update_user_mute(@bot.token, @server.id, @user.id, false)
end
# Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage
# Nicknames for other users.
# @param nick [String, nil] The string to set the nickname to, or nil if it should be reset.
def nick=(nick)
# Discord uses the empty string to signify 'no nickname' so we convert nil into that
nick ||= ''
if @user.current_bot?
API.change_own_nickname(@bot.token, @server.id, nick)
else
API.change_nickname(@bot.token, @server.id, @user.id, nick)
end
end
alias_method :nickname=, :nick=
# @return [String] the name the user displays as (nickname if they have one, username otherwise)
def display_name
nickname || username
end
# Update this member's roles
# @note For internal use only.
# @!visibility private
def update_roles(roles)
@roles = roles.map do |role|
role.is_a?(Role) ? role : @server.role(role.to_i)
end
end
# Update this member's nick
# @note For internal use only.
# @!visibility private
def update_nick(nick)
@nick = nick
end
include PermissionCalculator
# Overwriting inspect for debug purposes
def inspect
"<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>"
end
private
# Utility method to get a list of role IDs from one role or an array of roles
def role_id_array(role)
if role.is_a? Array
role.map(&:resolve_id)
else
[role.resolve_id]
end
end
# Utility method to get data out of this member's voice state
def voice_state_attribute(name)
voice_state = @server.voice_states[@user.id]
voice_state.send name if voice_state
end
end
# Recipients are members on private channels - they exist for completeness purposes, but all
# the attributes will be empty.
class Recipient < DelegateClass(User)
include MemberAttributes
# @return [Channel] the private channel this recipient is the recipient of.
attr_reader :channel
# @!visibility private
def initialize(user, channel, bot)
@bot = bot
@channel = channel
raise ArgumentError, 'Tried to create a recipient for a public channel!' unless @channel.private?
@user = user
super @user
# Member attributes
@mute = @deaf = @self_mute = @self_deaf = false
@voice_channel = nil
@server = nil
@roles = []
@joined_at = @channel.creation_time
end
# Overwriting inspect for debug purposes
def inspect
"<Recipient user=#{@user.inspect} channel=#{@channel.inspect}>"
end
end
# This class is a special variant of User that represents the bot's user profile (things like email addresses and the avatar).
# It can be accessed using {Bot#profile}.
class Profile < User
def initialize(data, bot, email, password)
super(data, bot)
@email = email
@password = password
end
# Whether or not the user is the bot. The Profile can only ever be the bot user, so this always returns true.
# @return [true]
def current_bot?
true
end
# Sets the bot's username.
# @param username [String] The new username.
def username=(username)
update_profile_data(username: username)
end
alias_method :name=, :username=
# Sets the bot's email address. If you use this method, make sure that the login email in the script matches this
# one afterwards, so the bot doesn't have any trouble logging in in the future.
# @param email [String] The new email address.
def email=(email)
update_profile_data(email: email)
end
# Changes the bot's password. This will invalidate all tokens so you will have to relog the bot.
# @param password [String] The new password.
def password=(password)
update_profile_data(new_password: password)
end
# Changes the bot's avatar.
# @param avatar [String, #read] A JPG file to be used as the avatar, either
# something readable (e. g. File) or as a data URL.
def avatar=(avatar)
if avatar.respond_to? :read
# Set the file to binary mode if supported, so we don't get problems with Windows
avatar.binmode if avatar.respond_to?(:binmode)
avatar_string = 'data:image/jpg;base64,'
avatar_string += Base64.strict_encode64(avatar.read)
update_profile_data(avatar: avatar_string)
else
update_profile_data(avatar: avatar)
end
end
# Updates the cached profile data with the new one.
# @note For internal use only.
# @!visibility private
def update_data(new_data)
@email = new_data[:email] || @email
@password = new_data[:new_password] || @password
@username = new_data[:username] || @username
@avatar_id = new_data[:avatar_id] || @avatar_id
end
# The inspect method is overwritten to give more useful output
def inspect
"<Profile email=#{@email} user=#{super}>"
end
private
def update_profile_data(new_data)
API.update_user(@bot.token,
new_data[:email] || @email,
@password,
new_data[:username] || @username,
new_data[:avatar],
new_data[:new_password] || nil)
update_data(new_data)
end
end
# A Discord role that contains permissions and applies to certain users
class Role
include IDObject
# @return [Permissions] this role's permissions.
attr_reader :permissions
# @return [String] this role's name ("new role" if it hasn't been changed)
attr_reader :name
# @return [true, false] whether or not this role should be displayed separately from other users
attr_reader :hoist
# @return [true, false] whether this role can be mentioned using a role mention
attr_reader :mentionable
alias_method :mentionable?, :mentionable
# @return [ColourRGB] the role colour
attr_reader :colour
alias_method :color, :colour
# This class is used internally as a wrapper to a Role object that allows easy writing of permission data.
class RoleWriter
# @!visibility private
def initialize(role, token)
@role = role
@token = token
end
# Write the specified permission data to the role, without updating the permission cache
# @param bits [Integer] The packed permissions to write.
def write(bits)
@role.send(:packed=, bits, false)
end
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
@server = server
@permissions = Permissions.new(data['permissions'], RoleWriter.new(self, @bot.token))
@name = data['name']
@id = data['id'].to_i
@position = data['position']
@hoist = data['hoist']
@mentionable = data['mentionable']
@colour = ColourRGB.new(data['color'])
end
# @return [String] a string that will mention this role, if it is mentionable.
def mention
"<@&#{@id}>"
end
# @return [Array<Member>] an array of members who have this role.
# @note This requests a member chunk if it hasn't for the server before, which may be slow initially
def members
@server.members.select { |m| m.role? role }
end
alias_method :users, :members
# Updates the data cache from another Role object
# @note For internal use only
# @!visibility private
def update_from(other)
@permissions = other.permissions
@name = other.name
@hoist = other.hoist
@colour = other.colour
@position = other.position
end
# Updates the data cache from a hash containing data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@hoist = new_data['hoist'] unless new_data['hoist'].nil?
@hoist = new_data[:hoist] unless new_data[:hoist].nil?
@colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour)
end
# Sets the role name to something new
# @param name [String] The name that should be set
def name=(name)
update_role_data(name: name)
end
# Changes whether or not this role is displayed at the top of the user list
# @param hoist [true, false] The value it should be changed to
def hoist=(hoist)
update_role_data(hoist: hoist)
end
# Changes whether or not this role can be mentioned
# @param mentionable [true, false] The value it should be changed to
def mentionable=(mentionable)
update_role_data(mentionable: mentionable)
end
# Sets the role colour to something new
# @param colour [ColourRGB] The new colour
def colour=(colour)
update_role_data(colour: colour)
end
alias_method :color=, :colour=
# Changes this role's permissions to a fixed bitfield. This allows setting multiple permissions at once with just
# one API call.
#
# Information on how this bitfield is structured can be found at
# https://discordapp.com/developers/docs/topics/permissions.
# @example Remove all permissions from a role
# role.packed = 0
# @param packed [Integer] A bitfield with the desired permissions value.
# @param update_perms [true, false] Whether the internal data should also be updated. This should always be true
# when calling externally.
def packed=(packed, update_perms = true)
update_role_data(permissions: packed)
@permissions.bits = packed if update_perms
end
# Delets this role. This cannot be undone without recreating the role!
def delete
API.delete_role(@bot.token, @server.id, @id)
@server.delete_role(@id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Role name=#{@name} permissions=#{@permissions.inspect} hoist=#{@hoist} colour=#{@colour.inspect} server=#{@server.inspect}>"
end
private
def update_role_data(new_data)
API.update_role(@bot.token, @server.id, @id,
new_data[:name] || @name,
(new_data[:colour] || @colour).combined,
new_data[:hoist].nil? ? @hoist : new_data[:hoist],
new_data[:mentionable].nil? ? @mentionable : new_data[:mentionable],
new_data[:permissions] || @permissions.bits)
update_data(new_data)
end
end
# A channel referenced by an invite. It has less data than regular channels, so it's a separate class
class InviteChannel
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [String] this channel's type (text or voice)
attr_reader :type
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@type = data['type']
end
end
# A server referenced to by an invite
class InviteServer
include IDObject
# @return [String] this server's name.
attr_reader :name
# @return [String, nil] the hash of the server's invite splash screen (for partnered servers) or nil if none is
# present
attr_reader :splash_hash
# @!visibility private
def initialize(data, bot)
@bot = bot
@id = data['id'].to_i
@name = data['name']
@splash_hash = data['splash_hash']
end
end
# A Discord invite to a channel
class Invite
# @return [InviteChannel] the channel this invite references.
attr_reader :channel
# @return [InviteServer] the server this invite references.
attr_reader :server
# @return [Integer] the amount of uses left on this invite.
attr_reader :uses
# @return [User, nil] the user that made this invite. May also be nil if the user can't be determined.
attr_reader :inviter
# @return [true, false] whether or not this invite is temporary.
attr_reader :temporary
# @return [true, false] whether this invite is still valid.
attr_reader :revoked
# @return [String] this invite's code
attr_reader :code
alias_method :max_uses, :uses
alias_method :user, :inviter
alias_method :temporary?, :temporary
alias_method :revoked?, :revoked
# @!visibility private
def initialize(data, bot)
@bot = bot
@channel = InviteChannel.new(data['channel'], bot)
@server = InviteServer.new(data['guild'], bot)
@uses = data['uses']
@inviter = data['inviter'] ? (@bot.user(data['inviter']['id'].to_i) || User.new(data['inviter'], bot)) : nil
@temporary = data['temporary']
@revoked = data['revoked']
@code = data['code']
end
# Code based comparison
def ==(other)
other.respond_to?(:code) ? (@code == other.code) : (@code == other)
end
# Deletes this invite
def delete
API.delete_invite(@bot.token, @code)
end
alias_method :revoke, :delete
# The inspect method is overwritten to give more useful output
def inspect
"<Invite code=#{@code} channel=#{@channel} uses=#{@uses} temporary=#{@temporary} revoked=#{@revoked}>"
end
# Creates an invite URL.
def url
"https://discord.gg/#{@code}"
end
end
# A Discord channel, including data like the topic
class Channel
# The type string that stands for a text channel
# @see Channel#type
TEXT_TYPE = 'text'.freeze
# The type string that stands for a voice channel
# @see Channel#type
VOICE_TYPE = 'voice'.freeze
include IDObject
# @return [String] this channel's name.
attr_reader :name
# @return [Server, nil] the server this channel is on. If this channel is a PM channel, it will be nil.
attr_reader :server
# @return [String] the type of this channel (currently either 'text' or 'voice')
attr_reader :type
# @return [Recipient, nil] the recipient of the private messages, or nil if this is not a PM channel
attr_reader :recipient
# @return [String] the channel's topic
attr_reader :topic
# @return [Integer] the channel's position on the channel list
attr_reader :position
# This channel's permission overwrites, represented as a hash of role/user ID to an OpenStruct which has the
# `allow` and `deny` properties which are {Permissions} objects respectively.
# @return [Hash<Integer => OpenStruct>] the channel's permission overwrites
attr_reader :permission_overwrites
# @return [true, false] whether or not this channel is a PM channel.
def private?
@server.nil?
end
# @return [String] a string that will mention the channel as a clickable link on Discord.
def mention
"<##{@id}>"
end
# @!visibility private
def initialize(data, bot, server = nil)
@bot = bot
# data is a sometimes a Hash and othertimes an array of Hashes, you only want the last one if it's an array
data = data[-1] if data.is_a?(Array)
@id = data['id'].to_i
@type = data['type'] || TEXT_TYPE
@topic = data['topic']
@position = data['position']
@is_private = data['is_private']
if @is_private
recipient_user = bot.ensure_user(data['recipient'])
@recipient = Recipient.new(recipient_user, self, bot)
@name = @recipient.username
else
@name = data['name']
@server = if server
server
else
bot.server(data['guild_id'].to_i)
end
end
# Populate permission overwrites
@permission_overwrites = {}
return unless data['permission_overwrites']
data['permission_overwrites'].each do |element|
role_id = element['id'].to_i
deny = Permissions.new(element['deny'])
allow = Permissions.new(element['allow'])
@permission_overwrites[role_id] = OpenStruct.new
@permission_overwrites[role_id].deny = deny
@permission_overwrites[role_id].allow = allow
end
end
# @return [true, false] whether or not this channel is a text channel
def text?
@type == TEXT_TYPE
end
# @return [true, false] whether or not this channel is a voice channel
def voice?
@type == VOICE_TYPE
end
# Sends a message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
# @return [Message] the message that was sent.
def send_message(content, tts = false)
@bot.send_message(@id, content, tts, @server && @server.id)
end
# Sends a temporary message to this channel.
# @param content [String] The content to send. Should not be longer than 2000 characters or it will result in an error.
# @param timeout [Float] The amount of time in seconds after which the message sent will be deleted.
# @param tts [true, false] Whether or not this message should be sent using Discord text-to-speech.
def send_temporary_message(content, timeout, tts = false)
@bot.send_temporary_message(@id, content, timeout, tts, @server && @server.id)
end
# Sends multiple messages to a channel
# @param content [Array<String>] The messages to send.
def send_multiple(content)
content.each { |e| send_message(e) }
end
# Splits a message into chunks whose length is at most the Discord character limit, then sends them individually.
# Useful for sending long messages, but be wary of rate limits!
def split_send(content)
send_multiple(Discordrb.split_message(content))
end
# Sends a file to this channel. If it is an image, it will be embedded.
# @param file [File] The file to send. There's no clear size limit for this, you'll have to attempt it for yourself (most non-image files are fine, large images may fail to embed)
# @param caption [string] The caption for the file.
# @param tts [true, false] Whether or not this file's caption should be sent using Discord text-to-speech.
def send_file(file, caption: nil, tts: false)
@bot.send_file(@id, file, caption: caption, tts: tts)
end
# Permanently deletes this channel
def delete
API.delete_channel(@bot.token, @id)
end
# Sets this channel's name. The name must be alphanumeric with dashes, unless this is a voice channel (then there are no limitations)
# @param name [String] The new name.
def name=(name)
@name = name
update_channel_data
end
# Sets this channel's topic.
# @param topic [String] The new topic.
def topic=(topic)
@topic = topic
update_channel_data
end
# Sets this channel's position in the list.
# @param position [Integer] The new position.
def position=(position)
@position = position
update_channel_data
end
# Defines a permission overwrite for this channel that sets the specified thing to the specified allow and deny
# permission sets, or change an existing one.
# @param thing [User, Role] What to define an overwrite for.
# @param allow [#bits, Permissions, Integer] The permission sets that should receive an `allow` override (i. e. a
# green checkmark on Discord)
# @param deny [#bits, Permissions, Integer] The permission sets that should receive a `deny` override (i. e. a red
# cross on Discord)
# @example Define a permission overwrite for a user that can then mention everyone and use TTS, but not create any invites
# allow = Discordrb::Permissions.new
# allow.can_mention_everyone = true
# allow.can_send_tts_messages = true
#
# deny = Discordrb::Permissions.new
# deny.can_create_instant_invite = true
#
# channel.define_overwrite(user, allow, deny)
def define_overwrite(thing, allow, deny)
allow_bits = allow.respond_to?(:bits) ? allow.bits : allow
deny_bits = deny.respond_to?(:bits) ? deny.bits : deny
# TODO: Be more flexible about what classes are allowed here
if thing.is_a?(User) || thing.is_a?(Member) || thing.is_a?(Recipient)
API.update_user_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits)
elsif thing.is_a? Role
API.update_role_overrides(@bot.token, @id, thing.id, allow_bits, deny_bits)
end
end
# Updates the cached data from another channel.
# @note For internal use only
# @!visibility private
def update_from(other)
@topic = other.topic
@name = other.name
@recipient = other.recipient
@permission_overwrites = other.permission_overwrites
end
# The list of users currently in this channel. This is mostly useful for a voice channel, for a text channel it will
# just return the users on the server that are online.
# @return [Array<Member>] the users in this channel
def users
if @type == 'text'
@server.online_members(include_idle: true).select { |u| u.status != :offline }
else
@server.voice_states.map { |id, voice_state| @server.member(id) if !voice_state.voice_channel.nil? && voice_state.voice_channel.id == @id }.compact
end
end
# Retrieves some of this channel's message history.
# @param amount [Integer] How many messages to retrieve. This must be less than or equal to 100, if it is higher
# than 100 it will be treated as 100 on Discord's side.
# @param before_id [Integer] The ID of the most recent message the retrieval should start at, or nil if it should
# start at the current message.
# @param after_id [Integer] The ID of the oldest message the retrieval should start at, or nil if it should start
# as soon as possible with the specified amount.
# @return [Array<Message>] the retrieved messages.
def history(amount, before_id = nil, after_id = nil)
logs = API.channel_log(@bot.token, @id, amount, before_id, after_id)
JSON.parse(logs).map { |message| Message.new(message, @bot) }
end
# Returns a single message from this channel's history by ID.
# @param message_id [Integer] The ID of the message to retrieve.
# @return [Message] the retrieved message.
def load_message(message_id)
response = API.channel_message(@bot.token, @id, message_id)
return Message.new(JSON.parse(response), @bot)
rescue RestClient::ResourceNotFound
return nil
end
# Requests all pinned messages of a channel.
# @return [Array<Message>] the received messages.
def pins
msgs = API.pins(@bot.token, @id)
JSON.parse(msgs).map { |msg| Message.new(msg, @bot) }
end
# Delete the last N messages on this channel.
# @param amount [Integer] How many messages to delete. Must be a value between 2 and 100 (Discord limitation)
# @raise [ArgumentError] if the amount of messages is not a value between 2 and 100
def prune(amount)
raise ArgumentError, 'Can only prune between 2 and 100 messages!' unless amount.between?(2, 100)
messages = history(amount).map(&:id)
API.bulk_delete(@bot.token, @id, messages)
end
# Updates the cached permission overwrites
# @note For internal use only
# @!visibility private
def update_overwrites(overwrites)
@permission_overwrites = overwrites
end
# Add an {Await} for a message in this channel. This is identical in functionality to adding a
# {Discordrb::Events::MessageEvent} await with the `in` attribute as this channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { in: @id }.merge(attributes), &block)
end
# Creates a new invite to this channel.
# @param max_age [Integer] How many seconds this invite should last.
# @param max_uses [Integer] How many times this invite should be able to be used.
# @param temporary [true, false] Whether membership should be temporary (kicked after going offline).
# @return [Invite] the created invite.
def make_invite(max_age = 0, max_uses = 0, temporary = false)
response = API.create_invite(@bot.token, @id, max_age, max_uses, temporary)
Invite.new(JSON.parse(response), @bot)
end
# Starts typing, which displays the typing indicator on the client for five seconds.
# If you want to keep typing you'll have to resend this every five seconds. (An abstraction
# for this will eventually be coming)
def start_typing
API.start_typing(@bot.token, @id)
end
alias_method :send, :send_message
alias_method :message, :send_message
alias_method :invite, :make_invite
# The inspect method is overwritten to give more useful output
def inspect
"<Channel name=#{@name} id=#{@id} topic=\"#{@topic}\" type=#{@type} position=#{@position} server=#{@server}>"
end
private
def update_channel_data
API.update_channel(@bot.token, @id, @name, @topic, @position)
end
end
# An attachment to a message
class Attachment
include IDObject
# @return [Message] the message this attachment belongs to.
attr_reader :message
# @return [String] the CDN URL this attachment can be downloaded at.
attr_reader :url
# @return [String] the attachment's proxy URL - I'm not sure what exactly this does, but I think it has something to
# do with CDNs
attr_reader :proxy_url
# @return [String] the attachment's filename.
attr_reader :filename
# @return [Integer] the attachment's file size in bytes.
attr_reader :size
# @return [Integer, nil] the width of an image file, in pixels, or nil if the file is not an image.
attr_reader :width
# @return [Integer, nil] the height of an image file, in pixels, or nil if the file is not an image.
attr_reader :height
# @!visibility private
def initialize(data, message, bot)
@bot = bot
@message = message
@url = data['url']
@proxy_url = data['proxy_url']
@filename = data['filename']
@size = data['size']
@width = data['width']
@height = data['height']
end
# @return [true, false] whether this file is an image file.
def image?
!(@width.nil? || @height.nil?)
end
end
# A message on Discord that was sent to a text channel
class Message
include IDObject
# @return [String] the content of this message.
attr_reader :content
# @return [Member] the user that sent this message.
attr_reader :author
# @return [Channel] the channel in which this message was sent.
attr_reader :channel
# @return [Time] the timestamp at which this message was sent.
attr_reader :timestamp
# @return [Array<User>] the users that were mentioned in this message.
attr_reader :mentions
# @return [Array<Role>] the roles that were mentioned in this message.
attr_reader :role_mentions
# @return [Array<Attachment>] the files attached to this message.
attr_reader :attachments
# @return [true, false] whether themesage is pinned or not.
attr_reader :pinned
alias_method :pinned?, :pinned
alias_method :user, :author
alias_method :text, :content
alias_method :to_s, :content
# @!visibility private
def initialize(data, bot)
@bot = bot
@content = data['content']
@channel = bot.channel(data['channel_id'].to_i)
@pinned = data['pinned']
@author = if data['author']
if @channel.private?
# Turn the message user into a recipient - we can't use the channel recipient
# directly because the bot may also send messages to the channel
Recipient.new(bot.user(data['author']['id'].to_i), @channel, bot)
else
member = @channel.server.member(data['author']['id'].to_i, false)
Discordrb::LOGGER.warn("Member with ID #{data['author']['id']} not cached even though it should be.") unless member
member
end
end
@timestamp = Time.parse(data['timestamp']) if data['timestamp']
@id = data['id'].to_i
@mentions = []
data['mentions'].each do |element|
@mentions << bot.ensure_user(element)
end if data['mentions']
@role_mentions = []
# Role mentions can only happen on public servers so make sure we only parse them there
unless @channel.private?
data['mention_roles'].each do |element|
@role_mentions << @channel.server.role(element.to_i)
end if data['mention_roles']
end
@attachments = []
@attachments = data['attachments'].map { |e| Attachment.new(e, self, @bot) } if data['attachments']
end
# Replies to this message with the specified content.
# @see Channel#send_message
def reply(content)
@channel.send_message(content)
end
# Edits this message to have the specified content instead.
# @param new_content [String] the new content the message should have.
# @return [Message] the resulting message.
def edit(new_content)
response = API.edit_message(@bot.token, @channel.id, @id, new_content)
Message.new(JSON.parse(response), @bot)
end
# Deletes this message.
def delete
API.delete_message(@bot.token, @channel.id, @id)
nil
end
# Pins this message
def pin
API.pin_message(@bot.token, @channel.id, @id)
@pinned = true
nil
end
# Unpins this message
def unpin
API.unpin_message(@bot.token, @channel.id, @id)
@pinned = false
nil
end
# Add an {Await} for a message with the same user and channel.
# @see Bot#add_await
def await(key, attributes = {}, &block)
@bot.add_await(key, Discordrb::Events::MessageEvent, { from: @author.id, in: @channel.id }.merge(attributes), &block)
end
# @return [true, false] whether this message was sent by the current {Bot}.
def from_bot?
@author && @author.current_bot?
end
# The inspect method is overwritten to give more useful output
def inspect
"<Message content=\"#{@content}\" id=#{@id} timestamp=#{@timestamp} author=#{@author} channel=#{@channel}>"
end
end
# Basic attributes a server should have
module ServerAttributes
# @return [String] this server's name.
attr_reader :name
# @return [String] the hexadecimal ID used to identify this server's icon.
attr_reader :icon_id
# Utility function to get the URL for the icon image
# @return [String] the URL to the icon image
def icon_url
API.icon_url(@id, @icon_id)
end
end
# A server on Discord
class Server
include IDObject
include ServerAttributes
# @return [String] the region the server is on (e. g. `amsterdam`).
attr_reader :region
# @return [Member] The server owner.
attr_reader :owner
# @return [Array<Channel>] an array of all the channels (text and voice) on this server.
attr_reader :channels
# @return [Array<Role>] an array of all the roles created on this server.
attr_reader :roles
# @return [true, false] whether or not this server is large (members > 100). If it is,
# it means the members list may be inaccurate for a couple seconds after starting up the bot.
attr_reader :large
alias_method :large?, :large
# @return [Integer] the absolute number of members on this server, offline or not.
attr_reader :member_count
# @return [Integer] the amount of time after which a voice user gets moved into the AFK channel, in seconds.
attr_reader :afk_timeout
# @return [Channel, nil] the AFK voice channel of this server, or nil if none is set
attr_reader :afk_channel
# @return [Hash<Integer => VoiceState>] the hash (user ID => voice state) of voice states of members on this server
attr_reader :voice_states
# @!visibility private
def initialize(data, bot, exists = true)
@bot = bot
@owner_id = data['owner_id'].to_i
@id = data['id'].to_i
update_data(data)
@large = data['large']
@member_count = data['member_count']
@members = {}
@voice_states = {}
process_roles(data['roles'])
process_members(data['members'])
process_presences(data['presences'])
process_channels(data['channels'])
process_voice_states(data['voice_states'])
# Whether this server's members have been chunked (resolved using op 8 and GUILD_MEMBERS_CHUNK) yet
@chunked = false
@processed_chunk_members = 0
# Only get the owner of the server actually exists (i. e. not for ServerDeleteEvent)
@owner = member(@owner_id) if exists
end
# @return [Channel] The default channel on this server (usually called #general)
def default_channel
@bot.channel(@id)
end
alias_method :general_channel, :default_channel
# Gets a role on this server based on its ID.
# @param id [Integer] The role ID to look for.
def role(id)
@roles.find { |e| e.id == id }
end
# Gets a member on this server based on user ID
# @param id [Integer] The user ID to look for
# @param request [true, false] Whether the member should be requested from Discord if it's not cached
def member(id, request = true)
id = id.resolve_id
return @members[id] if member_cached?(id)
return nil unless request
member = @bot.member(self, id)
@members[id] = member
rescue
nil
end
# @return [Array<Member>] an array of all the members on this server.
def members
return @members.values if @chunked
@bot.debug("Members for server #{@id} not chunked yet - initiating")
@bot.request_chunks(@id)
sleep 0.05 until @chunked
@members.values
end
alias_method :users, :members
# @param include_idle [true, false] Whether to count idle members as online.
# @param include_bots [true, false] Whether to include bot accounts in the count.
# @return [Array<Member>] an array of online members on this server.
def online_members(include_idle: false, include_bots: true)
@members.values.select do |e|
((include_idle ? e.idle? : false) || e.online?) && (include_bots ? true : !e.bot_account?)
end
end
alias_method :online_users, :online_members
# @return [Array<Channel>] an array of text channels on this server
def text_channels
@channels.select(&:text?)
end
# @return [Array<Channel>] an array of voice channels on this server
def voice_channels
@channels.select(&:voice?)
end
# Adds a role to the role cache
# @note For internal use only
# @!visibility private
def add_role(role)
@roles << role
end
# Removes a role from the role cache
# @note For internal use only
# @!visibility private
def delete_role(role_id)
@roles.reject! { |r| r.id == role_id }
@members.each do |_, member|
new_roles = member.roles.reject { |r| r.id == role_id }
member.update_roles(new_roles)
end
@channels.each do |channel|
overwrites = channel.permission_overwrites.reject { |id, _| id == role_id }
channel.update_overwrites(overwrites)
end
end
# Adds a member to the member cache.
# @note For internal use only
# @!visibility private
def add_member(member)
@members[member.id] = member
@member_count += 1
end
# Removes a member from the member cache.
# @note For internal use only
# @!visibility private
def delete_member(user_id)
@members.delete(user_id)
@member_count -= 1
end
# Checks whether a member is cached
# @note For internal use only
# @!visibility private
def member_cached?(user_id)
@members.include?(user_id)
end
# Adds a member to the cache
# @note For internal use only
# @!visibility private
def cache_member(member)
@members[member.id] = member
end
# Updates a member's voice state
# @note For internal use only
# @!visibility private
def update_voice_state(data)
user_id = data['user_id'].to_i
if data['channel_id']
unless @voice_states[user_id]
# Create a new voice state for the user
@voice_states[user_id] = VoiceState.new(user_id)
end
# Update the existing voice state (or the one we just created)
channel = @channels_by_id[data['channel_id'].to_i]
@voice_states[user_id].update(
channel,
data['mute'],
data['deaf'],
data['self_mute'],
data['self_deaf']
)
else
# The user is not in a voice channel anymore, so delete its voice state
@voice_states.delete(user_id)
end
end
# Creates a channel on this server with the given name.
# @return [Channel] the created channel.
def create_channel(name, type = 'text')
response = API.create_channel(@bot.token, @id, name, type)
Channel.new(JSON.parse(response), @bot)
end
# Creates a role on this server which can then be modified. It will be initialized (on Discord's side)
# with the regular role defaults the client uses, i. e. name is "new role", permissions are the default,
# colour is the default etc.
# @return [Role] the created role.
def create_role
response = API.create_role(@bot.token, @id)
role = Role.new(JSON.parse(response), @bot, self)
@roles << role
role
end
# @return [Array<User>] a list of banned users on this server.
def bans
users = JSON.parse(API.bans(@bot.token, @id))
users.map { |e| User.new(e['user'], @bot) }
end
# Bans a user from this server.
# @param user [User, #resolve_id] The user to ban.
# @param message_days [Integer] How many days worth of messages sent by the user should be deleted.
def ban(user, message_days = 0)
API.ban_user(@bot.token, @id, user.resolve_id, message_days)
end
# Unbans a previously banned user from this server.
# @param user [User, #resolve_id] The user to unban.
def unban(user)
API.unban_user(@bot.token, @id, user.resolve_id)
end
# Kicks a user from this server.
# @param user [User, #resolve_id] The user to kick.
def kick(user)
API.kick_user(@bot.token, @id, user.resolve_id)
end
# Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed.
# @param user [User] The user to move.
# @param channel [Channel] The voice channel to move into.
def move(user, channel)
API.move_user(@bot.token, @id, user.id, channel.id)
end
# Deletes this server. Be aware that this is permanent and impossible to undo, so be careful!
def delete
API.delete_server(@bot.token, @id)
end
# Leave the server
def leave
API.leave_server(@bot.token, @id)
end
# Transfers server ownership to another user.
# @param user [User] The user who should become the new owner.
def owner=(user)
API.transfer_ownership(@bot.token, @id, user.id)
end
# Sets the server's name.
# @param name [String] The new server name.
def name=(name)
update_server_data(name: name)
end
# Moves the server to another region. This will cause a voice interruption of at most a second.
# @param region [String] The new region the server should be in.
def region=(region)
update_server_data(region: region.to_s)
end
# Sets the server's icon.
# @param icon [String, #read] The new icon, in base64-encoded JPG format.
def icon=(icon)
if icon.respond_to? :read
icon_string = 'data:image/jpg;base64,'
icon_string += Base64.strict_encode64(icon.read)
update_server_data(icon: icon_string)
else
update_server_data(icon: icon)
end
end
# Sets the server's AFK channel.
# @param afk_channel [Channel, nil] The new AFK channel, or `nil` if there should be none set.
def afk_channel=(afk_channel)
update_server_data(afk_channel_id: afk_channel.resolve_id)
end
# Sets the amount of time after which a user gets moved into the AFK channel.
# @param afk_timeout [Integer] The AFK timeout, in seconds.
def afk_timeout=(afk_timeout)
update_server_data(afk_timeout: afk_timeout)
end
# Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field
# @note For internal use only
# @!visibility private
def process_chunk(members)
process_members(members)
@processed_chunk_members += members.length
LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}")
# Don't bother with the rest of the method if it's not truly the last packet
return unless @processed_chunk_members == @member_count
LOGGER.debug("Finished chunking server #{@id}")
# Reset everything to normal
@chunked = true
@processed_chunk_members = 0
end
# Updates the cached data with new data
# @note For internal use only
# @!visibility private
def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@region = new_data[:region] || new_data['region'] || @region
@icon_id = new_data[:icon] || new_data['icon'] || @icon_id
@afk_timeout = new_data[:afk_timeout] || new_data['afk_timeout'].to_i || @afk_timeout
@afk_channel_id = new_data[:afk_channel_id] || new_data['afk_channel_id'].to_i || @afk_channel.id
@afk_channel = @bot.channel(@afk_channel_id, self) if @afk_channel_id.nonzero? && (!@afk_channel || @afk_channel_id != @afk_channel.id)
end
# The inspect method is overwritten to give more useful output
def inspect
"<Server name=#{@name} id=#{@id} large=#{@large} region=#{@region} owner=#{@owner} afk_channel_id=#{@afk_channel_id} afk_timeout=#{@afk_timeout}>"
end
private
def update_server_data(new_data)
API.update_server(@bot.token, @id,
new_data[:name] || @name,
new_data[:region] || @region,
new_data[:icon_id] || @icon_id,
new_data[:afk_channel_id] || @afk_channel_id,
new_data[:afk_timeout] || @afk_timeout)
update_data(new_data)
end
def process_roles(roles)
# Create roles
@roles = []
@roles_by_id = {}
return unless roles
roles.each do |element|
role = Role.new(element, @bot, self)
@roles << role
@roles_by_id[role.id] = role
end
end
def process_members(members)
return unless members
members.each do |element|
member = Member.new(element, self, @bot)
@members[member.id] = member
end
end
def process_presences(presences)
# Update user statuses with presence info
return unless presences
presences.each do |element|
next unless element['user']
user_id = element['user']['id'].to_i
user = @members[user_id]
if user
user.status = element['status'].to_sym
user.game = element['game'] ? element['game']['name'] : nil
end
end
end
def process_channels(channels)
@channels = []
@channels_by_id = {}
return unless channels
channels.each do |element|
channel = @bot.ensure_channel(element, self)
@channels << channel
@channels_by_id[channel.id] = channel
end
end
def process_voice_states(voice_states)
return unless voice_states
voice_states.each do |element|
update_voice_state(element)
end
end
end
# A colour (red, green and blue values). Used for role colours. If you prefer the American spelling, the alias
# {ColorRGB} is also available.
class ColourRGB
# @return [Integer] the red part of this colour (0-255).
attr_reader :red
# @return [Integer] the green part of this colour (0-255).
attr_reader :green
# @return [Integer] the blue part of this colour (0-255).
attr_reader :blue
# @return [Integer] the colour's RGB values combined into one integer.
attr_reader :combined
# Make a new colour from the combined value.
# @param combined [Integer] The colour's RGB values combined into one integer
def initialize(combined)
@combined = combined
@red = (combined >> 16) & 0xFF
@green = (combined >> 8) & 0xFF
@blue = combined & 0xFF
end
end
# Alias for the class {ColourRGB}
ColorRGB = ColourRGB
end
|
require_dependency "onpdiff"
class DiscourseDiff
MAX_DIFFERENCE = 200
def initialize(before, after)
@before = before
@after = after
@block_by_block_diff = ONPDiff.new(tokenize_html_blocks(@before), tokenize_html_blocks(@after)).diff
@line_by_line_diff = ONPDiff.new(tokenize_line(@before), tokenize_line(@after)).short_diff
end
def inline_html
i = 0
inline = []
while i < @block_by_block_diff.length
op_code = @block_by_block_diff[i][1]
if op_code == :common then inline << @block_by_block_diff[i][0]
else
if op_code == :delete
opposite_op_code = :add
klass = "del"
first = i
second = i + 1
else
opposite_op_code = :delete
klass = "ins"
first = i + 1
second = i
end
if i + 1 < @block_by_block_diff.length && @block_by_block_diff[i + 1][1] == opposite_op_code
diff = ONPDiff.new(tokenize_html(@block_by_block_diff[first][0]), tokenize_html(@block_by_block_diff[second][0])).diff
inline << generate_inline_html(diff)
i += 1
else
inline << add_class_or_wrap_in_tags(@block_by_block_diff[i][0], klass)
end
end
i += 1
end
"<div class=\"inline-diff\">#{inline.join}</div>"
end
def side_by_side_html
i = 0
left, right = [], []
while i < @block_by_block_diff.length
op_code = @block_by_block_diff[i][1]
if op_code == :common
left << @block_by_block_diff[i][0]
right << @block_by_block_diff[i][0]
else
if op_code == :delete
opposite_op_code = :add
side = left
klass = "del"
first = i
second = i + 1
else
opposite_op_code = :delete
side = right
klass = "ins"
first = i + 1
second = i
end
if i + 1 < @block_by_block_diff.length && @block_by_block_diff[i + 1][1] == opposite_op_code
diff = ONPDiff.new(tokenize_html(@block_by_block_diff[first][0]), tokenize_html(@block_by_block_diff[second][0])).diff
deleted, inserted = generate_side_by_side_html(diff)
left << deleted
right << inserted
i += 1
else
side << add_class_or_wrap_in_tags(@block_by_block_diff[i][0], klass)
end
end
i += 1
end
"<div class=\"span8\">#{left.join}</div><div class=\"span8 offset1\">#{right.join}</div>"
end
def side_by_side_markdown
i = 0
table = ["<table class=\"markdown\">"]
while i < @line_by_line_diff.length
table << "<tr>"
op_code = @line_by_line_diff[i][1]
if op_code == :common
table << "<td>#{CGI::escapeHTML(@line_by_line_diff[i][0])}</td>"
table << "<td>#{CGI::escapeHTML(@line_by_line_diff[i][0])}</td>"
else
if op_code == :delete
opposite_op_code = :add
first = i
second = i + 1
else
opposite_op_code = :delete
first = i + 1
second = i
end
if i + 1 < @line_by_line_diff.length && @line_by_line_diff[i + 1][1] == opposite_op_code
before_tokens, after_tokens = tokenize_markdown(@line_by_line_diff[first][0]), tokenize_markdown(@line_by_line_diff[second][0])
if (before_tokens.length - after_tokens.length).abs > MAX_DIFFERENCE
before_tokens, after_tokens = tokenize_line(@line_by_line_diff[first][0]), tokenize_line(@line_by_line_diff[second][0])
end
diff = ONPDiff.new(before_tokens, after_tokens).short_diff
deleted, inserted = generate_side_by_side_markdown(diff)
table << "<td class=\"diff-del\">#{deleted.join}</td>"
table << "<td class=\"diff-ins\">#{inserted.join}</td>"
i += 1
else
if op_code == :delete
table << "<td class=\"diff-del\">#{CGI::escapeHTML(@line_by_line_diff[i][0])}</td>"
table << "<td></td>"
else
table << "<td></td>"
table << "<td class=\"diff-ins\">#{CGI::escapeHTML(@line_by_line_diff[i][0])}</td>"
end
end
end
table << "</tr>"
i += 1
end
table << "</table>"
table.join
end
private
def tokenize_line(text)
text.scan(/[^\r\n]+[\r\n]*/)
end
def tokenize_markdown(text)
t, tokens = [], []
i = 0
while i < text.length
if text[i] =~ /\w/
t << text[i]
elsif text[i] =~ /[ \t]/ && t.join =~ /^\w+$/
begin
t << text[i]
i += 1
end while i < text.length && text[i] =~ /[ \t]/
i -= 1
tokens << t.join
t = []
else
tokens << t.join if t.length > 0
tokens << text[i]
t = []
end
i += 1
end
tokens << t.join if t.length > 0
tokens
end
def tokenize_html_blocks(html)
Nokogiri::HTML.fragment(html).search("./*").map(&:to_html)
end
def tokenize_html(html)
HtmlTokenizer.tokenize(html)
end
def add_class_or_wrap_in_tags(html_or_text, klass)
index_of_next_chevron = html_or_text.index(">")
if html_or_text.length > 0 && html_or_text[0] == '<' && index_of_next_chevron
index_of_class = html_or_text.index("class=")
if index_of_class.nil? || index_of_class > index_of_next_chevron
# we do not have a class for the current tag
# add it right before the ">"
html_or_text.insert(index_of_next_chevron, " class=\"diff-#{klass}\"")
else
# we have a class, insert it at the beginning
html_or_text.insert(index_of_class + "class=".length + 1, "diff-#{klass} ")
end
else
"<#{klass}>#{html_or_text}</#{klass}>"
end
end
def generate_inline_html(diff)
inline = []
diff.each do |d|
case d[1]
when :common then inline << d[0]
when :delete then inline << add_class_or_wrap_in_tags(d[0], "del")
when :add then inline << add_class_or_wrap_in_tags(d[0], "ins")
end
end
inline
end
def generate_side_by_side_html(diff)
deleted, inserted = [], []
diff.each do |d|
case d[1]
when :common
deleted << d[0]
inserted << d[0]
when :delete then deleted << add_class_or_wrap_in_tags(d[0], "del")
when :add then inserted << add_class_or_wrap_in_tags(d[0], "ins")
end
end
[deleted, inserted]
end
def generate_side_by_side_markdown(diff)
deleted, inserted = [], []
diff.each do |d|
case d[1]
when :common
deleted << d[0]
inserted << d[0]
when :delete then deleted << "<del>#{CGI::escapeHTML(d[0])}</del>"
when :add then inserted << "<ins>#{CGI::escapeHTML(d[0])}</ins>"
end
end
[deleted, inserted]
end
class HtmlTokenizer < Nokogiri::XML::SAX::Document
attr_accessor :tokens
def initialize
@tokens = []
end
def self.tokenize(html)
me = new
parser = Nokogiri::HTML::SAX::Parser.new(me)
parser.parse("<html><body>#{html}</body></html>")
me.tokens
end
USELESS_TAGS = %w{html body}
def start_element(name, attributes = [])
return if USELESS_TAGS.include?(name)
attrs = attributes.map { |a| " #{a[0]}=\"#{a[1]}\"" }.join
@tokens << "<#{name}#{attrs}>"
end
AUTOCLOSING_TAGS = %w{area base br col embed hr img input meta}
def end_element(name)
return if USELESS_TAGS.include?(name) || AUTOCLOSING_TAGS.include?(name)
@tokens << "</#{name}>"
end
def characters(string)
@tokens.concat string.scan(/(\W|\w+[ \t]*)/).flatten
end
end
end
BUGFIX: broken images in edit history with markdown view
require_dependency "onpdiff"
class DiscourseDiff
MAX_DIFFERENCE = 200
def initialize(before, after)
@before = before
@after = after
before_html = tokenize_html_blocks(@before)
after_html = tokenize_html_blocks(@after)
before_markdown = tokenize_line(CGI::escapeHTML(@before))
after_markdown = tokenize_line(CGI::escapeHTML(@after))
@block_by_block_diff = ONPDiff.new(before_html, after_html).diff
@line_by_line_diff = ONPDiff.new(before_markdown, after_markdown).short_diff
end
def inline_html
i = 0
inline = []
while i < @block_by_block_diff.length
op_code = @block_by_block_diff[i][1]
if op_code == :common then inline << @block_by_block_diff[i][0]
else
if op_code == :delete
opposite_op_code = :add
klass = "del"
first = i
second = i + 1
else
opposite_op_code = :delete
klass = "ins"
first = i + 1
second = i
end
if i + 1 < @block_by_block_diff.length && @block_by_block_diff[i + 1][1] == opposite_op_code
diff = ONPDiff.new(tokenize_html(@block_by_block_diff[first][0]), tokenize_html(@block_by_block_diff[second][0])).diff
inline << generate_inline_html(diff)
i += 1
else
inline << add_class_or_wrap_in_tags(@block_by_block_diff[i][0], klass)
end
end
i += 1
end
"<div class=\"inline-diff\">#{inline.join}</div>"
end
def side_by_side_html
i = 0
left, right = [], []
while i < @block_by_block_diff.length
op_code = @block_by_block_diff[i][1]
if op_code == :common
left << @block_by_block_diff[i][0]
right << @block_by_block_diff[i][0]
else
if op_code == :delete
opposite_op_code = :add
side = left
klass = "del"
first = i
second = i + 1
else
opposite_op_code = :delete
side = right
klass = "ins"
first = i + 1
second = i
end
if i + 1 < @block_by_block_diff.length && @block_by_block_diff[i + 1][1] == opposite_op_code
diff = ONPDiff.new(tokenize_html(@block_by_block_diff[first][0]), tokenize_html(@block_by_block_diff[second][0])).diff
deleted, inserted = generate_side_by_side_html(diff)
left << deleted
right << inserted
i += 1
else
side << add_class_or_wrap_in_tags(@block_by_block_diff[i][0], klass)
end
end
i += 1
end
"<div class=\"span8\">#{left.join}</div><div class=\"span8 offset1\">#{right.join}</div>"
end
def side_by_side_markdown
i = 0
table = ["<table class=\"markdown\">"]
while i < @line_by_line_diff.length
table << "<tr>"
op_code = @line_by_line_diff[i][1]
if op_code == :common
table << "<td>#{@line_by_line_diff[i][0]}</td>"
table << "<td>#{@line_by_line_diff[i][0]}</td>"
else
if op_code == :delete
opposite_op_code = :add
first = i
second = i + 1
else
opposite_op_code = :delete
first = i + 1
second = i
end
if i + 1 < @line_by_line_diff.length && @line_by_line_diff[i + 1][1] == opposite_op_code
before_tokens, after_tokens = tokenize_markdown(@line_by_line_diff[first][0]), tokenize_markdown(@line_by_line_diff[second][0])
if (before_tokens.length - after_tokens.length).abs > MAX_DIFFERENCE
before_tokens, after_tokens = tokenize_line(@line_by_line_diff[first][0]), tokenize_line(@line_by_line_diff[second][0])
end
diff = ONPDiff.new(before_tokens, after_tokens).short_diff
deleted, inserted = generate_side_by_side_markdown(diff)
table << "<td class=\"diff-del\">#{deleted.join}</td>"
table << "<td class=\"diff-ins\">#{inserted.join}</td>"
i += 1
else
if op_code == :delete
table << "<td class=\"diff-del\">#{@line_by_line_diff[i][0]}</td>"
table << "<td></td>"
else
table << "<td></td>"
table << "<td class=\"diff-ins\">#{@line_by_line_diff[i][0]}</td>"
end
end
end
table << "</tr>"
i += 1
end
table << "</table>"
table.join
end
private
def tokenize_line(text)
text.scan(/[^\r\n]+[\r\n]*/)
end
def tokenize_markdown(text)
t, tokens = [], []
i = 0
while i < text.length
if text[i] =~ /\w/
t << text[i]
elsif text[i] =~ /[ \t]/ && t.join =~ /^\w+$/
begin
t << text[i]
i += 1
end while i < text.length && text[i] =~ /[ \t]/
i -= 1
tokens << t.join
t = []
else
tokens << t.join if t.length > 0
tokens << text[i]
t = []
end
i += 1
end
tokens << t.join if t.length > 0
tokens
end
def tokenize_html_blocks(html)
Nokogiri::HTML.fragment(html).search("./*").map(&:to_html)
end
def tokenize_html(html)
HtmlTokenizer.tokenize(html)
end
def add_class_or_wrap_in_tags(html_or_text, klass)
index_of_next_chevron = html_or_text.index(">")
if html_or_text.length > 0 && html_or_text[0] == '<' && index_of_next_chevron
index_of_class = html_or_text.index("class=")
if index_of_class.nil? || index_of_class > index_of_next_chevron
# we do not have a class for the current tag
# add it right before the ">"
html_or_text.insert(index_of_next_chevron, " class=\"diff-#{klass}\"")
else
# we have a class, insert it at the beginning
html_or_text.insert(index_of_class + "class=".length + 1, "diff-#{klass} ")
end
else
"<#{klass}>#{html_or_text}</#{klass}>"
end
end
def generate_inline_html(diff)
inline = []
diff.each do |d|
case d[1]
when :common then inline << d[0]
when :delete then inline << add_class_or_wrap_in_tags(d[0], "del")
when :add then inline << add_class_or_wrap_in_tags(d[0], "ins")
end
end
inline
end
def generate_side_by_side_html(diff)
deleted, inserted = [], []
diff.each do |d|
case d[1]
when :common
deleted << d[0]
inserted << d[0]
when :delete then deleted << add_class_or_wrap_in_tags(d[0], "del")
when :add then inserted << add_class_or_wrap_in_tags(d[0], "ins")
end
end
[deleted, inserted]
end
def generate_side_by_side_markdown(diff)
deleted, inserted = [], []
diff.each do |d|
case d[1]
when :common
deleted << d[0]
inserted << d[0]
when :delete then deleted << "<del>#{d[0]}</del>"
when :add then inserted << "<ins>#{d[0]}</ins>"
end
end
[deleted, inserted]
end
class HtmlTokenizer < Nokogiri::XML::SAX::Document
attr_accessor :tokens
def initialize
@tokens = []
end
def self.tokenize(html)
me = new
parser = Nokogiri::HTML::SAX::Parser.new(me)
parser.parse("<html><body>#{html}</body></html>")
me.tokens
end
USELESS_TAGS = %w{html body}
def start_element(name, attributes = [])
return if USELESS_TAGS.include?(name)
attrs = attributes.map { |a| " #{a[0]}=\"#{a[1]}\"" }.join
@tokens << "<#{name}#{attrs}>"
end
AUTOCLOSING_TAGS = %w{area base br col embed hr img input meta}
def end_element(name)
return if USELESS_TAGS.include?(name) || AUTOCLOSING_TAGS.include?(name)
@tokens << "</#{name}>"
end
def characters(string)
@tokens.concat string.scan(/(\W|\w+[ \t]*)/).flatten
end
end
end
|
#
# Copyright (C) 2010-2016 dtk contributors
#
# This file is part of the dtk project.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module DTK; class Assembly; class Instance; module Get
module AttributeMixin
def get_attributes_print_form(opts = {})
if filter = opts[:filter]
case filter
when :required_unset_attributes
opts.merge!(filter_proc: FilterProc)
else
fail Error.new("not treating filter (#{filter}) in Assembly::Instance#get_attributes_print_form")
end
end
get_attributes_print_form_aux(opts)
end
FilterProc = lambda do |r|
attr =
if r.is_a?(Attribute) then r
elsif r[:attribute] then r[:attribute]
else fail Error.new("Unexpected form for filtered element (#{r.inspect})")
end
attr.required_unset_attribute?()
end
def get_attributes_all_levels
assembly_attrs = get_assembly_level_attributes
component_attrs = get_augmented_component_attributes
assembly_attrs + component_attrs
end
AttributesAllLevels = Struct.new(:assembly_attrs, :component_attrs)
def get_attributes_all_levels_struct(filter_proc = nil)
assembly_attrs = get_assembly_level_attributes(filter_proc)
component_attrs = get_augmented_component_attributes(filter_proc)
# TODO: The pruning below might go in get_augmented_component_attributes
component_attrs.reject! do |attr|
(not attr[:nested_component].get_field?(:only_one_per_node)) && attr.is_title_attribute?()
end
AttributesAllLevels.new(assembly_attrs, component_attrs)
end
def get_augmented_component_attributes(filter_proc = nil)
get_objs_helper(:instance_nested_component_attributes, :attribute, filter_proc: filter_proc, augmented: true)
end
private
def get_attributes_print_form_aux(opts = Opts.new)
all_attrs = get_attributes_all_levels_struct(opts[:filter_proc])
assembly_attrs = all_attrs.assembly_attrs.map do |attr|
attr.print_form(opts.merge(level: :assembly))
end
component_attrs = get_component_attributes_print_form_aux(all_attrs.component_attrs, opts)
# Assembly attributes first
sort_attributes(assembly_attrs) + sort_attributes(component_attrs)
end
def get_component_attributes_print_form_aux(component_attrs, opts = Opts.new)
if opts[:all]
ret_print_form_component_attrs(component_attrs, opts)
elsif filter_component = opts[:filter_component]
# if filter component than just components that meet this filter
ret_print_form_component_attrs(filter_components(filter_component, component_attrs), opts)
else
# if all not selected and no fiter component that no component attributes
[]
end
end
def filter_components(filter, component_attrs)
regexp_filters = filter.split(",").map do | user_friendly_componet_name|
Regexp.new("^#{user_friendly_componet_name.gsub('::','__')}")
end
ret = []
component_attrs.each do |attr|
if component = attr[:nested_component]
ret << attr if regexp_filters.find { |regexp| component.display_name =~ regexp }
end
end
ret
end
def ret_print_form_component_attrs(component_attrs, opts = Opts.new)
Attribute.print_form(component_attrs, opts.merge(level: :component, assembly: self))
end
def sort_attributes(attributes)
attributes.sort { |a, b| a.display_name <=> b.display_name }
end
end
end; end; end; end
Fixed bug where set attributes could not find attribute pattern
#
# Copyright (C) 2010-2016 dtk contributors
#
# This file is part of the dtk project.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module DTK; class Assembly; class Instance; module Get
module AttributeMixin
def get_attributes_print_form(opts = {})
if filter = opts[:filter]
case filter
when :required_unset_attributes
opts.merge!(filter_proc: FilterProc)
else
fail Error.new("not treating filter (#{filter}) in Assembly::Instance#get_attributes_print_form")
end
end
get_attributes_print_form_aux(opts)
end
FilterProc = lambda do |r|
attr =
if r.is_a?(Attribute) then r
elsif r[:attribute] then r[:attribute]
else fail Error.new("Unexpected form for filtered element (#{r.inspect})")
end
attr.required_unset_attribute?()
end
def get_attributes_all_levels
assembly_attrs = get_assembly_level_attributes
component_attrs = get_augmented_component_attributes
assembly_attrs + component_attrs
end
AttributesAllLevels = Struct.new(:assembly_attrs, :component_attrs)
def get_attributes_all_levels_struct(filter_proc = nil)
assembly_attrs = get_assembly_level_attributes(filter_proc)
component_attrs = get_augmented_component_attributes(filter_proc)
# TODO: The pruning below might go in get_augmented_component_attributes
component_attrs.reject! do |attr|
(not attr[:nested_component].get_field?(:only_one_per_node)) && attr.is_title_attribute?()
end
AttributesAllLevels.new(assembly_attrs, component_attrs)
end
def get_augmented_component_attributes(filter_proc = nil)
get_objs_helper(:instance_nested_component_attributes, :attribute, filter_proc: filter_proc, augmented: true)
end
private
def get_attributes_print_form_aux(opts = Opts.new)
all_attrs = get_attributes_all_levels_struct(opts[:filter_proc])
assembly_attrs = all_attrs.assembly_attrs.map do |attr|
attr.print_form(opts.merge(level: :assembly))
end
component_attrs = get_component_attributes_print_form_aux(all_attrs.component_attrs, opts)
# Assembly attributes first
sort_attributes(assembly_attrs) + sort_attributes(component_attrs)
end
def get_component_attributes_print_form_aux(component_attrs, opts = Opts.new)
# default for opts[:all] is true
if opts[:all].nil? ? true : opts[:all]
ret_print_form_component_attrs(component_attrs, opts)
elsif filter_component = opts[:filter_component]
# if filter component than just components that meet this filter
ret_print_form_component_attrs(filter_components(filter_component, component_attrs), opts)
else
# if all not selected and no fiter component that no component attributes
[]
end
end
def filter_components(filter, component_attrs)
regexp_filters = filter.split(",").map do | user_friendly_componet_name|
Regexp.new("^#{user_friendly_componet_name.gsub('::','__')}")
end
ret = []
component_attrs.each do |attr|
if component = attr[:nested_component]
ret << attr if regexp_filters.find { |regexp| component.display_name =~ regexp }
end
end
ret
end
def ret_print_form_component_attrs(component_attrs, opts = Opts.new)
Attribute.print_form(component_attrs, opts.merge(level: :component, assembly: self))
end
def sort_attributes(attributes)
attributes.sort { |a, b| a.display_name <=> b.display_name }
end
end
end; end; end; end
|
module Dockly
VERSION = '1.4.3'
end
Version bump 1.4.4
module Dockly
VERSION = '1.4.4'
end
|
module Draper
VERSION = "1.0.0.beta1"
end
bump to 1.0.0.beta2
module Draper
VERSION = "1.0.0.beta2"
end
|
Add ssh_keys_users fact listing all public keys for all users
# SPDX-License-Identifier: GPL-3
# From https://gitlab.com/shared-puppet-modules-group/sshd/ @ c887bf09
require 'etc'
# this fact will iterate over all the known users (as defined by the
# Etc module) and look in their .ssh directory for public keys. the
# public keys are exported in a user => [keys] hash, where keys are
# stored in the array without distinction of type
Facter.add(:ssh_keys_users) do
setcode do
keys_hash = {}
Etc.passwd { |user|
keys = {}
Dir.glob(File.join(user.dir, '.ssh', '*.pub')).each { |filepath|
if FileTest.file?(filepath)
regex = %r{^ssh-(\S+) (\S+)\s?(.+)?$}
begin
line = File.open(filepath).read.chomp
if (match = regex.match(line))
keys[File.basename(filepath)] = {
'type' => match[1],
'key' => match[2],
'comment' => match[3]
}
end
rescue
puts "cannot read user SSH key: " + user.name
end
end
}
keys_hash[user.name] = keys if not keys.empty?
}
keys_hash
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: apianalytics 0.1.2 ruby lib
Gem::Specification.new do |s|
s.name = "apianalytics"
s.version = "0.1.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Kenneth Lee"]
s.date = "2015-03-25"
s.description = "The ruby agent reports API traffic to http://apianalytics.com"
s.email = "kennethkl@gmail.com"
s.extra_rdoc_files = [
"LICENSE",
"README.md"
]
s.files = [
".document",
".editorconfig",
".travis.yml",
"Gemfile",
"LICENSE",
"README.md",
"Rakefile",
"VERSION",
"apianalytics.gemspec",
"lib/apianalytics.rb",
"lib/apianalytics/capture.rb",
"lib/apianalytics/frameworks.rb",
"lib/apianalytics/frameworks/rack.rb",
"lib/apianalytics/frameworks/rails.rb",
"lib/apianalytics/frameworks/sinatra.rb",
"lib/apianalytics/message.rb",
"lib/apianalytics/message/alf.rb",
"test/helper.rb",
"test/test_capture.rb",
"test/test_rack.rb",
"test/test_sinatra.rb"
]
s.homepage = "http://github.com/Mashape/analytics-agent-ruby"
s.licenses = ["MIT"]
s.rubygems_version = "2.4.6"
s.summary = "Ruby agent for Mashape API Analytics"
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<rbczmq>, [">= 1.7.8", "~> 1.7"])
s.add_development_dependency(%q<minitest>, ["~> 5.5"])
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_development_dependency(%q<bundler>, ["~> 1.0"])
s.add_development_dependency(%q<jeweler>, [">= 2.0.1", "~> 2.0"])
s.add_development_dependency(%q<simplecov>, [">= 0"])
s.add_development_dependency(%q<rails>, ["~> 4.1"])
s.add_development_dependency(%q<sinatra>, ["~> 1.4"])
else
s.add_dependency(%q<rbczmq>, [">= 1.7.8", "~> 1.7"])
s.add_dependency(%q<minitest>, ["~> 5.5"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, [">= 2.0.1", "~> 2.0"])
s.add_dependency(%q<simplecov>, [">= 0"])
s.add_dependency(%q<rails>, ["~> 4.1"])
s.add_dependency(%q<sinatra>, ["~> 1.4"])
end
else
s.add_dependency(%q<rbczmq>, [">= 1.7.8", "~> 1.7"])
s.add_dependency(%q<minitest>, ["~> 5.5"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, [">= 2.0.1", "~> 2.0"])
s.add_dependency(%q<simplecov>, [">= 0"])
s.add_dependency(%q<rails>, ["~> 4.1"])
s.add_dependency(%q<sinatra>, ["~> 1.4"])
end
end
Regenerate gemspec for version 0.1.3
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: apianalytics 0.1.3 ruby lib
Gem::Specification.new do |s|
s.name = "apianalytics"
s.version = "0.1.3"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Kenneth Lee"]
s.date = "2015-03-26"
s.description = "The ruby agent reports API traffic to http://apianalytics.com"
s.email = "kennethkl@gmail.com"
s.extra_rdoc_files = [
"LICENSE",
"README.md"
]
s.files = [
".document",
".editorconfig",
".travis.yml",
"Gemfile",
"LICENSE",
"README.md",
"Rakefile",
"VERSION",
"apianalytics.gemspec",
"lib/apianalytics.rb",
"lib/apianalytics/capture.rb",
"lib/apianalytics/frameworks.rb",
"lib/apianalytics/frameworks/rack.rb",
"lib/apianalytics/frameworks/rails.rb",
"lib/apianalytics/frameworks/sinatra.rb",
"lib/apianalytics/message.rb",
"lib/apianalytics/message/alf.rb",
"test/helper.rb",
"test/test_capture.rb",
"test/test_rack.rb",
"test/test_sinatra.rb"
]
s.homepage = "http://github.com/Mashape/analytics-agent-ruby"
s.licenses = ["MIT"]
s.rubygems_version = "2.4.6"
s.summary = "Ruby agent for Mashape API Analytics"
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<rbczmq>, [">= 1.7.8", "~> 1.7"])
s.add_development_dependency(%q<minitest>, ["~> 5.5"])
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_development_dependency(%q<bundler>, ["~> 1.0"])
s.add_development_dependency(%q<jeweler>, [">= 2.0.1", "~> 2.0"])
s.add_development_dependency(%q<simplecov>, [">= 0"])
s.add_development_dependency(%q<rails>, ["~> 4.1"])
s.add_development_dependency(%q<sinatra>, ["~> 1.4"])
else
s.add_dependency(%q<rbczmq>, [">= 1.7.8", "~> 1.7"])
s.add_dependency(%q<minitest>, ["~> 5.5"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, [">= 2.0.1", "~> 2.0"])
s.add_dependency(%q<simplecov>, [">= 0"])
s.add_dependency(%q<rails>, ["~> 4.1"])
s.add_dependency(%q<sinatra>, ["~> 1.4"])
end
else
s.add_dependency(%q<rbczmq>, [">= 1.7.8", "~> 1.7"])
s.add_dependency(%q<minitest>, ["~> 5.5"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, [">= 2.0.1", "~> 2.0"])
s.add_dependency(%q<simplecov>, [">= 0"])
s.add_dependency(%q<rails>, ["~> 4.1"])
s.add_dependency(%q<sinatra>, ["~> 1.4"])
end
end
|
require "digest"
require_dependency "new_post_manager"
require_dependency "post_action_creator"
require_dependency "email/html_cleaner"
module Email
class Receiver
include ActionView::Helpers::NumberHelper
class ProcessingError < StandardError; end
class EmptyEmailError < ProcessingError; end
class UserNotFoundError < ProcessingError; end
class AutoGeneratedEmailError < ProcessingError; end
class NoBodyDetectedError < ProcessingError; end
class InactiveUserError < ProcessingError; end
class BlockedUserError < ProcessingError; end
class BadDestinationAddress < ProcessingError; end
class StrangersNotAllowedError < ProcessingError; end
class InsufficientTrustLevelError < ProcessingError; end
class ReplyUserNotMatchingError < ProcessingError; end
class TopicNotFoundError < ProcessingError; end
class TopicClosedError < ProcessingError; end
class InvalidPost < ProcessingError; end
class InvalidPostAction < ProcessingError; end
attr_reader :incoming_email
def initialize(mail_string)
raise EmptyEmailError if mail_string.blank?
@raw_email = mail_string
@mail = Mail.new(@raw_email)
@message_id = @mail.message_id.presence || Digest::MD5.hexdigest(mail_string)
end
def process!
@from_email, @from_display_name = parse_from_field
@incoming_email = find_or_create_incoming_email
process_internal
rescue => e
@incoming_email.update_columns(error: e.to_s)
raise
end
def find_or_create_incoming_email
IncomingEmail.find_or_create_by(message_id: @message_id) do |ie|
ie.raw = @raw_email
ie.subject = subject
ie.from_address = @from_email
ie.to_addresses = @mail.to.map(&:downcase).join(";") if @mail.to.present?
ie.cc_addresses = @mail.cc.map(&:downcase).join(";") if @mail.cc.present?
end
end
def process_internal
user = find_or_create_user(@from_email, @from_display_name)
raise UserNotFoundError if user.nil?
@incoming_email.update_columns(user_id: user.id)
body, @elided = select_body
body ||= ""
raise AutoGeneratedEmailError if is_auto_generated?
raise NoBodyDetectedError if body.blank? && !@mail.has_attachments?
raise InactiveUserError if !user.active && !user.staged
raise BlockedUserError if user.blocked
if action = subscription_action_for(body, subject)
message = SubscriptionMailer.send(action, user)
Email::Sender.new(message, :subscription).send
elsif post = find_related_post
create_reply(user: user,
raw: body,
post: post,
topic: post.topic,
skip_validations: user.staged?)
else
destination = destinations.first
raise BadDestinationAddress if destination.blank?
case destination[:type]
when :group
group = destination[:obj]
create_topic(user: user,
raw: body,
title: subject,
archetype: Archetype.private_message,
target_group_names: [group.name],
is_group_message: true,
skip_validations: true)
when :category
category = destination[:obj]
raise StrangersNotAllowedError if user.staged? && !category.email_in_allow_strangers
raise InsufficientTrustLevelError if !user.has_trust_level?(SiteSetting.email_in_min_trust)
create_topic(user: user,
raw: body,
title: subject,
category: category.id,
skip_validations: user.staged?)
when :reply
email_log = destination[:obj]
raise ReplyUserNotMatchingError if email_log.user_id != user.id
create_reply(user: user,
raw: body,
post: email_log.post,
topic: email_log.post.topic)
end
end
end
def is_auto_generated?
@mail[:precedence].to_s[/list|junk|bulk|auto_reply/] ||
@mail.header.to_s[/auto-(submitted|replied|generated)/]
end
def select_body
text = nil
html = nil
elided = nil
if @mail.multipart?
text = fix_charset(@mail.text_part)
html = fix_charset(@mail.html_part)
elsif @mail.content_type.to_s["text/html"]
html = fix_charset(@mail)
else
text = fix_charset(@mail)
end
# prefer text over html
text = trim_discourse_markers(text) if text.present?
text, elided = EmailReplyTrimmer.trim(text, true) if text.present?
return [text, elided] if text.present?
# clean the html if that's all we've got
html = Email::HtmlCleaner.new(html).output_html if html.present?
html = trim_discourse_markers(html) if html.present?
html, elided = EmailReplyTrimmer.trim(html, true) if html.present?
return [html, elided] if html.present?
end
def fix_charset(mail_part)
return nil if mail_part.blank? || mail_part.body.blank?
string = mail_part.body.decoded rescue nil
return nil if string.blank?
# 1) use the charset provided
if mail_part.charset.present?
fixed = try_to_encode(string, mail_part.charset)
return fixed if fixed.present?
end
# 2) default to UTF-8
try_to_encode(string, "UTF-8")
end
def try_to_encode(string, encoding)
string.encode("UTF-8", encoding)
rescue Encoding::InvalidByteSequenceError,
Encoding::UndefinedConversionError,
Encoding::ConverterNotFoundError
nil
end
def previous_replies_regex
@previous_replies_regex ||= /^--[- ]\n\*#{I18n.t("user_notifications.previous_discussion")}\*\n/im
end
def trim_discourse_markers(reply)
reply.split(previous_replies_regex)[0]
end
def parse_from_field
if @mail[:from].errors.blank?
address_field = @mail[:from].address_list.addresses.first
address_field.decoded
from_address = address_field.address
from_display_name = address_field.display_name.try(:to_s)
else
from_address = @mail.from[/<([^>]+)>/, 1]
from_display_name = @mail.from[/^([^<]+)/, 1]
end
[from_address.downcase, from_display_name]
end
def subject
@suject ||= @mail.subject.presence || I18n.t("emails.incoming.default_subject", email: @from_email)
end
def find_or_create_user(email, display_name)
user = nil
User.transaction do
user = User.find_by_email(email)
if user.nil? && SiteSetting.enable_staged_users
username = UserNameSuggester.sanitize_username(display_name) if display_name.present?
user = User.create(
email: email,
username: UserNameSuggester.suggest(username.presence || email),
name: display_name.presence || User.suggest_name(email),
staged: true
)
end
end
user
end
def destinations
[ @mail.destinations,
[@mail[:x_forwarded_to]].flatten.compact.map(&:decoded),
[@mail[:delivered_to]].flatten.compact.map(&:decoded),
].flatten
.select(&:present?)
.uniq
.lazy
.map { |d| check_address(d) }
.drop_while(&:blank?)
end
def check_address(address)
# only check for a group/category when 'email_in' is enabled
if SiteSetting.email_in
group = Group.find_by_email(address)
return { type: :group, obj: group } if group
category = Category.find_by_email(address)
return { type: :category, obj: category } if category
end
# reply
match = reply_by_email_address_regex.match(address)
if match && match[1].present?
email_log = EmailLog.for(match[1])
return { type: :reply, obj: email_log } if email_log
end
end
def reply_by_email_address_regex
@reply_by_email_address_regex ||= Regexp.new Regexp.escape(SiteSetting.reply_by_email_address)
.gsub(Regexp.escape("%{reply_key}"), "([[:xdigit:]]{32})")
end
def group_incoming_emails_regex
@group_incoming_emails_regex ||= Regexp.union Group.pluck(:incoming_email).select(&:present?).map { |e| e.split("|") }.flatten.uniq
end
def category_email_in_regex
@category_email_in_regex ||= Regexp.union Category.pluck(:email_in).select(&:present?).map { |e| e.split("|") }.flatten.uniq
end
def find_related_post
message_ids = [@mail.in_reply_to, Email::Receiver.extract_references(@mail.references)]
message_ids.flatten!
message_ids.select!(&:present?)
message_ids.uniq!
return if message_ids.empty?
Post.where(id: IncomingEmail.where(message_id: message_ids).select(:post_id))
.order(created_at: :desc)
.first
end
def self.extract_references(references)
if Array === references
references
elsif references.present?
references.split(/[\s,]/).map { |r| r.sub(/^</, "").sub(/>$/, "") }
end
end
def likes
@likes ||= Set.new ["+1", I18n.t('post_action_types.like.title').downcase]
end
def subscription_action_for(body, subject)
return unless SiteSetting.unsubscribe_via_email
if ([subject, body].compact.map(&:to_s).map(&:downcase) & ['unsubscribe']).any?
:confirm_unsubscribe
end
end
def post_action_for(body)
if likes.include?(body.strip.downcase)
PostActionType.types[:like]
end
end
def create_topic(options={})
create_post_with_attachments(options)
end
def create_reply(options={})
raise TopicNotFoundError if options[:topic].nil? || options[:topic].trashed?
raise TopicClosedError if options[:topic].closed?
if post_action_type = post_action_for(options[:raw])
create_post_action(options[:user], options[:post], post_action_type)
else
options[:topic_id] = options[:post].try(:topic_id)
options[:reply_to_post_number] = options[:post].try(:post_number)
options[:is_group_message] = options[:topic].private_message? && options[:topic].allowed_groups.exists?
create_post_with_attachments(options)
end
end
def create_post_action(user, post, type)
PostActionCreator.new(user, post).perform(type)
rescue PostAction::AlreadyActed
# it's cool, don't care
rescue Discourse::InvalidAccess => e
raise InvalidPostAction.new(e)
end
def create_post_with_attachments(options={})
# deal with attachments
@mail.attachments.each do |attachment|
tmp = Tempfile.new("discourse-email-attachment")
begin
# read attachment
File.open(tmp.path, "w+b") { |f| f.write attachment.body.decoded }
# create the upload for the user
opts = { is_attachment_for_group_message: options[:is_group_message] }
upload = Upload.create_for(options[:user].id, tmp, attachment.filename, tmp.size, opts)
if upload && upload.errors.empty?
# try to inline images
if attachment.content_type.start_with?("image/") && options[:raw][/\[image: .+ \d+\]/]
options[:raw].sub!(/\[image: .+ \d+\]/, attachment_markdown(upload))
else
options[:raw] << "\n\n#{attachment_markdown(upload)}\n\n"
end
end
ensure
tmp.try(:close!) rescue nil
end
end
create_post(options)
end
def attachment_markdown(upload)
if FileHelper.is_image?(upload.original_filename)
"<img src='#{upload.url}' width='#{upload.width}' height='#{upload.height}'>"
else
"<a class='attachment' href='#{upload.url}'>#{upload.original_filename}</a> (#{number_to_human_size(upload.filesize)})"
end
end
def create_post(options={})
options[:via_email] = true
options[:raw_email] = @raw_email
# ensure posts aren't created in the future
options[:created_at] = [@mail.date, DateTime.now].min
# only add elided part in messages
if @elided.present? && options[:topic].try(:private_message?)
options[:raw] << "\n\n" << "<details class='elided'>" << "\n"
options[:raw] << "<summary title='#{I18n.t('emails.incoming.show_trimmed_content')}'>···</summary>" << "\n"
options[:raw] << @elided << "\n"
options[:raw] << "</details>" << "\n"
end
manager = NewPostManager.new(options[:user], options)
result = manager.perform
raise InvalidPost, result.errors.full_messages.join("\n") if result.errors.any?
if result.post
@incoming_email.update_columns(topic_id: result.post.topic_id, post_id: result.post.id)
if result.post.topic && result.post.topic.private_message?
add_other_addresses(result.post.topic, options[:user])
end
end
end
def add_other_addresses(topic, sender)
%i(to cc bcc).each do |d|
if @mail[d] && @mail[d].address_list && @mail[d].address_list.addresses
@mail[d].address_list.addresses.each do |address_field|
begin
address_field.decoded
email = address_field.address.downcase
display_name = address_field.display_name.try(:to_s)
if should_invite?(email)
user = find_or_create_user(email, display_name)
if user && can_invite?(topic, user)
topic.topic_allowed_users.create!(user_id: user.id)
topic.add_small_action(sender, "invited_user", user.username)
end
end
rescue ActiveRecord::RecordInvalid
# don't care if user already allowed
end
end
end
end
end
def should_invite?(email)
email !~ reply_by_email_address_regex &&
email !~ group_incoming_emails_regex &&
email !~ category_email_in_regex
end
def can_invite?(topic, user)
!topic.topic_allowed_users.where(user_id: user.id).exists? &&
!topic.topic_allowed_groups.where("group_id IN (SELECT group_id FROM group_users WHERE user_id = ?)", user.id).exists?
end
end
end
detect more auto-generated emails
require "digest"
require_dependency "new_post_manager"
require_dependency "post_action_creator"
require_dependency "email/html_cleaner"
module Email
class Receiver
include ActionView::Helpers::NumberHelper
class ProcessingError < StandardError; end
class EmptyEmailError < ProcessingError; end
class UserNotFoundError < ProcessingError; end
class AutoGeneratedEmailError < ProcessingError; end
class NoBodyDetectedError < ProcessingError; end
class InactiveUserError < ProcessingError; end
class BlockedUserError < ProcessingError; end
class BadDestinationAddress < ProcessingError; end
class StrangersNotAllowedError < ProcessingError; end
class InsufficientTrustLevelError < ProcessingError; end
class ReplyUserNotMatchingError < ProcessingError; end
class TopicNotFoundError < ProcessingError; end
class TopicClosedError < ProcessingError; end
class InvalidPost < ProcessingError; end
class InvalidPostAction < ProcessingError; end
attr_reader :incoming_email
def initialize(mail_string)
raise EmptyEmailError if mail_string.blank?
@raw_email = mail_string
@mail = Mail.new(@raw_email)
@message_id = @mail.message_id.presence || Digest::MD5.hexdigest(mail_string)
end
def process!
@from_email, @from_display_name = parse_from_field
@incoming_email = find_or_create_incoming_email
process_internal
rescue => e
@incoming_email.update_columns(error: e.to_s)
raise
end
def find_or_create_incoming_email
IncomingEmail.find_or_create_by(message_id: @message_id) do |ie|
ie.raw = @raw_email
ie.subject = subject
ie.from_address = @from_email
ie.to_addresses = @mail.to.map(&:downcase).join(";") if @mail.to.present?
ie.cc_addresses = @mail.cc.map(&:downcase).join(";") if @mail.cc.present?
end
end
def process_internal
user = find_or_create_user(@from_email, @from_display_name)
raise UserNotFoundError if user.nil?
@incoming_email.update_columns(user_id: user.id)
body, @elided = select_body
body ||= ""
raise AutoGeneratedEmailError if is_auto_generated?
raise NoBodyDetectedError if body.blank? && !@mail.has_attachments?
raise InactiveUserError if !user.active && !user.staged
raise BlockedUserError if user.blocked
if action = subscription_action_for(body, subject)
message = SubscriptionMailer.send(action, user)
Email::Sender.new(message, :subscription).send
elsif post = find_related_post
create_reply(user: user,
raw: body,
post: post,
topic: post.topic,
skip_validations: user.staged?)
else
destination = destinations.first
raise BadDestinationAddress if destination.blank?
case destination[:type]
when :group
group = destination[:obj]
create_topic(user: user,
raw: body,
title: subject,
archetype: Archetype.private_message,
target_group_names: [group.name],
is_group_message: true,
skip_validations: true)
when :category
category = destination[:obj]
raise StrangersNotAllowedError if user.staged? && !category.email_in_allow_strangers
raise InsufficientTrustLevelError if !user.has_trust_level?(SiteSetting.email_in_min_trust)
create_topic(user: user,
raw: body,
title: subject,
category: category.id,
skip_validations: user.staged?)
when :reply
email_log = destination[:obj]
raise ReplyUserNotMatchingError if email_log.user_id != user.id
create_reply(user: user,
raw: body,
post: email_log.post,
topic: email_log.post.topic)
end
end
end
def is_auto_generated?
@mail[:precedence].to_s[/list|junk|bulk|auto_reply/i] ||
@mail[:from].to_s[/(mailer-?daemon|postmaster|noreply)@/i] ||
@mail.header.to_s[/auto[\-_]?(response|submitted|replied|reply|generated|respond)|holidayreply|machinegenerated/i]
end
def select_body
text = nil
html = nil
elided = nil
if @mail.multipart?
text = fix_charset(@mail.text_part)
html = fix_charset(@mail.html_part)
elsif @mail.content_type.to_s["text/html"]
html = fix_charset(@mail)
else
text = fix_charset(@mail)
end
# prefer text over html
text = trim_discourse_markers(text) if text.present?
text, elided = EmailReplyTrimmer.trim(text, true) if text.present?
return [text, elided] if text.present?
# clean the html if that's all we've got
html = Email::HtmlCleaner.new(html).output_html if html.present?
html = trim_discourse_markers(html) if html.present?
html, elided = EmailReplyTrimmer.trim(html, true) if html.present?
return [html, elided] if html.present?
end
def fix_charset(mail_part)
return nil if mail_part.blank? || mail_part.body.blank?
string = mail_part.body.decoded rescue nil
return nil if string.blank?
# 1) use the charset provided
if mail_part.charset.present?
fixed = try_to_encode(string, mail_part.charset)
return fixed if fixed.present?
end
# 2) default to UTF-8
try_to_encode(string, "UTF-8")
end
def try_to_encode(string, encoding)
string.encode("UTF-8", encoding)
rescue Encoding::InvalidByteSequenceError,
Encoding::UndefinedConversionError,
Encoding::ConverterNotFoundError
nil
end
def previous_replies_regex
@previous_replies_regex ||= /^--[- ]\n\*#{I18n.t("user_notifications.previous_discussion")}\*\n/im
end
def trim_discourse_markers(reply)
reply.split(previous_replies_regex)[0]
end
def parse_from_field
if @mail[:from].errors.blank?
address_field = @mail[:from].address_list.addresses.first
address_field.decoded
from_address = address_field.address
from_display_name = address_field.display_name.try(:to_s)
else
from_address = @mail.from[/<([^>]+)>/, 1]
from_display_name = @mail.from[/^([^<]+)/, 1]
end
[from_address.downcase, from_display_name]
end
def subject
@suject ||= @mail.subject.presence || I18n.t("emails.incoming.default_subject", email: @from_email)
end
def find_or_create_user(email, display_name)
user = nil
User.transaction do
user = User.find_by_email(email)
if user.nil? && SiteSetting.enable_staged_users
username = UserNameSuggester.sanitize_username(display_name) if display_name.present?
user = User.create(
email: email,
username: UserNameSuggester.suggest(username.presence || email),
name: display_name.presence || User.suggest_name(email),
staged: true
)
end
end
user
end
def destinations
[ @mail.destinations,
[@mail[:x_forwarded_to]].flatten.compact.map(&:decoded),
[@mail[:delivered_to]].flatten.compact.map(&:decoded),
].flatten
.select(&:present?)
.uniq
.lazy
.map { |d| check_address(d) }
.drop_while(&:blank?)
end
def check_address(address)
# only check for a group/category when 'email_in' is enabled
if SiteSetting.email_in
group = Group.find_by_email(address)
return { type: :group, obj: group } if group
category = Category.find_by_email(address)
return { type: :category, obj: category } if category
end
# reply
match = reply_by_email_address_regex.match(address)
if match && match[1].present?
email_log = EmailLog.for(match[1])
return { type: :reply, obj: email_log } if email_log
end
end
def reply_by_email_address_regex
@reply_by_email_address_regex ||= Regexp.new Regexp.escape(SiteSetting.reply_by_email_address)
.gsub(Regexp.escape("%{reply_key}"), "([[:xdigit:]]{32})")
end
def group_incoming_emails_regex
@group_incoming_emails_regex ||= Regexp.union Group.pluck(:incoming_email).select(&:present?).map { |e| e.split("|") }.flatten.uniq
end
def category_email_in_regex
@category_email_in_regex ||= Regexp.union Category.pluck(:email_in).select(&:present?).map { |e| e.split("|") }.flatten.uniq
end
def find_related_post
message_ids = [@mail.in_reply_to, Email::Receiver.extract_references(@mail.references)]
message_ids.flatten!
message_ids.select!(&:present?)
message_ids.uniq!
return if message_ids.empty?
Post.where(id: IncomingEmail.where(message_id: message_ids).select(:post_id))
.order(created_at: :desc)
.first
end
def self.extract_references(references)
if Array === references
references
elsif references.present?
references.split(/[\s,]/).map { |r| r.sub(/^</, "").sub(/>$/, "") }
end
end
def likes
@likes ||= Set.new ["+1", I18n.t('post_action_types.like.title').downcase]
end
def subscription_action_for(body, subject)
return unless SiteSetting.unsubscribe_via_email
if ([subject, body].compact.map(&:to_s).map(&:downcase) & ['unsubscribe']).any?
:confirm_unsubscribe
end
end
def post_action_for(body)
if likes.include?(body.strip.downcase)
PostActionType.types[:like]
end
end
def create_topic(options={})
create_post_with_attachments(options)
end
def create_reply(options={})
raise TopicNotFoundError if options[:topic].nil? || options[:topic].trashed?
raise TopicClosedError if options[:topic].closed?
if post_action_type = post_action_for(options[:raw])
create_post_action(options[:user], options[:post], post_action_type)
else
options[:topic_id] = options[:post].try(:topic_id)
options[:reply_to_post_number] = options[:post].try(:post_number)
options[:is_group_message] = options[:topic].private_message? && options[:topic].allowed_groups.exists?
create_post_with_attachments(options)
end
end
def create_post_action(user, post, type)
PostActionCreator.new(user, post).perform(type)
rescue PostAction::AlreadyActed
# it's cool, don't care
rescue Discourse::InvalidAccess => e
raise InvalidPostAction.new(e)
end
def create_post_with_attachments(options={})
# deal with attachments
@mail.attachments.each do |attachment|
tmp = Tempfile.new("discourse-email-attachment")
begin
# read attachment
File.open(tmp.path, "w+b") { |f| f.write attachment.body.decoded }
# create the upload for the user
opts = { is_attachment_for_group_message: options[:is_group_message] }
upload = Upload.create_for(options[:user].id, tmp, attachment.filename, tmp.size, opts)
if upload && upload.errors.empty?
# try to inline images
if attachment.content_type.start_with?("image/") && options[:raw][/\[image: .+ \d+\]/]
options[:raw].sub!(/\[image: .+ \d+\]/, attachment_markdown(upload))
else
options[:raw] << "\n\n#{attachment_markdown(upload)}\n\n"
end
end
ensure
tmp.try(:close!) rescue nil
end
end
create_post(options)
end
def attachment_markdown(upload)
if FileHelper.is_image?(upload.original_filename)
"<img src='#{upload.url}' width='#{upload.width}' height='#{upload.height}'>"
else
"<a class='attachment' href='#{upload.url}'>#{upload.original_filename}</a> (#{number_to_human_size(upload.filesize)})"
end
end
def create_post(options={})
options[:via_email] = true
options[:raw_email] = @raw_email
# ensure posts aren't created in the future
options[:created_at] = [@mail.date, DateTime.now].min
# only add elided part in messages
if @elided.present? && options[:topic].try(:private_message?)
options[:raw] << "\n\n" << "<details class='elided'>" << "\n"
options[:raw] << "<summary title='#{I18n.t('emails.incoming.show_trimmed_content')}'>···</summary>" << "\n"
options[:raw] << @elided << "\n"
options[:raw] << "</details>" << "\n"
end
manager = NewPostManager.new(options[:user], options)
result = manager.perform
raise InvalidPost, result.errors.full_messages.join("\n") if result.errors.any?
if result.post
@incoming_email.update_columns(topic_id: result.post.topic_id, post_id: result.post.id)
if result.post.topic && result.post.topic.private_message?
add_other_addresses(result.post.topic, options[:user])
end
end
end
def add_other_addresses(topic, sender)
%i(to cc bcc).each do |d|
if @mail[d] && @mail[d].address_list && @mail[d].address_list.addresses
@mail[d].address_list.addresses.each do |address_field|
begin
address_field.decoded
email = address_field.address.downcase
display_name = address_field.display_name.try(:to_s)
if should_invite?(email)
user = find_or_create_user(email, display_name)
if user && can_invite?(topic, user)
topic.topic_allowed_users.create!(user_id: user.id)
topic.add_small_action(sender, "invited_user", user.username)
end
end
rescue ActiveRecord::RecordInvalid
# don't care if user already allowed
end
end
end
end
end
def should_invite?(email)
email !~ reply_by_email_address_regex &&
email !~ group_incoming_emails_regex &&
email !~ category_email_in_regex
end
def can_invite?(topic, user)
!topic.topic_allowed_users.where(user_id: user.id).exists? &&
!topic.topic_allowed_groups.where("group_id IN (SELECT group_id FROM group_users WHERE user_id = ?)", user.id).exists?
end
end
end
|
$:.unshift File.expand_path('../../vendor', __FILE__)
require 'thor'
require 'engineyard'
require 'engineyard/cli/error'
module EY
class CLI < Thor
EYSD_VERSION = "~>0.2.4.pre"
autoload :API, 'engineyard/cli/api'
autoload :UI, 'engineyard/cli/ui'
include Thor::Actions
def self.start(*)
EY.ui = EY::CLI::UI.new
super
end
desc "deploy [ENVIRONMENT] [BRANCH]", "Deploy [BRANCH] of the app in the current directory to [ENVIRONMENT]"
method_option :force, :type => :boolean, :aliases => %w(-f),
:desc => "Force a deploy of the specified branch"
method_option :migrate, :type => :string, :aliases => %w(-m),
:desc => "Run migrations via [MIGRATE], defaults to 'rake db:migrate'"
method_option :install_eysd, :type => :boolean, :aliases => %(-s),
:desc => "Force remote install of eysd"
def deploy(env_name = nil, branch = nil)
app = account.app_for_repo(repo)
raise NoAppError.new(repo) unless app
env_name ||= EY.config.default_environment
raise DeployArgumentError if !env_name && app.environments.size > 1
default_branch = EY.config.default_branch(env_name)
branch ||= (default_branch || repo.current_branch)
raise DeployArgumentError unless branch
invalid_branch = default_branch && (branch != default_branch) && !options[:force]
raise BranchMismatch.new(default_branch, branch) if invalid_branch
if env_name
env = app.environments.find{|e| e.name == env_name }
else
env = app.environments.first
end
if !env && account.environment_named(env_name)
raise EnvironmentError, "Environment '#{env_name}' doesn't run this application\nYou can add it at cloud.engineyard.com"
elsif !env
raise EnvironmentError, "No environment named '#{env_name}'\nYou can create one at cloud.engineyard.com"
end
running = env.app_master && env.app_master.status == "running"
raise EnvironmentError, "No running instances for environment #{env.name}\nStart one at cloud.engineyard.com" unless running
hostname = env.app_master.public_hostname
username = env.username
EY.ui.info "Connecting to the server..."
ssh(hostname, "sudo eysd check '#{EY::VERSION}' '#{EYSD_VERSION}'", username, false)
case $?.exitstatus
when 255
raise EnvironmentError, "SSH connection to #{hostname} failed"
when 127
EY.ui.warn "Server does not have ey-deploy gem installed"
eysd_installed = false
when 0
eysd_installed = true
else
raise EnvironmentError, "ey-deploy version not compatible"
end
if !eysd_installed || options[:install_eysd]
EY.ui.info "Installing ey-deploy gem..."
ssh(hostname,
"sudo gem install ey-deploy -v '#{EYSD_VERSION}'",
username)
end
deploy_cmd = "eysd deploy --app #{app.name} --branch #{branch}"
deploy_cmd << " --config '#{env.config.to_json.gsub(/"/, "\\\"")}'" if env.config
if options.key(:migrate)
if options[:migrate]
deploy_cmd << " --migrate='#{options[:migrate]}'"
else
deploy_cmd << " --no-migrate"
end
end
EY.ui.info "Running deploy on server..."
deployed = ssh(hostname, deploy_cmd, username)
if deployed
EY.ui.info "Deploy complete"
else
raise EY::Error, "Deploy failed"
end
end
desc "environments [--all]", "List cloud environments for this app, or all environments"
method_option :all, :type => :boolean, :aliases => %(-a)
def environments
app = account.app_for_repo(repo)
if options[:all] || !app
envs = account.environments
if envs.empty?
EY.ui.say %|You do not have any cloud environments.|
else
EY.ui.say %|Cloud environments:|
EY.ui.print_envs(envs, EY.config.default_environment)
end
EY.ui.warn(NoAppError.new(repo).message) unless app || options[:all]
else
app = account.app_for_repo(repo)
envs = app.environments
if envs.empty?
EY.ui.warn %|You have no environments set up for the application "#{app.name}"|
EY.ui.warn %|You can make one at cloud.engineyard.com|
else
EY.ui.say %|Cloud environments for #{app.name}:|
EY.ui.print_envs(envs, EY.config.default_environment)
end
end
end
map "envs" => :environments
desc "version", "Print the version of the engineyard gem"
def version
EY.ui.say %{engineyard version #{EY::VERSION}}
end
map "-v" => :version
private
def account
@account ||= EY::Account.new(API.new)
end
def repo
@repo ||= EY::Repo.new
end
def debug(*args)
EY.ui.debug(*args)
end
def ssh(hostname, remote_cmd, user, output = true)
cmd = %{ssh -q #{user}@#{hostname} "#{remote_cmd}"}
cmd << %{ &> /dev/null} unless output
EY.ui.debug(cmd)
puts cmd if output
system cmd unless ENV["NO_SSH"]
end
end # CLI
end # EY
Don't use sudo to run eysd check
Change-Id: I8688a1b5a8214d83aff66d4e3d0e3024831030c0
Reviewed-on: http://review.engineyard.com/173
Reviewed-by: Andy Delcambre <dceae9ae498de7d794de551710d5e4d9b952cadb@engineyard.com>
Tested-by: Andy Delcambre <dceae9ae498de7d794de551710d5e4d9b952cadb@engineyard.com>
$:.unshift File.expand_path('../../vendor', __FILE__)
require 'thor'
require 'engineyard'
require 'engineyard/cli/error'
module EY
class CLI < Thor
EYSD_VERSION = "~>0.2.4.pre"
autoload :API, 'engineyard/cli/api'
autoload :UI, 'engineyard/cli/ui'
include Thor::Actions
def self.start(*)
EY.ui = EY::CLI::UI.new
super
end
desc "deploy [ENVIRONMENT] [BRANCH]", "Deploy [BRANCH] of the app in the current directory to [ENVIRONMENT]"
method_option :force, :type => :boolean, :aliases => %w(-f),
:desc => "Force a deploy of the specified branch"
method_option :migrate, :type => :string, :aliases => %w(-m),
:desc => "Run migrations via [MIGRATE], defaults to 'rake db:migrate'"
method_option :install_eysd, :type => :boolean, :aliases => %(-s),
:desc => "Force remote install of eysd"
def deploy(env_name = nil, branch = nil)
app = account.app_for_repo(repo)
raise NoAppError.new(repo) unless app
env_name ||= EY.config.default_environment
raise DeployArgumentError if !env_name && app.environments.size > 1
default_branch = EY.config.default_branch(env_name)
branch ||= (default_branch || repo.current_branch)
raise DeployArgumentError unless branch
invalid_branch = default_branch && (branch != default_branch) && !options[:force]
raise BranchMismatch.new(default_branch, branch) if invalid_branch
if env_name
env = app.environments.find{|e| e.name == env_name }
else
env = app.environments.first
end
if !env && account.environment_named(env_name)
raise EnvironmentError, "Environment '#{env_name}' doesn't run this application\nYou can add it at cloud.engineyard.com"
elsif !env
raise EnvironmentError, "No environment named '#{env_name}'\nYou can create one at cloud.engineyard.com"
end
running = env.app_master && env.app_master.status == "running"
raise EnvironmentError, "No running instances for environment #{env.name}\nStart one at cloud.engineyard.com" unless running
hostname = env.app_master.public_hostname
username = env.username
EY.ui.info "Connecting to the server..."
ssh(hostname, "eysd check '#{EY::VERSION}' '#{EYSD_VERSION}'", username, false)
case $?.exitstatus
when 255
raise EnvironmentError, "SSH connection to #{hostname} failed"
when 127
EY.ui.warn "Server does not have ey-deploy gem installed"
eysd_installed = false
when 0
eysd_installed = true
else
raise EnvironmentError, "ey-deploy version not compatible"
end
if !eysd_installed || options[:install_eysd]
EY.ui.info "Installing ey-deploy gem..."
ssh(hostname,
"sudo gem install ey-deploy -v '#{EYSD_VERSION}'",
username)
end
deploy_cmd = "eysd deploy --app #{app.name} --branch #{branch}"
deploy_cmd << " --config '#{env.config.to_json.gsub(/"/, "\\\"")}'" if env.config
if options.key(:migrate)
if options[:migrate]
deploy_cmd << " --migrate='#{options[:migrate]}'"
else
deploy_cmd << " --no-migrate"
end
end
EY.ui.info "Running deploy on server..."
deployed = ssh(hostname, deploy_cmd, username)
if deployed
EY.ui.info "Deploy complete"
else
raise EY::Error, "Deploy failed"
end
end
desc "environments [--all]", "List cloud environments for this app, or all environments"
method_option :all, :type => :boolean, :aliases => %(-a)
def environments
app = account.app_for_repo(repo)
if options[:all] || !app
envs = account.environments
if envs.empty?
EY.ui.say %|You do not have any cloud environments.|
else
EY.ui.say %|Cloud environments:|
EY.ui.print_envs(envs, EY.config.default_environment)
end
EY.ui.warn(NoAppError.new(repo).message) unless app || options[:all]
else
app = account.app_for_repo(repo)
envs = app.environments
if envs.empty?
EY.ui.warn %|You have no environments set up for the application "#{app.name}"|
EY.ui.warn %|You can make one at cloud.engineyard.com|
else
EY.ui.say %|Cloud environments for #{app.name}:|
EY.ui.print_envs(envs, EY.config.default_environment)
end
end
end
map "envs" => :environments
desc "version", "Print the version of the engineyard gem"
def version
EY.ui.say %{engineyard version #{EY::VERSION}}
end
map "-v" => :version
private
def account
@account ||= EY::Account.new(API.new)
end
def repo
@repo ||= EY::Repo.new
end
def debug(*args)
EY.ui.debug(*args)
end
def ssh(hostname, remote_cmd, user, output = true)
cmd = %{ssh -q #{user}@#{hostname} "#{remote_cmd}"}
cmd << %{ &> /dev/null} unless output
EY.ui.debug(cmd)
puts cmd if output
system cmd unless ENV["NO_SSH"]
end
end # CLI
end # EY
|
# $Abso$
module EPPClient::XML
attr_reader :sent_xml, :recv_xml, :msgQ_count, :msgQ_id
# Parses a frame and returns a Nokogiri::XML::Document.
def parse_xml(string) #:doc:
Nokogiri::XML::Document.parse(string) do |opts|
opts.options = 0
opts.noblanks
end
end
private :parse_xml
def recv_frame_to_xml #:nodoc:
@recv_xml = parse_xml(@recv_frame)
puts @recv_xml.to_s.gsub(/^/, '<< ') if $DEBUG
return @recv_xml
end
def sent_frame_to_xml #:nodoc:
@send_xml = parse_xml(@sent_frame)
puts @send_xml.to_s.gsub(/^/, '>> ') if $DEBUG
return @send_xml
end
def raw_builder(opts = {}) #:nodoc:
xml = Builder::XmlMarkup.new(opts)
yield xml
end
# creates a Builder::XmlMarkup object, mostly only used by +command+
def builder(opts = {})
raw_builder(opts) do |xml|
xml.instruct! :xml, :version =>"1.0", :encoding => "UTF-8"
xml.epp('xmlns' => EPPClient::SCHEMAS_URL['epp'], 'xmlns:epp' => EPPClient::SCHEMAS_URL['epp']) do
yield xml
end
end
end
# Takes a xml response and checks that the result is in the right range of
# results, that is, between 1000 and 1999, which are results meaning all
# went well.
#
# In case all went well, it either calls the callback if given, or returns
# true.
#
# In case there was a problem, an EPPErrorResponse exception is raised.
def get_result(args)
xml = case args
when Hash
args.delete(:xml)
else
xml = args
args = {}
xml
end
args[:range] ||= 1000..1999
if (mq = xml.xpath('epp:epp/epp:response/epp:msgQ', EPPClient::SCHEMAS_URL)).size > 0
@msgQ_count = mq.attribute('count').value.to_i
@msgQ_id = mq.attribute('id').value
puts "DEBUG: MSGQ : count=#{@msgQ_count}, id=#{@msgQ_id}\n" if $DEBUG
else
@msgQ_count = 0
@msgQ_id = nil
end
res = xml.xpath('epp:epp/epp:response/epp:result', EPPClient::SCHEMAS_URL)
code = res.attribute('code').value.to_i
if args[:range].include?(code)
if args.key?(:callback)
case cb = args[:callback]
when Symbol
return send(cb, xml.xpath('epp:epp/epp:response', EPPClient::SCHEMAS_URL))
else
raise ArgumentError, "Invalid callback type"
end
else
return true
end
else
raise EPPErrorResponse.new(:xml => xml, :code => code, :message => res.xpath('epp:msg', EPPClient::SCHEMAS_URL).text)
end
end
# Creates the xml for the command.
#
# You can either pass a block to it, in that case, it's the command body,
# or a series of procs, the first one being the commands, the other ones
# being the extensions.
#
# command do |xml|
# xml.logout
# end
#
# or
#
# command(lambda do |xml|
# xml.logout
# end, lambda do |xml|
# xml.extension
# end)
def command(*args, &block)
builder do |xml|
xml.command do
if block_given?
yield xml
else
command = args.shift
command.call(xml)
args.each do |ext|
xml.extension do
ext.call(xml)
end
end
end
xml.clTRID(clTRID)
end
end
end
# Wraps the content in an epp:extension.
def extension
raw_builder do |xml|
xml.extension do
yield(xml)
end
end
end
# Insert xml2 in xml1 before pattern
def insert_extension(xml1, xml2, pattern = /<clTRID>/)
xml1.sub(pattern, "#{xml2}\\&")
end
end
Mettre le nom complet de l'objet.
# $Abso$
module EPPClient::XML
attr_reader :sent_xml, :recv_xml, :msgQ_count, :msgQ_id
# Parses a frame and returns a Nokogiri::XML::Document.
def parse_xml(string) #:doc:
Nokogiri::XML::Document.parse(string) do |opts|
opts.options = 0
opts.noblanks
end
end
private :parse_xml
def recv_frame_to_xml #:nodoc:
@recv_xml = parse_xml(@recv_frame)
puts @recv_xml.to_s.gsub(/^/, '<< ') if $DEBUG
return @recv_xml
end
def sent_frame_to_xml #:nodoc:
@send_xml = parse_xml(@sent_frame)
puts @send_xml.to_s.gsub(/^/, '>> ') if $DEBUG
return @send_xml
end
def raw_builder(opts = {}) #:nodoc:
xml = Builder::XmlMarkup.new(opts)
yield xml
end
# creates a Builder::XmlMarkup object, mostly only used by +command+
def builder(opts = {})
raw_builder(opts) do |xml|
xml.instruct! :xml, :version =>"1.0", :encoding => "UTF-8"
xml.epp('xmlns' => EPPClient::SCHEMAS_URL['epp'], 'xmlns:epp' => EPPClient::SCHEMAS_URL['epp']) do
yield xml
end
end
end
# Takes a xml response and checks that the result is in the right range of
# results, that is, between 1000 and 1999, which are results meaning all
# went well.
#
# In case all went well, it either calls the callback if given, or returns
# true.
#
# In case there was a problem, an EPPErrorResponse exception is raised.
def get_result(args)
xml = case args
when Hash
args.delete(:xml)
else
xml = args
args = {}
xml
end
args[:range] ||= 1000..1999
if (mq = xml.xpath('epp:epp/epp:response/epp:msgQ', EPPClient::SCHEMAS_URL)).size > 0
@msgQ_count = mq.attribute('count').value.to_i
@msgQ_id = mq.attribute('id').value
puts "DEBUG: MSGQ : count=#{@msgQ_count}, id=#{@msgQ_id}\n" if $DEBUG
else
@msgQ_count = 0
@msgQ_id = nil
end
res = xml.xpath('epp:epp/epp:response/epp:result', EPPClient::SCHEMAS_URL)
code = res.attribute('code').value.to_i
if args[:range].include?(code)
if args.key?(:callback)
case cb = args[:callback]
when Symbol
return send(cb, xml.xpath('epp:epp/epp:response', EPPClient::SCHEMAS_URL))
else
raise ArgumentError, "Invalid callback type"
end
else
return true
end
else
raise EPPClient::EPPErrorResponse.new(:xml => xml, :code => code, :message => res.xpath('epp:msg', EPPClient::SCHEMAS_URL).text)
end
end
# Creates the xml for the command.
#
# You can either pass a block to it, in that case, it's the command body,
# or a series of procs, the first one being the commands, the other ones
# being the extensions.
#
# command do |xml|
# xml.logout
# end
#
# or
#
# command(lambda do |xml|
# xml.logout
# end, lambda do |xml|
# xml.extension
# end)
def command(*args, &block)
builder do |xml|
xml.command do
if block_given?
yield xml
else
command = args.shift
command.call(xml)
args.each do |ext|
xml.extension do
ext.call(xml)
end
end
end
xml.clTRID(clTRID)
end
end
end
# Wraps the content in an epp:extension.
def extension
raw_builder do |xml|
xml.extension do
yield(xml)
end
end
end
# Insert xml2 in xml1 before pattern
def insert_extension(xml1, xml2, pattern = /<clTRID>/)
xml1.sub(pattern, "#{xml2}\\&")
end
end
|
Detect when the Concourse GPG keys file hasn't been updated
Adds a simple test that compares the file modification time of `./.gpg-id` to
that of `./concourse/vars-files/gpg-keys.yml`. In theory, we should never
updated `.gpg-id` without updating `gpg-keys.yml`, and so we should always see
the latters file modification time is after the formers.
Test failure looks like
1) vars files gpg-keys.yml was updated after a change to .gpg-id
Failure/Error: expect(gpg_keys_mod_time).to be >= gpg_id_mod_time
expected: >= 2022-07-27 10:43:07.433614004 +0000
got: 2022-07-27 10:41:41.427827006 +0000
REPO_ROOT = File.expand_path(File.join(SPEC_DIR, "..", ".."))
RSpec.describe "vars files" do
it "gpg-keys.yml was updated after a change to .gpg-id" do
gpg_id_mod_time = File.mtime(File.join(REPO_ROOT, ".gpg-id"))
gpg_keys_mod_time = File.mtime(File.join(REPO_ROOT, "concourse", "vars-files", "gpg-keys.yml"))
expect(gpg_keys_mod_time).to be >= gpg_id_mod_time
end
end
|
Pod::Spec.new do |s|
s.name = "ILPDFKit"
s.version = "0.2.0"
s.summary = "A simple toolkit for filling out and saving PDF forms, and extracting PDF data."
s.homepage = "http://ilpdfkit.com"
s.screenshot = "http://imgur.com/oo5HLUg.png"
s.license = "MIT"
s.author = { "Derek Blair" => "derekjblair@gmail.com" }
s.platform = :ios
s.ios.deployment_target = "7.0"
s.source = { :git => "https://github.com/conquermobile/ILPDFKit.git", :tag => "0.2.0" }
s.source_files = "ILPDFKit/**/*.{h,m}"
s.frameworks = "QuartzCore", "UIKit"
s.requires_arc = true
s.dependency = { :git => "https://github.com/conquermobile/SJCSimplePDFView.git", :branch => "master" }
s.documentation_url = 'http://ilpdfkit.com/index.html'
end
Fixing up the podspec dependency
Pod::Spec.new do |s|
s.name = "ILPDFKit"
s.version = "0.2.0"
s.summary = "A simple toolkit for filling out and saving PDF forms, and extracting PDF data."
s.homepage = "http://ilpdfkit.com"
s.screenshot = "http://imgur.com/oo5HLUg.png"
s.license = "MIT"
s.author = { "Derek Blair" => "derekjblair@gmail.com" }
s.platform = :ios
s.ios.deployment_target = "7.0"
s.source = { :git => "https://github.com/conquermobile/ILPDFKit.git", :tag => "0.2.0" }
s.source_files = "ILPDFKit/**/*.{h,m}"
s.frameworks = "QuartzCore", "UIKit"
s.requires_arc = true
s.documentation_url = 'http://ilpdfkit.com/index.html'
s.dependency 'SJCSimplePDFView'
#, :git => "https://github.com/conquermobile/SJCSimplePDFView.git", :tag => "1.0.0"
end
|
Pod::Spec.new do |s|
s.name = 'ImojiSDK'
s.version = '0.2.4'
s.license = 'MIT'
s.summary = 'iOS SDK for Imoji.'
s.homepage = 'http://imoji.io/sdk'
s.authors = {'Nima Khoshini'=>'nima@imojiapp.com'}
s.source = { :git => 'https://github.com/imojiengineering/imoji-ios-sdk.git', :tag => s.version.to_s }
s.ios.deployment_target = '7.0'
s.source_files = 'Source/**/*.{h,m}'
s.requires_arc = true
s.dependency "Bolts", '~> 1.1'
s.dependency "libwebp", "~> 0.4.3"
end
final version update
Pod::Spec.new do |s|
s.name = 'ImojiSDK'
s.version = '0.2.5'
s.license = 'MIT'
s.summary = 'iOS SDK for Imoji.'
s.homepage = 'http://imoji.io/sdk'
s.authors = {'Nima Khoshini'=>'nima@imojiapp.com'}
s.source = { :git => 'https://github.com/imojiengineering/imoji-ios-sdk.git', :tag => s.version.to_s }
s.ios.deployment_target = '7.0'
s.source_files = 'Source/**/*.{h,m}'
s.requires_arc = true
s.dependency "Bolts", '~> 1.1'
s.dependency "libwebp", "~> 0.4.3"
end
|
module Ethereum
##
# Manages the chain and requests to it.
#
class Chain
HEAD_KEY = 'HEAD'.freeze
##
# @param config [Ethereum::Config] configuration of the chain
#
def initialize(config, genesis: nil, new_head_cb: nil, coinbase: Constant::ADDRESS_ZERO)
@config = config
@db = config.db
@new_head_cb = new_head_cb
@index = Index.new config
@coinbase = coinbase
initialize_blockchain(genesis) unless @db.has_key?(HEAD_KEY)
logger.debug "chain @ head_hash=#{head}"
@genesis = get @index.get_block_by_number(0)
logger.debug "got genesis nonce=#{Utils.encode_hex @genesis.nonce} difficulty=#{@genesis.difficulty}"
@head_candidate = nil
update_head_candidate
end
def head
initialize_blockchain unless @db && @db.has_key?(HEAD_KEY)
ptr = @db.get HEAD_KEY
blocks.get_block @config, ptr # TODO - blocks
end
def commit
#TODO
end
def include?(blk_hash)
# TODO
end
private
def logger
@logger = Logger['eth.chain']
end
def initialize_blockchain(genesis=nil)
logger.info "Initializing new chain"
unless genesis
genesis = blocks.genesis @config # TODO - blocks
logger.info "new genesis genesis_hash=#{genesis} difficulty=#{genesis.difficulty}"
@index.add_block genesis
end
store_block genesis
raise "failed to store block" unless genesis == blocks.get_block(@config, genesis.hash)
update_head genesis
raise "falied to update head" unless include?(genesis.hash)
commit
end
def store_block
# TODO
end
def update_head_candidate
# TODO
end
end
end
update chain
module Ethereum
##
# Manages the chain and requests to it.
#
class Chain
HEAD_KEY = 'HEAD'.freeze
##
# @param env [Ethereum::Env] configuration of the chain
#
def initialize(env, genesis: nil, new_head_cb: nil, coinbase: Constant::ADDRESS_ZERO)
@env = env
@db = env.db
@new_head_cb = new_head_cb
@index = Index.new env
@coinbase = coinbase
initialize_blockchain(genesis) unless @db.has_key?(HEAD_KEY)
logger.debug "chain @ head_hash=#{head}"
@genesis = get @index.get_block_by_number(0)
logger.debug "got genesis nonce=#{Utils.encode_hex @genesis.nonce} difficulty=#{@genesis.difficulty}"
@head_candidate = nil
update_head_candidate
end
def head
initialize_blockchain unless @db && @db.has_key?(HEAD_KEY)
ptr = @db.get HEAD_KEY
blocks.get_block @env, ptr # TODO - blocks
end
def commit
@db.commit
end
def include?(blk_hash)
@db.has_key?(blk_hash)
end
private
def logger
@logger = Logger['eth.chain']
end
def initialize_blockchain(genesis=nil)
logger.info "Initializing new chain"
unless genesis
genesis = blocks.genesis @env # TODO - blocks
logger.info "new genesis genesis_hash=#{genesis} difficulty=#{genesis.difficulty}"
@index.add_block genesis
end
store_block genesis
raise "failed to store block" unless genesis == blocks.get_block(@env, genesis.hash)
update_head genesis
raise "falied to update head" unless include?(genesis.hash)
commit
end
def store_block(block)
if block.number > 0
@db.put_temporarily block.hash, RLP.encode(block)
else
@db.put block.hash, RLP.encode(block)
end
end
def update_head_candidate(forward_pending_transaction=true)
logger.debug "updating head candidate head=#{head}"
blk = head # parent of the block we are collecting uncles for
uncles = get_brothers(blk).map(&:header).uniq
end
def get_brothers(blk)
end
end
end
|
module Viewpoint::EWS::Types
module Item
include Viewpoint::EWS
include Viewpoint::EWS::Types
include ItemFieldUriMap
def self.included(klass)
klass.extend ClassMethods
end
module ClassMethods
def init_simple_item(ews, id, change_key = nil, parent = nil)
ews_item = {item_id: {attribs: {id: id, change_key: change_key}}}
self.new ews, ews_item, parent
end
end
ITEM_KEY_PATHS = {
item_id: [:item_id, :attribs],
id: [:item_id, :attribs, :id],
change_key: [:item_id, :attribs, :change_key],
subject: [:subject, :text],
sensitivity: [:sensitivity, :text],
size: [:size, :text],
date_time_sent: [:date_time_sent, :text],
date_time_created: [:date_time_created, :text],
last_modified_time: [:last_modified_time, :text],
mime_content: [:mime_content, :text],
has_attachments?:[:has_attachments, :text],
is_associated?: [:is_associated, :text],
is_read?: [:is_read, :text],
is_draft?: [:is_draft, :text],
is_submitted?: [:is_submitted, :text],
conversation_id:[:conversation_id, :attribs, :id],
categories: [:categories, :elems],
internet_message_id:[:internet_message_id, :text],
internet_message_headers:[:internet_message_headers, :elems],
sender: [:sender, :elems, 0, :mailbox, :elems],
from: [:from, :elems, 0, :mailbox, :elems],
to_recipients: [:to_recipients, :elems],
cc_recipients: [:cc_recipients, :elems],
attachments: [:attachments, :elems],
importance: [:importance, :text],
conversation_index: [:conversation_index, :text],
conversation_topic: [:conversation_topic, :text],
body_type: [:body, :attribs, :body_type],
body: [:body, :text]
}
ITEM_KEY_TYPES = {
size: ->(str){str.to_i},
date_time_sent: ->(str){DateTime.parse(str)},
date_time_created: ->(str){DateTime.parse(str)},
last_modified_time: ->(str){DateTime.parse(str)},
has_attachments?: ->(str){str.downcase == 'true'},
is_associated?: ->(str){str.downcase == 'true'},
is_read?: ->(str){str.downcase == 'true'},
is_draft?: ->(str){str.downcase == 'true'},
is_submitted?: ->(str){str.downcase == 'true'},
categories: ->(obj){obj.collect{|s| s[:string][:text]}},
internet_message_headers: ->(obj){obj.collect{|h|
{h[:internet_message_header][:attribs][:header_name] =>
h[:internet_message_header][:text]} } },
sender: :build_mailbox_user,
from: :build_mailbox_user,
to_recipients: :build_mailbox_users,
cc_recipients: :build_mailbox_users,
attachments: :build_attachments,
}
ITEM_KEY_ALIAS = {
:read? => :is_read?,
:draft? => :is_draft?,
:submitted? => :is_submitted?,
:associated? => :is_associated?,
}
attr_reader :ews_item, :parent
# @param ews [SOAP::ExchangeWebService] the EWS reference
# @param ews_item [Hash] the EWS parsed response document
# @param parent [GenericFolder] an optional parent object
def initialize(ews, ews_item, parent = nil)
super(ews, ews_item)
@parent = parent
@body_type = false
simplify!
@new_file_attachments = []
@new_item_attachments = []
@new_inline_attachments = []
end
# Specify a body_type to fetch this item with if it hasn't already been fetched.
# @param body_type [String, Symbol, FalseClass] must be :best, :text, or
# :html. You can also set it to false to make it use the default.
def default_body_type=(body_type)
@body_type = body_type
end
def delete!(deltype = :hard, opts = {})
opts = {
:delete_type => delete_type(deltype),
:item_ids => [{:item_id => {:id => id}}]
}.merge(opts)
resp = @ews.delete_item(opts)
rmsg = resp.response_messages[0]
unless rmsg.success?
raise EwsError, "Could not delete #{self.class}. #{rmsg.response_code}: #{rmsg.message_text}"
end
true
end
def recycle!
delete! :recycle
end
def get_all_properties!
@ews_item = get_item(base_shape: 'AllProperties')
simplify!
end
# Mark an item as read
def mark_read!
update_is_read_status true
end
# Mark an item as unread
def mark_unread!
update_is_read_status false
end
# Move this item to a new folder
# @param [String,Symbol,GenericFolder] new_folder The new folder to move it to. This should
# be a subclass of GenericFolder, a DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @return [String] the new Id of the moved item
def move!(new_folder)
new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)
move_opts = {
:to_folder_id => {:id => new_folder},
:item_ids => [{:item_id => {:id => self.id}}]
}
resp = @ews.move_item(move_opts)
rmsg = resp.response_messages[0]
if rmsg.success?
obj = rmsg.items.first
itype = obj.keys.first
obj[itype][:elems][0][:item_id][:attribs][:id]
else
raise EwsError, "Could not move item. #{resp.code}: #{resp.message}"
end
end
# Copy this item to a new folder
# @param [String,Symbol,GenericFolder] new_folder The new folder to move it to. This should
# be a subclass of GenericFolder, a DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @return [String] the new Id of the copied item
def copy(new_folder)
new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)
copy_opts = {
:to_folder_id => {:id => new_folder},
:item_ids => [{:item_id => {:id => self.id}}]
}
resp = @ews.copy_item(copy_opts)
rmsg = resp.response_messages[0]
if rmsg.success?
obj = rmsg.items.first
itype = obj.keys.first
obj[itype][:elems][0][:item_id][:attribs][:id]
else
raise EwsError, "Could not copy item. #{rmsg.response_code}: #{rmsg.message_text}"
end
end
def add_file_attachment(file)
fa = OpenStruct.new
fa.name = File.basename(file.path)
fa.content = Base64.encode64(file.read)
@new_file_attachments << fa
end
def add_item_attachment(other_item, name = nil)
ia = OpenStruct.new
ia.name = (name ? name : other_item.subject)
ia.item = {id: other_item.id, change_key: other_item.change_key}
@new_item_attachments << ia
end
def add_inline_attachment(file)
fi = OpenStruct.new
fi.name = File.basename(file.path)
fi.content = Base64.encode64(file.read)
@new_inline_attachments << fi
end
def submit!
if draft?
submit_attachments!
resp = ews.send_item(item_ids: [{item_id: {id: self.id, change_key: self.change_key}}])
rm = resp.response_messages[0]
if rm.success?
true
else
raise EwsSendItemError, "#{rm.code}: #{rm.message_text}"
end
else
false
end
end
def submit_attachments!
return false unless draft? && !(@new_file_attachments.empty? && @new_item_attachments.empty? && @new_inline_attachments.empty?)
opts = {
parent_id: {id: self.id, change_key: self.change_key},
files: @new_file_attachments,
items: @new_item_attachments,
inline_files: @new_inline_attachments
}
resp = ews.create_attachment(opts)
set_change_key resp.response_messages[0].attachments[0].parent_change_key
@new_file_attachments = []
@new_item_attachments = []
@new_inline_attachments = []
end
# If you want to add to the body set #new_body_content. If you set #body
# it will override the body that is there.
# @see MessageAccessors#send_message for options
# additional options:
# :new_body_content, :new_body_type
# @example
# item.forward do |i|
# i.new_body_content = "Add this to the top"
# i.to_recipients << 'test@example.com'
# end
def forward(opts = {})
msg = Template::ForwardItem.new opts.clone
yield msg if block_given?
msg.reference_item_id = {id: self.id, change_key: self.change_key}
dispatch_create_item! msg
end
def reply_to(opts = {})
msg = Template::ReplyToItem.new opts.clone
yield msg if block_given?
msg.reference_item_id = {id: self.id, change_key: self.change_key}
dispatch_create_item! msg
end
def reply_to_all(opts = {})
msg = Template::ReplyToItem.new opts.clone
yield msg if block_given?
msg.reference_item_id = {id: self.id, change_key: self.change_key}
msg.ews_type = :reply_all_to_item
dispatch_create_item! msg
end
private
def key_paths
super.merge(ITEM_KEY_PATHS)
end
def key_types
super.merge(ITEM_KEY_TYPES)
end
def key_alias
super.merge(ITEM_KEY_ALIAS)
end
def update_is_read_status(read)
field = :is_read
opts = {item_changes:
[
{ item_id: {id: id, change_key: change_key},
updates: [
{set_item_field: {field_uRI: {field_uRI: FIELD_URIS[field][:text]},
message: {sub_elements: [{field => {text: read}}]}}}
]
}
]
}
resp = ews.update_item({conflict_resolution: 'AutoResolve'}.merge(opts))
rmsg = resp.response_messages[0]
unless rmsg.success?
raise EwsError, "#{rmsg.response_code}: #{rmsg.message_text}"
end
true
end
def simplify!
return unless @ews_item.has_key?(:elems)
@ews_item = @ews_item[:elems].inject({}) do |o,i|
key = i.keys.first
if o.has_key?(key)
if o[key].is_a?(Array)
o[key] << i[key]
else
o[key] = [o.delete(key), i[key]]
end
else
o[key] = i[key]
end
o
end
end
# Get a specific item by its ID.
# @param [Hash] opts Misc options to control request
# @option opts [String] :base_shape IdOnly/Default/AllProperties
# @raise [EwsError] raised when the backend SOAP method returns an error.
def get_item(opts = {})
args = get_item_args(opts)
resp = ews.get_item(args)
get_item_parser(resp)
end
# Build up the arguements for #get_item
# @todo: should we really pass the ChangeKey or do we want the freshest obj?
def get_item_args(opts)
opts[:base_shape] ||= 'Default'
default_args = {
item_shape: {base_shape: opts[:base_shape]},
item_ids: [{item_id:{id: id, change_key: change_key}}]
}
default_args[:item_shape][:body_type] = @body_type if @body_type
default_args
end
def get_item_parser(resp)
rm = resp.response_messages[0]
if(rm.status == 'Success')
rm.items[0].values.first
else
raise EwsError, "Could not retrieve #{self.class}. #{rm.code}: #{rm.message_text}"
end
end
# Map a delete type to what EWS expects
# @param [Symbol] type. Must be :hard, :soft, or :recycle
def delete_type(type)
case type
when :hard then 'HardDelete'
when :soft then 'SoftDelete'
when :recycle then 'MoveToDeletedItems'
else 'MoveToDeletedItems'
end
end
def build_deleted_occurrences(occurrences)
occurrences.collect{|a| DateTime.parse a[:deleted_occurrence][:elems][0][:start][:text]}
end
def build_modified_occurrences(occurrences)
{}.tap do |h|
occurrences.collect do |a|
elems = a[:occurrence][:elems]
h[DateTime.parse(elems.find{|e| e[:original_start]}[:original_start][:text])] = {
start: elems.find{|e| e[:start]}[:start][:text],
end: elems.find{|e| e[:end]}[:end][:text]
}
end
end
end
def build_mailbox_user(mbox_ews)
MailboxUser.new(ews, mbox_ews)
end
def build_mailbox_users(users)
return [] if users.nil?
users.collect{|u| build_mailbox_user(u[:mailbox][:elems])}
end
def build_attendees_users(users)
return [] if users.nil?
users.collect do |u|
u[:attendee][:elems].collect do |a|
return a[:response_type] if a[:response_type]
return a[:last_response_time] if a[:last_response_time]
return build_mailbox_user(a[:mailbox][:elems]) if a[:mailbox]
end
end.flatten.compact
end
def build_attachments(attachments)
return [] if attachments.nil?
attachments.collect do |att|
key = att.keys.first
class_by_name(key).new(self, att[key])
end
end
def set_change_key(ck)
p = resolve_key_path(ews_item, key_paths[:change_key][0..-2])
p[:change_key] = ck
end
# Handles the CreateItem call for Forward, ReplyTo, and ReplyAllTo
# It will handle the neccessary actions for adding attachments.
def dispatch_create_item!(msg)
if msg.has_attachments?
draft = msg.draft
msg.draft = true
resp = validate_created_item(ews.create_item(msg.to_ews))
msg.file_attachments.each do |f|
next unless f.kind_of?(File)
resp.add_file_attachment(f)
end
if draft
resp.submit_attachments!
resp
else
resp.submit!
end
else
resp = ews.create_item(msg.to_ews)
validate_created_item resp
end
end
# validate the CreateItem response.
# @return [Boolean, Item] returns true if items is empty and status is
# "Success" if items is not empty it will return the first Item since
# we are only dealing with single items here.
# @raise EwsCreateItemError on failure
def validate_created_item(response)
msg = response.response_messages[0]
if(msg.status == 'Success')
msg.items.empty? ? true : parse_created_item(msg.items.first)
else
raise EwsCreateItemError, "#{msg.code}: #{msg.message_text}"
end
end
def parse_created_item(msg)
mtype = msg.keys.first
message = class_by_name(mtype).new(ews, msg[mtype])
end
end
end
no message
module Viewpoint::EWS::Types
module Item
include Viewpoint::EWS
include Viewpoint::EWS::Types
include ItemFieldUriMap
def self.included(klass)
klass.extend ClassMethods
end
module ClassMethods
def init_simple_item(ews, id, change_key = nil, parent = nil)
ews_item = {item_id: {attribs: {id: id, change_key: change_key}}}
self.new ews, ews_item, parent
end
end
ITEM_KEY_PATHS = {
item_id: [:item_id, :attribs],
id: [:item_id, :attribs, :id],
change_key: [:item_id, :attribs, :change_key],
subject: [:subject, :text],
sensitivity: [:sensitivity, :text],
size: [:size, :text],
date_time_sent: [:date_time_sent, :text],
date_time_created: [:date_time_created, :text],
last_modified_time: [:last_modified_time, :text],
mime_content: [:mime_content, :text],
has_attachments?:[:has_attachments, :text],
is_associated?: [:is_associated, :text],
is_read?: [:is_read, :text],
is_draft?: [:is_draft, :text],
is_submitted?: [:is_submitted, :text],
conversation_id:[:conversation_id, :attribs, :id],
categories: [:categories, :elems],
internet_message_id:[:internet_message_id, :text],
internet_message_headers:[:internet_message_headers, :elems],
sender: [:sender, :elems, 0, :mailbox, :elems],
from: [:from, :elems, 0, :mailbox, :elems],
to_recipients: [:to_recipients, :elems],
cc_recipients: [:cc_recipients, :elems],
attachments: [:attachments, :elems],
importance: [:importance, :text],
conversation_index: [:conversation_index, :text],
conversation_topic: [:conversation_topic, :text],
body_type: [:body, :attribs, :body_type],
body: [:body, :text]
}
ITEM_KEY_TYPES = {
size: ->(str){str.to_i},
date_time_sent: ->(str){DateTime.parse(str)},
date_time_created: ->(str){DateTime.parse(str)},
last_modified_time: ->(str){DateTime.parse(str)},
has_attachments?: ->(str){str.downcase == 'true'},
is_associated?: ->(str){str.downcase == 'true'},
is_read?: ->(str){str.downcase == 'true'},
is_draft?: ->(str){str.downcase == 'true'},
is_submitted?: ->(str){str.downcase == 'true'},
categories: ->(obj){obj.collect{|s| s[:string][:text]}},
internet_message_headers: ->(obj){obj.collect{|h|
{h[:internet_message_header][:attribs][:header_name] =>
h[:internet_message_header][:text]} } },
sender: :build_mailbox_user,
from: :build_mailbox_user,
to_recipients: :build_mailbox_users,
cc_recipients: :build_mailbox_users,
attachments: :build_attachments,
}
ITEM_KEY_ALIAS = {
:read? => :is_read?,
:draft? => :is_draft?,
:submitted? => :is_submitted?,
:associated? => :is_associated?,
}
attr_reader :ews_item, :parent
# @param ews [SOAP::ExchangeWebService] the EWS reference
# @param ews_item [Hash] the EWS parsed response document
# @param parent [GenericFolder] an optional parent object
def initialize(ews, ews_item, parent = nil)
super(ews, ews_item)
@parent = parent
@body_type = false
simplify!
@new_file_attachments = []
@new_item_attachments = []
@new_inline_attachments = []
end
# Specify a body_type to fetch this item with if it hasn't already been fetched.
# @param body_type [String, Symbol, FalseClass] must be :best, :text, or
# :html. You can also set it to false to make it use the default.
def default_body_type=(body_type)
@body_type = body_type
end
def delete!(deltype = :hard, opts = {})
opts = {
:delete_type => delete_type(deltype),
:item_ids => [{:item_id => {:id => id}}]
}.merge(opts)
resp = @ews.delete_item(opts)
rmsg = resp.response_messages[0]
unless rmsg.success?
raise EwsError, "Could not delete #{self.class}. #{rmsg.response_code}: #{rmsg.message_text}"
end
true
end
def recycle!
delete! :recycle
end
def get_all_properties!
@ews_item = get_item(base_shape: 'AllProperties')
simplify!
end
# Mark an item as read
def mark_read!
update_is_read_status true
end
# Mark an item as unread
def mark_unread!
update_is_read_status false
end
# Move this item to a new folder
# @param [String,Symbol,GenericFolder] new_folder The new folder to move it to. This should
# be a subclass of GenericFolder, a DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @return [String] the new Id of the moved item
def move!(new_folder)
new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)
move_opts = {
:to_folder_id => {:id => new_folder},
:item_ids => [{:item_id => {:id => self.id}}]
}
resp = @ews.move_item(move_opts)
rmsg = resp.response_messages[0]
if rmsg.success?
obj = rmsg.items.first
itype = obj.keys.first
obj[itype][:elems][0][:item_id][:attribs][:id]
else
raise EwsError, "Could not move item. #{resp.code}: #{resp.message}"
end
end
# Copy this item to a new folder
# @param [String,Symbol,GenericFolder] new_folder The new folder to move it to. This should
# be a subclass of GenericFolder, a DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @return [String] the new Id of the copied item
def copy(new_folder)
new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)
copy_opts = {
:to_folder_id => {:id => new_folder},
:item_ids => [{:item_id => {:id => self.id}}]
}
resp = @ews.copy_item(copy_opts)
rmsg = resp.response_messages[0]
if rmsg.success?
obj = rmsg.items.first
itype = obj.keys.first
obj[itype][:elems][0][:item_id][:attribs][:id]
else
raise EwsError, "Could not copy item. #{rmsg.response_code}: #{rmsg.message_text}"
end
end
def add_file_attachment(file)
fa = OpenStruct.new
fa.name = File.basename(file.path)
fa.content = Base64.encode64(file.read)
@new_file_attachments << fa
end
def add_item_attachment(other_item, name = nil)
ia = OpenStruct.new
ia.name = (name ? name : other_item.subject)
ia.item = {id: other_item.id, change_key: other_item.change_key}
@new_item_attachments << ia
end
def add_inline_attachment(file)
fi = OpenStruct.new
fi.name = File.basename(file.path)
fi.content = Base64.encode64(file.read)
@new_inline_attachments << fi
end
def submit!
if draft?
submit_attachments!
resp = ews.send_item(item_ids: [{item_id: {id: self.id, change_key: self.change_key}}])
rm = resp.response_messages[0]
if rm.success?
true
else
raise EwsSendItemError, "#{rm.code}: #{rm.message_text}"
end
else
false
end
end
def submit_attachments!
return false unless draft? && !(@new_file_attachments.empty? && @new_item_attachments.empty? && @new_inline_attachments.empty?)
opts = {
parent_id: {id: self.id, change_key: self.change_key},
files: @new_file_attachments,
items: @new_item_attachments,
inline_files: @new_inline_attachments
}
resp = ews.create_attachment(opts)
set_change_key resp.response_messages[0].attachments[0].parent_change_key
@new_file_attachments = []
@new_item_attachments = []
@new_inline_attachments = []
end
# If you want to add to the body set #new_body_content. If you set #body
# it will override the body that is there.
# @see MessageAccessors#send_message for options
# additional options:
# :new_body_content, :new_body_type
# @example
# item.forward do |i|
# i.new_body_content = "Add this to the top"
# i.to_recipients << 'test@example.com'
# end
def forward(opts = {})
msg = Template::ForwardItem.new opts.clone
yield msg if block_given?
msg.reference_item_id = {id: self.id, change_key: self.change_key}
dispatch_create_item! msg
end
def reply_to(opts = {})
msg = Template::ReplyToItem.new opts.clone
yield msg if block_given?
msg.reference_item_id = {id: self.id, change_key: self.change_key}
dispatch_create_item! msg
end
def reply_to_all(opts = {})
msg = Template::ReplyToItem.new opts.clone
yield msg if block_given?
msg.reference_item_id = {id: self.id, change_key: self.change_key}
msg.ews_type = :reply_all_to_item
dispatch_create_item! msg
end
private
def key_paths
super.merge(ITEM_KEY_PATHS)
end
def key_types
super.merge(ITEM_KEY_TYPES)
end
def key_alias
super.merge(ITEM_KEY_ALIAS)
end
def update_is_read_status(read)
field = :is_read
opts = {item_changes:
[
{ item_id: {id: id, change_key: change_key},
updates: [
{set_item_field: {field_uRI: {field_uRI: FIELD_URIS[field][:text]},
message: {sub_elements: [{field => {text: read}}]}}}
]
}
]
}
resp = ews.update_item({conflict_resolution: 'AutoResolve'}.merge(opts))
rmsg = resp.response_messages[0]
unless rmsg.success?
raise EwsError, "#{rmsg.response_code}: #{rmsg.message_text}"
end
true
end
def simplify!
return unless @ews_item.has_key?(:elems)
@ews_item = @ews_item[:elems].inject({}) do |o,i|
key = i.keys.first
if o.has_key?(key)
if o[key].is_a?(Array)
o[key] << i[key]
else
o[key] = [o.delete(key), i[key]]
end
else
o[key] = i[key]
end
o
end
end
# Get a specific item by its ID.
# @param [Hash] opts Misc options to control request
# @option opts [String] :base_shape IdOnly/Default/AllProperties
# @raise [EwsError] raised when the backend SOAP method returns an error.
def get_item(opts = {})
args = get_item_args(opts)
resp = ews.get_item(args)
get_item_parser(resp)
end
# Build up the arguements for #get_item
# @todo: should we really pass the ChangeKey or do we want the freshest obj?
def get_item_args(opts)
opts[:base_shape] ||= 'Default'
default_args = {
item_shape: {base_shape: opts[:base_shape]},
item_ids: [{item_id:{id: id, change_key: change_key}}]
}
default_args[:item_shape][:body_type] = @body_type if @body_type
default_args
end
def get_item_parser(resp)
rm = resp.response_messages[0]
if(rm.status == 'Success')
rm.items[0].values.first
else
raise EwsError, "Could not retrieve #{self.class}. #{rm.code}: #{rm.message_text}"
end
end
# Map a delete type to what EWS expects
# @param [Symbol] type. Must be :hard, :soft, or :recycle
def delete_type(type)
case type
when :hard then 'HardDelete'
when :soft then 'SoftDelete'
when :recycle then 'MoveToDeletedItems'
else 'MoveToDeletedItems'
end
end
def build_deleted_occurrences(occurrences)
occurrences.collect{|a| DateTime.parse a[:deleted_occurrence][:elems][0][:start][:text]}
end
def build_modified_occurrences(occurrences)
{}.tap do |h|
occurrences.collect do |a|
elems = a[:occurrence][:elems]
h[DateTime.parse(elems.find{|e| e[:original_start]}[:original_start][:text])] = {
start: elems.find{|e| e[:start]}[:start][:text],
end: elems.find{|e| e[:end]}[:end][:text]
}
end
end
end
def build_mailbox_user(mbox_ews)
MailboxUser.new(ews, mbox_ews)
end
def build_mailbox_users(users)
return [] if users.nil?
users.collect{|u| build_mailbox_user(u[:mailbox][:elems])}
end
def build_attendees_users(users)
return [] if users.nil?
users.collect do |u|
u[:attendee][:elems].collect do |a|
# return a[:response_type] if a[:response_type]
# return a[:last_response_time] if a[:last_response_time]
build_mailbox_user(a[:mailbox][:elems]) if a[:mailbox]
end
end.flatten.compact
end
def build_attachments(attachments)
return [] if attachments.nil?
attachments.collect do |att|
key = att.keys.first
class_by_name(key).new(self, att[key])
end
end
def set_change_key(ck)
p = resolve_key_path(ews_item, key_paths[:change_key][0..-2])
p[:change_key] = ck
end
# Handles the CreateItem call for Forward, ReplyTo, and ReplyAllTo
# It will handle the neccessary actions for adding attachments.
def dispatch_create_item!(msg)
if msg.has_attachments?
draft = msg.draft
msg.draft = true
resp = validate_created_item(ews.create_item(msg.to_ews))
msg.file_attachments.each do |f|
next unless f.kind_of?(File)
resp.add_file_attachment(f)
end
if draft
resp.submit_attachments!
resp
else
resp.submit!
end
else
resp = ews.create_item(msg.to_ews)
validate_created_item resp
end
end
# validate the CreateItem response.
# @return [Boolean, Item] returns true if items is empty and status is
# "Success" if items is not empty it will return the first Item since
# we are only dealing with single items here.
# @raise EwsCreateItemError on failure
def validate_created_item(response)
msg = response.response_messages[0]
if(msg.status == 'Success')
msg.items.empty? ? true : parse_created_item(msg.items.first)
else
raise EwsCreateItemError, "#{msg.code}: #{msg.message_text}"
end
end
def parse_created_item(msg)
mtype = msg.keys.first
message = class_by_name(mtype).new(ews, msg[mtype])
end
end
end
|
#!/usr/bin/ruby
require 'cgi'
require 'rest_client'
require 'json'
# The category of the results, 09 - for australian sites
_c = '09'
# number of results per page, i.e. how many results will be returned
_ps = 10
# result page number, starting with 0
_np = 0
# synonyms use flag, 1 - to use, 0 - don't
_sy = 0
# word forms use flag, 1 - to use, 0 - don't (search for words in query exactly)
_sp = 1
# search mode, can be 'near', 'all', 'any'
_m = 'near'
# results groupping by site flag, 'yes' - to group, 'no' - don't
_GroupBySite = 'no'
# search result template
_tmplt = 'json2.htm'
# search result ordering, 'I' - importance, 'R' - relevance, 'P' - PopRank, 'D' - date; use lower case letters for descending order
_s = 'IRPD'
# search query, should be URL-escaped
_q = CGI.escape('careers')
response = RestClient.get('http://inet-sochi.ru:7003/', {:params => {
:c => _c,
:ps => _ps,
:np => _np,
:sy => _sy,
:sp => _sp,
:m => _m,
'GroupBysite' => _GroupBySite,
:tmplt => _tmplt,
:s => 'IRPD',
:q => _q
}}){ |response, request, result, &block|
case response.code
when 200
# p "It worked !"
response
when 423
raise SomeCustomExceptionIfYouWant
else
response.return!(request, result, &block)
end
}
result = JSON.parse(response)
result['responseData']['results'].each { |pos|
print "#{pos['title']}\n => #{pos['url']}\n\n"
}
print " ** Total #{result['responseData']['found']} documents found in #{result['responseData']['time']} sec."
print " Displaying documents #{result['responseData']['first']}-#{result['responseData']['last']}.\n"
use variable for sorting parameter
#!/usr/bin/ruby
require 'cgi'
require 'rest_client'
require 'json'
# The category of the results, 09 - for australian sites
_c = '09'
# number of results per page, i.e. how many results will be returned
_ps = 10
# result page number, starting with 0
_np = 0
# synonyms use flag, 1 - to use, 0 - don't
_sy = 0
# word forms use flag, 1 - to use, 0 - don't (search for words in query exactly)
_sp = 1
# search mode, can be 'near', 'all', 'any'
_m = 'near'
# results groupping by site flag, 'yes' - to group, 'no' - don't
_GroupBySite = 'no'
# search result template
_tmplt = 'json2.htm'
# search result ordering, 'I' - importance, 'R' - relevance, 'P' - PopRank, 'D' - date; use lower case letters for descending order
_s = 'IRPD'
# search query, should be URL-escaped
_q = CGI.escape('careers')
response = RestClient.get('http://inet-sochi.ru:7003/', {:params => {
:c => _c,
:ps => _ps,
:np => _np,
:sy => _sy,
:sp => _sp,
:m => _m,
'GroupBysite' => _GroupBySite,
:tmplt => _tmplt,
:s => _s,
:q => _q
}}){ |response, request, result, &block|
case response.code
when 200
# p "It worked !"
response
when 423
raise SomeCustomExceptionIfYouWant
else
response.return!(request, result, &block)
end
}
result = JSON.parse(response)
result['responseData']['results'].each { |pos|
print "#{pos['title']}\n => #{pos['url']}\n\n"
}
print " ** Total #{result['responseData']['found']} documents found in #{result['responseData']['time']} sec."
print " Displaying documents #{result['responseData']['first']}-#{result['responseData']['last']}.\n"
|
##
# Yet Another Window Message with Portrait
# Esphas
#
# v4.2.1 2018.04.08 ...and Interactive.weaken_type now supports variable
# v4.2.0 2018.04.08 new features: change dialog skin according to character name
# & new interactive weaken type: exit
# v4.1.3 2018.04.05 shakes will abort when message ends
# v4.1.2 2018.04.02 bug fix: anime --x--> face image
# v4.1.1 2018.04.01 new feature: when missing portrait, use face image instead
# v4.1.0 2018.04.01 happy fool's day! I decide to change the version number to
# v4.1.0, but actually not much changes are made:
# a fix to a vallana bug;
# portrait offset;
# shake control improvments.
# v3.0.0 2017.12.31 alright, shake overhaul, compatible with v2.0
# v2.2.0 2017.12.31 new feature: shakes now supports up to 4 parameters
# v2.1.0 2017.12.31 new features: shake dialog, play SE
# v2.0.1 2017.10.18 fixed bugs displaying wrong dialog skin
# v2.0.0 2017.07.21 release
#
# https://github.com/ShadowMomo/Smomo-RGSS-Scripts/blob/master/Single/YAWMP.rb
# https://rpg.blue/forum.php?mod=viewthread&tid=401822
##
# 前置
# Interactive.weaken_type.dim 需要 Bitmap#change_tone
# 说人话的话,如果交互对话时采取的弱化效果是变暗,
# 那么就需要提供 Bitmap 类的 change_tone 方法
# # 已知的提供方
# * TKTK_Bitmap
# http://www.tktkgame.com/tkool/rgss_common/files/tktk_bitmap.zip
module Cache
##
# 存放立绘的位置
PortraitFolder = 'Graphics/Faces/Large/'
def self.generate_portrait_filename name, index, frame
##
# 生成文件名的规则
filename = "#{name}_L#{index}"
filename = "#{filename}_#{frame}" if frame > 0
filename
end
end
class Window_ChoiceList
##
# 用于修复一个原生 bug:显示选项时使用图标造成的长度不当
# 如果你已经使用了其他修复手段,那么请将下方标注的 true 改为 false
def max_choice_width
$game_message.choices.collect do |s|
s = convert_escape_characters s
height = calc_line_height s
pos = {x: 0, y: -Graphics.height, new_x: 0, height: height}
process_character(s.slice!(0, 1), s, pos) until s.empty?
pos[:x]
end.max
end if true ## 此处标注
end
class Window_Message
##
# 主设定区
# 所有开关 ID,若设为 0,则认为对应的值为开关关闭
# 所有变量 ID,若设为 0,则认为对应的值为 0
##
# Skin
# basename: 对话框皮肤的基础文件名
# var: 表示具体使用几号皮肤的变量
# # 皮肤文件位于 Graphics/System
# # 命名格式为 basename+var,例如 dialog1,dialog4,
# # var 为零时省略:dialog 而不是 dialog0
# # 如果文件不存在,就使用默认的窗体而不是对话框
Skin = {
basename: 'dialog',
var: 81
}
##
# Portrait
# on_the_right_switch: 开关打开时,立绘首先显示在右边
# left_mirror_switch: 开关打开时,在左边的立绘会镜像
# right_mirror_switch: 开关打开时,在右边的立绘会镜像
# under_dialogbox_switch: 开关打开时,立绘重叠次序在对话框下方
Portrait = {
on_the_right_switch: 81,
left_mirror_switch: 82,
right_mirror_switch: 83,
under_dialogbox_switch: 84
}
##
# Name
# disable_switch: 开关打开时,不把第一行文字识别为名字
# deco: 有两个字符串的数组,名字会放置在这两个字符串中间
# color: 名字的颜色
# default: 默认颜色
# face: 按脸图文件名判断的特殊颜色
# 'abc' => 4: 文件名以 abc 开头的脸图的名字使用 4 号颜色
# # 字母不区分大小写
# name: 按文字字面判断的特殊颜色
# '路人' => 3: 以 路人 开头的名字用 3 号颜色,比如路人甲之类
# # 字母区分大小写
# # 优先依据脸图的判断结果,脸图无匹配的情况采用字面匹配
# # 均无匹配才使用默认颜色
# indent: 正文的缩进量,以半角空格为单位
Name = {
disable_switch: 85,
deco: ['【', '】'],
color: {
default: 6,
face: {
'Agn' => 2,
'def' => 7,
'Gal' => 5,
},
name: {
'路人' => 3,
}
},
indent: 2
}
##
# Fading
# dialogbox_in: 对话框淡入需要的时间
# dialogbox_out: 对话框淡出需要的时间
# portrait_in: 立绘淡入需要的时间
# portrait_out: 立绘淡出需要的时间
# portrait_dist: 立绘淡入滑动的距离
# together: 淡入效果是否可以同时进行
Fading = {
dialogbox_in: 10,
dialogbox_out: 10,
portrait_in: 15,
portrait_out: 15,
portrait_dist: 30,
together: false
}
##
# Anime
# disable_switch: 开关打开时,完全禁用动画效果
# interval_var: 表示帧与帧之间间隔的变量
# repeat_var: 表示动画最多播放次数的变量
# # 若为零,则一直重播
# stop_var: 表示动画最终应该停留的帧序数的变量
# # 帧序数从零开始
# # 若变量值超过动画最大帧数,则停留在第一帧
# repeat_inteval_var: 两个变量
# # 第一个为表示动画重播之间等待的时间的变量
# # 第二个为表示等待时间波动范围的变量
# # 实际等待时间在 var1 ± var2 内
# # 第一次播放之前也会等待
Anime = {
disable_switch: 86,
interval_var: 82,
repeat_var: 83,
stop_var: 84,
repeat_inteval_var: [85, 86]
}
##
# Offset
# portrait_x_back: X 方向向后方(立绘在左即左方,在右即右方)的偏移量
# portrait_y_down: Y 方向向下的偏移量
# face_side_left: 无立绘时,脸图在左侧时的侧边距
# face_side_right: 无立绘时,脸图在右侧时的侧边距
# face_bottom: 无立绘时脸图的下边距
# text_without_face: 没有立绘时的文本左偏移量
# text_with_face: 有立绘时的文本左偏移量
Offset = {
portrait_x_back: 0,
portrait_y_down: 0,
face_side_left: 20,
face_side_right: 20,
face_bottom: 12,
text_without_face: 40,
text_with_face: 10
}
##
# Interactive
# enable_switch: 开关打开时,启用交互对话模式
# host_mode_switch: 开关打开时,交互对话模式有一个主角
# weaken_time: 立绘弱化所需要的帧数
# weaken_type: 立绘弱化的类型
# # :dim 变暗
# # :opacity 透明
# # :blur 模糊
# # :exit 退出画面
# # 数字则表示变量,变量的值依次为 0 1 2 ... 时表示采用对应的上述方式
# weaken_rate: 立绘弱化的程度
# # 变暗时,0 为不变,255 为全黑
# # 透明时,0 为不变,255 为完全透明
# # 模糊不受影响
# down_pixel: 立绘弱化时的下移量
# back_pixel: 立绘弱化时的后移量
Interactive = {
enable_switch: 87,
host_mode_switch: 88,
weaken_time: 10,
weaken_type: 0,
weaken_rate: 100,
down_pixel: 0,
back_pixel: 10
}
##
# Text
# character_wait_var: 表示两个字符之间等待时间的变量
# # 超过 15 按 15 处理
# escape: 控制符
# shake: 抖动立绘,参数:抖动对象,半周期,次数,幅度
# # 缺省参数为 x,5,3,5
# # 抖动对象:x 或 y 或 opacity(不透明度)
# # 半周期(帧)和次数(次)和幅度顾名思义
# # 幅度的单位是像素(对于 x 和 y)或者取值0~255(对于 opacity)
# # 例:【\d】【\d[x,10]】【\d[y,7,6,-15]】【\d[opacity,30,6,128]】
# shake_dialog: 抖动对话框
# # 参数配置同 shake
# wait_for_shake_complete: 等待抖动完成
# switch: 切换立绘,参数为立绘图编号或全称,如【\S[6]】【\S[AgnesC_L0]】
# se: 播放音效(SE),参数为音效文件名,不带拓展名,如【\X[Absorb1]】
# # 也可以带上一个额外参数表示音量,如【\X[Absorb1,100]】
# # 还可再带一个额外参数表示音调,如【\X[Absorb1,100,150]】
# # 控制符必须是单个字符,不区分大小写
Text = {
character_wait_var: 87,
escape: {
shake: 'D',
shake_dialog: 'Z',
wait_for_shake_complete: 'W',
switch: 'S',
se: 'X'
}
}
##
# Misc
# comp: 识别同一角色时比较前多少个字母
# # 字母不区分大小写
# adjust_choice_switch: 开关打开时,选项显示在立绘的另一侧
# name_with_skin: 根据角色名字或文件名自动换对话框皮肤
# revert: 自动更换之后,是否在此对话结束时换回原皮肤
# face: 按脸图文件名判断皮肤
# 'abc' => 4: 文件名以 abc 开头的脸图使用 4 号皮肤
# # 字母不区分大小写
# name: 按文字字面判断皮肤
# '路人' => 3: 以 路人 开头的名字用 3 号皮肤,比如路人甲之类
# # 字母区分大小写
# # 当 Name.diable_switch 打开,即禁用第一行识别为名字时,此处设置不生效
# # 优先依据脸图的判断结果,脸图无匹配的情况采用字面匹配
# # 均无匹配才使用 Skin.var 指定的皮肤
Misc = {
comp: 3,
adjust_choice_switch: 89,
name_with_skin: {
revert: true,
face: {
'Agn' => 2,
'def' => 3,
'Gal' => 5,
},
name: {
'路人' => 1,
}
}
}
##
# ErrorMessage
# 错误信息
ErrorMessage = {
invalid_switch: '无效的切换,只支持切换同一角色的立绘!'
}
'Edit Anything Below At Your Own Risk'
'Edit Anything Below At Your Own Risk'
'Edit Anything Below At Your Own Risk'
module SpriteContainer
def clear_shake
@shake = { x: [], y: [], opacity: [] }
end
def abort_shake
clear_shake
update_shake
end
def shaking?
!@shake.values.all?(&:empty?)
end
def update_shake
@sprite.ox = @shake[:x].pop || 0
@sprite.oy = @shake[:y].pop || 0
@sprite.opacity = @shake[:opacity].pop || 255
end
def start_shake param
type, halfperiod, count, amplitude = param.split ','
type = (type || :x).downcase.to_sym
halfperiod = (halfperiod || 5).to_i
count = (count || 3).to_i
amplitude = (amplitude || 5).to_i
if type == :opacity
list = shaker1d halfperiod, count, amplitude, &Math.method(:cos)
list.map!{ |v| v + 255 - amplitude }
else
list = shaker1d halfperiod, count, amplitude, &Math.method(:sin)
end
@shake[type] = list
end
def shaker1d halfperiod, count, amplitude
period = 2*halfperiod
list = period.times.map do |p|
amplitude*yield(2*Math::PI*p/period)
end
list*count
end
end
class DialogBox
include SpriteContainer
attr_accessor :state
attr_accessor :override_skin
def get_game_variable id, default
id.zero? ? default : $game_variables[id]
end
def initialize
@sprite = Sprite.new
@sprite.opacity = 0
@state = nil
@override_skin = nil
@update_frame_count = 0
load_skin
clear_shake
end
def load_skin
skin = Skin[:basename]
index = @override_skin || get_game_variable(Skin[:var], 0)
@override_skin = nil
$game_variables[Skin[:var]] = index unless Misc[:name_with_skin][:revert]
skin = "#{skin}#{index}" if index > 0
@sprite.bitmap = Cache.system skin
@valid = true
rescue Errno::ENOENT
@valid = false
end
def valid?
@valid
end
%w[x y z visible].each do |prop|
define_method "#{prop}=" do |value|
@sprite.send "#{prop}=", value
end
end
%w[x y z visible width height].each do |prop|
define_method prop do
@sprite.send prop
end
end
def update
case @state
when :fading_in
@update_frame_count += 1
do_fading_in
state_end = @update_frame_count >= Fading[:dialogbox_in]
when :fading_out
@update_frame_count += 1
do_fading_out
state_end = @update_frame_count >= Fading[:dialogbox_out]
else
if shaking?
update_shake
end
end
if state_end
@update_frame_count = 0
@state = nil
end
@sprite.update
end
def transitioning?
not @state.nil?
end
def do_fading_in
return if @sprite.opacity == 255
progress = @update_frame_count.to_f / Fading[:dialogbox_in]
@sprite.opacity = 255 * progress
end
def do_fading_out
return if @sprite.opacity == 0
progress = @update_frame_count.to_f / Fading[:dialogbox_out]
@sprite.opacity = 255 - 255 * progress
end
def dispose
@sprite.dispose
end
def disposed?
@sprite.disposed?
end
end
class PortraitFrame
include SpriteContainer
attr_reader :face_name
attr_reader :face_index
attr_reader :guest
attr_reader :right
attr_accessor :state
def inspect
"<PortraitFrame: #{@face_name}_L#{@face_index}_#{@frame}*#{@state}>"
end
def get_game_variable id, default
id.zero? ? default : $game_variables[id]
end
def get_game_switch id
id.zero? ? false : $game_switches[id]
end
def weaken_type
wt = Interactive[:weaken_type]
if wt.is_a? Symbol
wt
else
[:dim, :opacity, :blur, :exit][get_game_variable(wt, 0)]
end
end
def initialize face_name, face_index, guest = false
@face_name = face_name
@face_index = face_index
@guest = guest
@sprite = Sprite.new
@helper = Sprite.new
@sprite.opacity = @helper.opacity = 0
@state = :fading_in
@update_frame_count = 0
@weakened = false
reset_anime
clear_shake
right!
end
def right!
@right = get_game_switch Portrait[:on_the_right_switch]
@right = !@right if @guest
mirror = @right ? :right_mirror_switch : :left_mirror_switch
@sprite.mirror = get_game_switch Portrait[mirror]
load_portrait
end
def load_portrait
@sprite.bitmap = Cache.portrait @face_name, @face_index, @frame, @right
prepare_helper
adjust_placement
end
def adjust_placement
if @right
self.x = Graphics.width - width + Offset[:portrait_x_back]
self.x += Interactive[:back_pixel] if weakened?
else
self.x = -Offset[:portrait_x_back]
self.x -= Interactive[:back_pixel] if weakened?
end
self.y = Graphics.height - height + Offset[:portrait_y_down]
self.y += Interactive[:down_pixel] if weakened?
end
def hotload face_name, face_index
reset_anime
@face_name = face_name
@face_index = face_index
load_portrait
end
def reset_anime
@frame = 0
@anime_frame_count = 0
@anime_repeat_count = 0
@anime_repeat_interval = anime_repeat_interval
@wait_for_repeat = true
end
def prepare_helper
@helper.mirror = @sprite.mirror
case weaken_type
when :dim
@helper.bitmap = get_portrait_dim
when :opacity
when :blur
@helper.bitmap = get_portrait_blur
when :exit
end
end
def same_character? face_name
@face_name[0, Misc[:comp]].downcase == face_name[0, Misc[:comp]].downcase
end
%w[x y z].each do |prop|
define_method "#{prop}=" do |value|
@sprite.send "#{prop}=", value
@helper.send "#{prop}=", value
end
end
%w[x y z width height].each do |prop|
define_method prop do
@sprite.send prop
end
end
def update
case @state
when :fading_in
@update_frame_count += 1
do_fading_in
if @update_frame_count >= Fading[:portrait_in]
@update_frame_count = 0
@state = nil
end
when :fading_out
@update_frame_count += 1
do_fading_out
if @update_frame_count >= Fading[:portrait_out]
dispose
end
when :weakening
@update_frame_count += 1
do_weakening
if @update_frame_count >= Interactive[:weaken_time]
@update_frame_count = 0
@state = nil
@weakened = true
end
when :strengthening
@update_frame_count += 1
do_strengthening
if @update_frame_count >= Interactive[:weaken_time]
@update_frame_count = 0
@state = nil
@weakened = false
end
else
if shaking?
update_shake
else
update_anime unless anime_disabled?
end
end
return if disposed?
@sprite.update
@helper.update
end
def transitioning?
not @state.nil?
end
def weakened?
@weakened
end
def do_fading_in
return if @sprite.opacity == 255
progress = @update_frame_count.to_f / Fading[:portrait_in]
@sprite.opacity = 255 * progress
if @right
target = Graphics.width - width
origin = target + Fading[:portrait_dist]
else
target = 0
origin = target - Fading[:portrait_dist]
end
self.x = progress * target + (1-progress) * origin
end
def do_fading_out
sprite = weakened? ? @helper : @sprite
return if sprite.opacity == 0
progress = @update_frame_count.to_f / Fading[:portrait_out]
sprite.opacity = 255 - 255 * progress
if @right
origin = Graphics.width - width
origin += Interactive[:back_pixel] if weakened?
target = origin + Fading[:portrait_dist]
else
origin = 0
origin -= Interactive[:back_pixel] if weakened?
target = origin - Fading[:portrait_dist]
end
self.x = progress * target + (1-progress) * origin
end
def get_portrait_dim
dimness = Interactive[:weaken_rate]
Cache.portrait_dim @face_name, @face_index, @frame, @right, dimness
end
def get_portrait_blur
Cache.portrait_blur @face_name, @face_index, @frame, @right
end
def do_weakening
if weaken_type == :exit
return @state = :fading_out
end
return if weakened?
progress = @update_frame_count.to_f / Interactive[:weaken_time]
case weaken_type
when :dim
blending_civet_cat_and_prince_edward progress
when :opacity
@sprite.opacity = 255 - Interactive[:weaken_rate] * progress
when :blur
blending_civet_cat_and_prince_edward progress
end
if @right
originx = Graphics.width - width
targetx = originx + Interactive[:back_pixel]
else
originx = 0
targetx = originx - Interactive[:back_pixel]
end
originy = Graphics.height - height
targety = originy + Interactive[:down_pixel]
self.x = progress * targetx + (1-progress) * originx
self.y = progress * targety + (1-progress) * originy
end
def do_strengthening
return unless weakened?
progress = @update_frame_count.to_f / Interactive[:weaken_time]
case weaken_type
when :dim
blending_civet_cat_and_prince_edward 1-progress
when :opacity
@sprite.opacity = 255 - Interactive[:weaken_rate] * (1 - progress)
when :blur
blending_civet_cat_and_prince_edward 1-progress
end
if @right
targetx = Graphics.width - width
originx = targetx + Interactive[:back_pixel]
else
targetx = 0
originx = targetx - Interactive[:back_pixel]
end
targety = Graphics.height - height
originy = targety + Interactive[:down_pixel]
self.x = progress * targetx + (1-progress) * originx
self.y = progress * targety + (1-progress) * originy
end
def blending_civet_cat_and_prince_edward progress
@helper.opacity = 255 * progress
@sprite.opacity = 255 - 128 * progress
end
def anime_disabled?
get_game_switch Anime[:disable_switch]
end
def update_anime
return if anime_limit_reached?
@anime_frame_count += 1
if @wait_for_repeat
if @anime_frame_count >= @anime_repeat_interval
@wait_for_repeat = false
end
elsif @anime_frame_count >= anime_frame_interval
@anime_frame_count = 0
@frame += 1
unless load_next_frame
@frame = 0
@anime_repeat_count += 1
@wait_for_repeat = true
@anime_repeat_interval = anime_repeat_interval
load_next_frame
end
end
end
def anime_limit_reached?
stop_var = get_game_variable Anime[:stop_var], 0
repeat_var = get_game_variable Anime[:repeat_var], 0
repeat_var = Float::INFINITY if repeat_var.zero?
@anime_repeat_count == repeat_var && @frame >= stop_var ||
@anime_repeat_count > repeat_var
end
def anime_frame_interval
interval = get_game_variable Anime[:interval_var], 0
interval = 5 if interval.zero?
interval
end
def anime_repeat_interval
interval = get_game_variable Anime[:repeat_inteval_var][0], 0
interval = 120 if interval.zero?
range = get_game_variable Anime[:repeat_inteval_var][1], 0
interval += rand(range*2) - range
interval
end
def load_next_frame
file = Cache.generate_portrait_filename @face_name, @face_index, @frame
file = Cache::PortraitFolder + file
if %w[.png .jpg .bmp].any?{ |ext| FileTest.exist? file + ext }
load_portrait
return true
else
return false
end
end
def dispose
@helper.dispose
@sprite.dispose
end
def disposed?
@sprite.disposed?
end
end
def get_game_variable id, default
id.zero? ? default : $game_variables[id]
end
def get_game_switch id
id.zero? ? false : $game_switches[id]
end
alias :yawmp_initialize :initialize
def initialize
yawmp_initialize
create_dialogbox
create_portraits
end
alias :yawmp_create_all_windows :create_all_windows
def create_all_windows
yawmp_create_all_windows
@gold_window.z =
@choice_window.z =
@number_window.z =
@item_window.z = z+10
end
def create_dialogbox
@dialogbox = DialogBox.new
@dialogbox.z = z-1
end
def create_portraits
@portraits = []
@active_portraits = []
end
def portraits_under_dialog?
get_game_switch Portrait[:under_dialogbox_switch]
end
alias :yawmp_clear_flags :clear_flags
def clear_flags
yawmp_clear_flags
clear_portrait_flags
end
def clear_portrait_flags
@first_time_window_open = true
end
alias :yawmp_dispose :dispose
def dispose
yawmp_dispose
dispose_dialog
dispose_portraits
end
def dispose_dialog
@dialogbox.dispose
end
def dispose_portraits
@portraits.each &:dispose
end
alias :yawmp_update :update
def update
yawmp_update
update_dialog
update_portraits
end
def update_dialog
if !Fading[:together] && portraits_transitioning?
return unless (@dialogbox.state == :fading_in) ^ portraits_under_dialog?
end
@dialogbox.update
end
def update_portraits
if !Fading[:together] && dialog_transitioning?
return unless (@dialogbox.state == :fading_in) ^ !portraits_under_dialog?
end
return unless has_portrait?
return if adjust_choice? && @choice_window.active
first = @active_portraits.first
while @portraits[first].disposed?
@portraits[first] = nil
@portraits.compact!
@active_portraits.delete first
@active_portraits.map! do |value|
value > first ? value-1 : value
end
return if @portraits.size.zero?
first = @active_portraits.first
end
if @portraits[first].weakened? && @portraits[first].state.nil?
weakened = @active_portraits.shift
@active_portraits.push weakened
end
@portraits[@active_portraits.first].update
end
def dialog_transitioning?
@dialogbox.transitioning?
end
def portraits_transitioning?
return false if @portraits.size.zero?
@portraits[@active_portraits.first].transitioning?
end
def transitioning?
dialog_transitioning? || portraits_transitioning?
end
def interactive_mode?
get_game_switch Interactive[:enable_switch]
end
def host_mode?
get_game_switch Interactive[:host_mode_switch]
end
def portrait_alone?
@active_portraits.size == 1
end
def current_is_host?
!@portraits[@active_portraits.first].guest
end
def update_background
@background = $game_message.background
@dialogbox.load_skin
update_dialog_validation
end
def update_dialog_validation
if @dialogbox.valid?
@dialogbox.visible = @background.zero?
self.opacity = 0
else
@dialogbox.visible = false
self.opacity = @background.zero? ? 255 : 0
end
end
alias :yawmp_update_placement :update_placement
def update_placement
yawmp_update_placement
@dialogbox.y = @position * (Graphics.height - @dialogbox.height) / 2
end
def adjust_placement
@portraits.each &:right!
end
def refresh_portraits
Fiber.yield while transitioning?
adjust_placement
validate_portraits
update_portraits_z
end
def update_portraits_z
@portraits.each do |portrait|
portrait.z = z-1 + (portraits_under_dialog? ? -1 : 1)
end
end
def face_changed?
portrait = @portraits[@active_portraits.first]
portrait.face_name != $game_message.face_name ||
portrait.face_index != $game_message.face_index
end
def has_portrait?
!@active_portraits.size.zero?
end
def has_portrait_in_left?
@portraits.any? do |portrait|
!portrait.right
end
end
def validate_portraits
return create_first_portrait unless has_portrait?
return unless face_changed?
if interactive_mode?
validate_interactive_mode
else
validate_basic_mode
end
end
def create_first_portrait
face_name = $game_message.face_name
face_index = $game_message.face_index
return if face_name.empty?
@active_portraits.push 0
portrait = PortraitFrame.new face_name, face_index
@portraits.push portrait
end
def validate_basic_mode
face_name = $game_message.face_name
face_index = $game_message.face_index
if face_name.empty?
@portraits[@active_portraits.first].state = :fading_out
elsif @portraits[@active_portraits.first].same_character? face_name
@portraits[@active_portraits.first].hotload face_name, face_index
else
change_to_new_portrait face_name, face_index
end
end
def validate_interactive_mode
face_name = $game_message.face_name
face_index = $game_message.face_index
if face_name.empty?
@portraits.each do |portrait|
portrait.state = :fading_out
end
elsif @portraits[@active_portraits.first].same_character? face_name
@portraits[@active_portraits.first].hotload face_name, face_index
else
if host_mode?
if portrait_alone?
create_second_portrait face_name, face_index
else
if current_is_host?
switch_to_new_portrait face_name, face_index
else
if get_interactive_host.same_character? face_name
switch_to_new_portrait face_name, face_index
else
change_to_new_portrait face_name, face_index
end
end
end
else
if portrait_alone?
create_second_portrait face_name, face_index
else
switch_to_new_portrait face_name, face_index
end
end
end
end
def get_interactive_host
@portraits.find do |portrait|
!portrait.guest
end
end
def create_second_portrait face_name, face_index
@portraits[@active_portraits.first].state = :weakening
@active_portraits.insert 1, @portraits.size
portrait = PortraitFrame.new face_name, face_index, current_is_host?
@portraits.push portrait
end
def change_to_new_portrait face_name, face_index
@portraits[@active_portraits.first].state = :fading_out
@active_portraits.insert 1, @portraits.size
portrait = PortraitFrame.new face_name, face_index, !current_is_host?
@portraits.push portrait
end
def switch_to_new_portrait face_name, face_index
@portraits[@active_portraits.first].state = :weakening
current = @active_portraits.shift
if @portraits[@active_portraits.first].same_character? face_name
portrait = @portraits[@active_portraits.first]
portrait.state = :strengthening
if portrait.face_name != face_name || portrait.face_index != face_index
@portraits[@active_portraits.first].hotload face_name, face_index
end
else
change_to_new_portrait face_name, face_index
end
@active_portraits.unshift current
end
def open_and_wait
@dialogbox.load_skin
update_dialog_validation
if @first_time_window_open
@dialogbox.state = :fading_in
@first_time_window_open = false
end
open
Fiber.yield until open?
end
def close_and_wait
clear_portrait_flags
@dialogbox.abort_shake
@dialogbox.state = :fading_out
@portraits.each do |portrait|
portrait.abort_shake
portrait.state = :fading_out
end
close
Fiber.yield until all_close?
Fiber.yield while transitioning?
end
def process_all_text
open_and_wait
text = $game_message.all_text
disable_name = get_game_switch Name[:disable_switch]
text = convert_escape_characters text
unless disable_name
text = pre_process_name text
end
pos = {}
new_page text, pos
process_character text.slice!(0, 1), text, pos until text.empty?
end
def pre_process_name text
return text unless @background.zero?
ls = text.split ?\n
if ls[0] && !ls[0].empty?
ldeco = Name[:deco][0]
rdeco = Name[:deco][1]
color = Name[:color][:default]
matched = false
face_name = $game_message.face_name
Name[:color][:face].each do |match, mcolor|
if face_name.downcase.start_with? match.downcase
color = mcolor
break matched = true
end
end
Name[:color][:name].each do |match, mcolor|
if ls[0].start_with? match
color = mcolor
break matched = true
end
end unless matched
Misc[:name_with_skin][:name].each do |match, mskin|
if ls[0].start_with? match
break @dialogbox.override_skin = mskin
end
end
ls[0] = "\e>\ec[#{color}]#{ldeco}#{ls[0]}#{rdeco}\ec[0]"
text = ls.join ?\n + ?\s * Name[:indent]
end
text.rstrip
end
def wait_for_one_character
update_show_fast
duration = get_game_variable Text[:character_wait_var], 0
duration = 15 if duration > 15
wait duration + 1 unless @show_fast || @line_show_fast
end
def new_page text, pos
contents.clear
@dialogbox.abort_shake
@portraits.each do |portrait|
portrait.abort_shake
end
Misc[:name_with_skin][:face].each do |match, mskin|
if $game_message.face_name.downcase.start_with? match.downcase
break @dialogbox.override_skin = mskin
end
end
@dialogbox.load_skin
update_dialog_validation
refresh_portraits
Fiber.yield while transitioning?
reset_font_settings
pos[:x] = new_line_x
pos[:y] = 0
pos[:new_x] = new_line_x
pos[:height] = calc_line_height text
yawmp_clear_flags
end
def new_line_x
if has_portrait_in_left? && !portraits_under_dialog?
max_portrait_width = @portraits.map do |portrait|
portrait.right ? 0 : portrait.width
end.max
return max_portrait_width - Offset[:text_with_face]
elsif @background.zero?
return @dialogbox.valid? ? Offset[:text_without_face] : 0
else
return 0
end
end
alias :yawmp_process_escape_character :process_escape_character
def process_escape_character code, text, pos
case code.upcase
when Text[:escape][:shake].upcase
param = obtain_escape_param_string text
@portraits[@active_portraits.first].start_shake param
when Text[:escape][:shake_dialog].upcase
param = obtain_escape_param_string text
@dialogbox.start_shake param
when Text[:escape][:wait_for_shake_complete].upcase
Fiber.yield while @dialogbox.shaking? || @portraits.any?(&:shaking?)
when Text[:escape][:switch].upcase
param = obtain_escape_param_string text
if param =~ /^\d+$/
face_index = param.to_i
portrait = @portraits[@active_portraits.first]
portrait.hotload portrait.face_name, face_index
else
face_name, face_index = param.split '_L'
face_index = face_index.to_i
portrait = @portraits[@active_portraits.first]
if portrait.same_character? face_name
portrait.hotload face_name, face_index
else
msgbox ErrorMessage[:invalid_switch]
end
end
when Text[:escape][:se].upcase
param = obtain_escape_param_string text
params = param.split ','
params[0] = 'Audio/SE/' + params[0]
params[1] = (params[1] || 80).to_i
params[2] = (params[2] || 100).to_i
Audio.se_stop
Audio.se_play *params
else
yawmp_process_escape_character code, text, pos
end
end
def obtain_escape_param_string text
text.slice!(/^\[[^\[\]]+\]/)[/[^\[\]]+/] rescue ''
end
def adjust_choice?
get_game_switch Misc[:adjust_choice_switch]
end
def input_choice
@choice_window.start
if has_portrait? && adjust_choice?
@choice_window.close
@choice_window.deactivate
Fiber.yield while transitioning?
if interactive_mode? && host_mode?
current = get_interactive_host
fade_out_all_guest
current.state = :strengthening if current.weakened?
else
current = @portraits[@active_portraits.first]
fade_out_side !current.right
end
if current.right
@choice_window.x = 0
end
Fiber.yield while transitioning?
@choice_window.open
@choice_window.activate
end
Fiber.yield while @choice_window.active
end
def fade_out_all_that
newlist = []
@active_portraits.each do |id|
if yield @portraits[id]
@portraits[id].state = :fading_out
newlist.unshift id
else
newlist.push id
end
end
@active_portraits = newlist
end
def fade_out_all_guest
fade_out_all_that do |portrait|
portrait.guest
end
end
def fade_out_side right
fade_out_all_that do |portrait|
portrait.right == right
end
end
end
module Cache
def self.portrait name, index, frame, right
filename = generate_portrait_filename name, index, frame
filename = PortraitFolder + filename
key = [filename, right]
unless include? key
begin
@cache[key] = normal_bitmap(filename)
rescue Errno::ENOENT
src = face name
rect = Rect.new index % 4 * 96, index / 4 * 96, 96, 96
right = right ? "right" : "left"
right = "face_side_" + right
right = right.to_sym
side_padding = Window_Message::Offset[right]
bottom_padding = Window_Message::Offset[:face_bottom]
bmp = Bitmap.new 2*side_padding + 96, bottom_padding + 96
bmp.blt side_padding, 0, src, rect
src.dispose
@cache[key] = bmp
end
end
@cache[key]
end
def self.portrait_dim name, index, frame, right, dimness
filename = generate_portrait_filename name, index, frame
filename = PortraitFolder + filename
key = [filename, :dim, dimness, right]
unless include? key
bmp = portrait name, index, frame, right
@cache[key] = bmp.clone
tone = Array.new 3, -dimness
@cache[key].change_tone *tone
end
@cache[key]
end
def self.portrait_blur name, index, frame, right
filename = generate_portrait_filename name, index, frame
filename = PortraitFolder + filename
key = [filename, :blur, right]
unless include? key
bmp = portrait name, index, frame, right
@cache[key] = bmp.clone
@cache[key].blur
end
@cache[key]
end
end
Update YAWMP.rb
##
# Yet Another Window Message with Portrait
# Esphas
#
# v5.0.0 2018.07.24 reworked, and of course, fixed all known bugs
# some settings have been changed
# this version is completely compatable with RGD(v1.1.2+)
# new features:
# use \W and \NW to wait for specified number of frames;
# use a key (default to Ctrl) to skip message.
# v4.2.1 2018.04.08 ...and Interactive.weaken_type now supports variable
# v4.2.0 2018.04.08 new features: change dialog skin according to character name
# & new interactive weaken type: exit
# v4.1.3 2018.04.05 shakes will abort when message ends
# v4.1.2 2018.04.02 bug fix: anime --x--> face image
# v4.1.1 2018.04.01 new feature: when missing portrait, use face image instead
# v4.1.0 2018.04.01 happy fool's day! I decide to change the version number to
# v4.1.0, but actually not much changes are made:
# a fix to a vallana bug;
# portrait offset;
# shake control improvments.
# v3.0.0 2017.12.31 alright, shake overhaul, compatible with v2.0
# v2.2.0 2017.12.31 new feature: shakes now supports up to 4 parameters
# v2.1.0 2017.12.31 new features: shake dialog, play SE
# v2.0.1 2017.10.18 fixed bugs displaying wrong dialog skin
# v2.0.0 2017.07.21 release
#
# https://github.com/ShadowMomo/Smomo-RGSS-Scripts/blob/master/Single/YAWMP.rb
# https://rpg.blue/thread-401822-1-1.html
module YAWMP
##
# 设定区
# - 在进行设置之前,建议先通过在线文档或者 demo 来了解各功能的意义
# - 仅可修改注释指示的内容,尤其注意不要碰逗号冒号花括号
# - 部分功能可能需要其他脚本的支持,请仔细阅读注释
# - 所有开关 ID,若设为 0,则认为对应的值为开关关闭
# - 所有变量 ID,若设为 0,则认为对应的值为 0
# - 原则上,不为不看这些注释的人提供任何技术支持
# -- 但是你可以用金钱来挑战这条原则,钱要多
# -- 开玩笑的,给钱我也会咕咕咕
##
# 对话框
Dialogbox = {
var_skin: 81, # 指示当前对话框皮肤的变量
}
##
# 立绘
Portrait = {
swi_major_right: 81, # 指示立绘是否居右的开关
swi_mirror_left: 82, # 指示左侧立绘或脸图是否镜像处理的开关
swi_mirror_right: 83, # 指示右侧立绘或脸图是否镜像处理的开关
compare_count: 3, # 判别同一角色时比较脸图文件名的前多少个字母
}
##
# 动态效果
Dynamic = {
# 淡入与淡出
dialogbox_in: 10, # 对话框淡入所需时间
dialogbox_out: 10, # 对话框淡出所需时间
portrait_in: 15, # 立绘淡入所需时间
portrait_out: 15, # 立绘淡出所需时间
portrait_dist: 30, # 立绘滑入距离
# 多帧立绘
swi_disable: 86, # 指示禁用此功能的开关
var_interval: 82, # 指示两关键帧之间的时间的变量
var_max_loops: 83, # 指示最大循环次数的变量,为零代表无限循环
var_final_frame: 84, # 指示最终的停留帧的变量,超过帧数则停留在首帧
var_loop_interval: [85, 86] # 指示循环之间的停顿时间的两个变量
# - 第一个变量指示基准时长,第二个变量指示波动范围
# - 即,实际等待时长在 var1 ± var2 内
# - 在首次循环开始之前,也会进行等待
}
##
# 布局
# - 经过深思,决定支持不对称的布局
# -- 立绘或脸图在左侧时,生效的是左边距和左底边距
# -- 反之则是右边距和右底边距
# - 脸图仅在没有对应的立绘时使用
Layout = {
portrait: {
# 立绘
left: 0, # 左边距
right: 0, # 右边距
left_bottom: 0, # 左底边距
right_bottom: 0, # 右底边距
},
face: {
# 脸图
left: 20, # 左边距
right: 20, # 右边距
left_bottom: 12, # 左底边距
right_bottom: 12, # 右底边距
},
text: {
# 文本
plain: 40, # 未使用立绘或脸图时的左边距
portrait: 10, # 左侧有立绘时的左边距,相对于立绘的右边缘
face: 5, # 左侧有脸图时的左边距,相对于脸图的右边缘
},
# 杂项
swi_under_dialogbox: 84, # 指示立绘置于对话框之下的开关
swi_choice_opposite: 89, # 指示将显示选项窗口放在立绘的对面一侧的开关
}
##
# 交替式对话
Dialogue = {
swi_enable: 87, # 指示启用交替式对话的开关
swi_host_mode: 88, # 指示交替式对话存在主持人的开关
deactivation: { # 弱化非活跃角色立绘
type: :dim, # 弱化类型
# - 可选类型有四种
# -- :dim 变暗
# -- :opacity 半透明
# -- :blur 模糊
# -- :exit 退出
# --- 也可使用数字,表示由变量指示
# --- 变量的值为 0 则相当于使用 :dim,为 1 相当于使用 :opacity,以此类推
rate: 100, # 弱化程度
# - 对于 :dim,0 表示不变,255 表示全黑
# - 对于 :opacity,0 表示不变,255 表示全透明
# - 对于其他两项无影响
duration: 10, # 弱化耗时
offset_back: 10, # 弱化时立绘后移的距离
offset_down: 10 # 弱化时立绘下移的距离
}
}
##
# 文本控制
Text = {
var_wait_for_character: 87, # 指示两个字之间等待时间的变量
skip_button: :CTRL, # 用于快进对话的按键
swi_disable_skip: 90, # 指示禁用快进对话的开关
control: {
# 控制符,不区分大小写
shake: 'D', # 抖动当前立绘
# - 参数:抖动对象,半周期,次数,幅度
# - 缺省参数为 x,5,3,5
# - 抖动对象:x 或 y 或 opacity(不透明度)
# - 半周期、次数和幅度顾名思义
# - 幅度的单位是像素(对于 x 和 y)或者取值 0~255(对于 opacity)
# - 例:【\d】【\d[x,10]】【\d[y,7,6,-15]】【\d[opacity,30,6,128]】
shake_dialogbox: 'Z', # 抖动对话框,参数同上
wait_for_shake: 'WS', # 等待抖动完成
wait_frame: 'W', # 等待指定帧数,可被按键跳过,如【\W[3]】
wait_frame_hard: 'NW', # 等待指定帧数,不可被跳过
switch_portrait: 'S', # 切换当前立绘的图形
# - 参数为立绘图编号或全称,如【\S[6]】【\S[AgnesC_L0]】
# - 为了防止各式各样的手滑,只允许切换同一角色的立绘,否则会主动报错
se: 'X' # 播放音效
# - 参数为音效文件名,不带拓展名,如【\X[Absorb1]】
# - 也可以带上一个额外参数表示音量,如【\X[Absorb1,100]】
# - 还可再带一个额外参数表示音调,如【\X[Absorb1,100,150]】
}
}
##
# 名字识别与处理
# - 启用时,第一行文字视为名字
# - 无论是否启用,只在正常背景下生效
Name = {
swi_disable: 85, # 禁用名字识别的开关
deco: ['【', '】'], # 应用在名字两侧的装饰文字
indent: 2, # 正文内容相对于名字的缩进量,以半角空格为单位
color: {
default: 6, # 默认名字颜色
name: {
# 依据名字决定的名字颜色,优先于默认颜色
# 若使用字符串,则代表“匹配名字开头”
# 若使用正则表达式,则直接进行匹配
'以此开头' => 3,
/正则匹配/ => 6,
},
face: {
# 依据脸图文件名决定的名字颜色,优先于默认颜色和名字匹配
'以此开头' => 3,
/正则匹配/ => 6,
/^esphas$/ => 7,
}
},
skin: {
# 为某些名字采用单独的对话框皮肤
name: {
# 依据名字决定
'以此开头' => 3,
/正则匹配/ => 1,
/测试员/ => 5,
},
face: {
# 依据脸图文件名决定
'以此开头' => 3,
/正则匹配/ => 1,
}
}
}
ErrorMessage = {
no_portrait: "无效的操作,根本就不存在立绘",
invalid_switch_wrong_name: "无效的切换,根本不是同一个人"
}
##
# 文件名相关的设置
# - 对这部分的修改需要掌握基础的 ruby 知识
# -- 或者也可以使用勇气、决断和想象力来代替
# - 请自由修改方法内容
def self.dialogbox_skin_name id
# 对话框文件名
"dialog" + (id.zero? ? "" : "#{id}")
end
def self.portrait_name facename, faceindex, framecount
# 立绘文件名
"Graphics/Faces/Large/#{facename}_L#{faceindex}" +
(framecount.zero? ? "" : "_#{framecount}")
end
end
class Window_ChoiceList
##
# 用于修复一个原生 bug:显示选项时使用图标造成的长度不当
# 如果你已经使用了其他修复手段,那么请将下方标注的 true 改为 false
def max_choice_width
$game_message.choices.collect do |s|
s = convert_escape_characters s
height = calc_line_height s
pos = {x: 0, y: -Graphics.height, new_x: 0, height: height}
process_character(s.slice!(0, 1), s, pos) until s.empty?
pos[:x]
end.max
end if true ## 此处标注
end
'Edit Anything Below At Your Own Risk'
'Edit Anything Below At Your Own Risk'
'Edit Anything Below At Your Own Risk'
module YAWMP
# actually this is the first time I introduce a version string here
VERSION = "5.0.0"
def self.get_variable id
return 0 if id.zero?
$game_variables[id]
end
def self.get_switch id
return false if id.zero?
$game_switches[id]
end
def self.has_portrait? name, index, frame
filename = portrait_name name, index, frame
["", ".png", ".jpg"].any? do |ext|
FileTest.exist? filename + ext
end
end
def self.same_character? name1, name2
beg1 = name1.downcase[0, Portrait[:compare_count]]
beg2 = name2.downcase[0, Portrait[:compare_count]]
beg1 == beg2
end
def self.deactivation_type
type = Dialogue[:deactivation][:type]
if type.is_a? Integer
type = get_variable type
type = [:dim, :opacity, :blur, :exit][type]
end
type
end
module C
end
end
class Window_Message
def initialize
super(0, 0, window_width, window_height)
self.z = 200
self.openness = 0
create_all_windows
create_back_bitmap
create_back_sprite
create_dialogbox
create_portraits
clear_instance_variables
end
def create_dialogbox
@dialogbox = YAWMP::C::Dialogbox.new
@dialogbox.x = 0
@dialogbox.z = z - 1
end
def create_portraits
@portraits = YAWMP::C::PortraitManager.new
@portraits.z = z
end
def dispose
super
dispose_all_windows
dispose_back_bitmap
dispose_back_sprite
dispose_dialogbox
dispose_portraits
end
def dispose_dialogbox
@dialogbox.dispose
end
def dispose_portraits
@portraits.dispose
end
def update
super
update_all_windows
update_back_sprite
update_dialogbox
update_portraits
update_fiber
end
def update_dialogbox
@dialogbox.y = y
@dialogbox.update
end
def update_portraits
@portraits.update
end
def update_background
@background = $game_message.background
@dialogbox.visible = false
self.opacity = 0
end
def process_all_text
text = convert_escape_characters $game_message.all_text
skin_id = YAWMP.get_variable YAWMP::Dialogbox[:var_skin]
if @background.zero? # normal background
unless YAWMP.get_switch YAWMP::Name[:swi_disable]
ls = text.split "\n"
if ls[0] && !ls[0].empty?
ldeco = YAWMP::Name[:deco][0]
rdeco = YAWMP::Name[:deco][1]
color = YAWMP::Name[:color][:default]
YAWMP::Name[:color][:name].each do |name, ncolor|
if name.is_a? String
if ls[0].start_with? name
color = ncolor
break
end
elsif name.is_a? Regexp
if ls[0].match name
color = ncolor
break
end
end
end
YAWMP::Name[:color][:face].each do |face, fcolor|
if face.is_a? String
if $game_message.face_name.downcase.start_with? face.downcase
color = fcolor
break
end
elsif face.is_a? Regexp
if $game_message.face_name.match face
color = fcolor
break
end
end
end
YAWMP::Name[:skin][:name].each do |name, nskin|
if name.is_a? String
if ls[0].start_with? name
skin_id = nskin
break
end
elsif name.is_a? Regexp
if ls[0].match name
skin_id = nskin
break
end
end
end
YAWMP::Name[:skin][:face].each do |face, fskin|
if face.is_a? String
if $game_message.face_name.downcase.start_with? face.downcase
skin_id = fskin
break
end
elsif face.is_a? Regexp
if $game_message.face_name.match face
skin_id = fskin
break
end
end
end
ls[0] = "\e>\ec[#{color}]#{ldeco}#{ls[0]}#{rdeco}\ec[0]"
text = ls.join "\n" + "\s" * YAWMP::Name[:indent]
end
end
end
load_dialogbox skin_id
open_and_wait
pos = {}
new_page text, pos
process_character(text.slice!(0, 1), text, pos) until text.empty?
end
def load_dialogbox skin_id
if @background.zero? # normal background
@dialogbox.load_skin skin_id
@dialogbox.y = y
@dialogbox.visible = @dialogbox.valid
self.opacity = @dialogbox.valid ? 0 : 255
else
self.opacity = 0
end
end
def open_and_wait
@dialogbox.enter
open
Fiber.yield until open? && !@dialogbox.busy?
end
def close_and_wait
@dialogbox.exit
@portraits.exit_all
close
Fiber.yield until all_close? && !@dialogbox.busy? && !@portraits.busy?
contents.clear
end
def wait duration
if YAWMP.get_switch YAWMP::Text[:swi_disable_skip]
duration.times { Fiber.yield }
else
duration.times do
if Input.press? YAWMP::Text[:skip_button]
break
else
Fiber.yield
end
end
end
end
def update_show_fast
@show_fast = true if Input.trigger?(:C)
unless YAWMP.get_switch YAWMP::Text[:swi_disable_skip]
@show_fast ||= Input.press? YAWMP::Text[:skip_button]
end
end
def wait_for_one_character
update_show_fast
duration = YAWMP.get_variable YAWMP::Text[:var_wait_for_character]
duration = 0 if duration < 0
duration = 15 if duration > 15
wait duration + 1 unless @show_fast || @line_show_fast
end
def new_page text, pos
contents.clear
reset_font_settings
name, index = $game_message.face_name, $game_message.face_index
@portraits.push name, index
if YAWMP.get_switch YAWMP::Text[:swi_disable_skip]
Fiber.yield while @portraits.busy?
else
while @portraits.busy?
if Input.press? YAWMP::Text[:skip_button]
@portraits.skip
break
end
Fiber.yield
end
end
if @portraits.current_left &&
@portraits.current_left.z > z
if @portraits.current_left.type == :portrait
new_line_x = @portraits.current_left.width
new_line_x += YAWMP::Layout[:portrait][:left]
new_line_x += YAWMP::Layout[:text][:portrait]
else
new_line_x = @portraits.current_left.width
new_line_x += YAWMP::Layout[:face][:left]
new_line_x += YAWMP::Layout[:text][:face]
end
else
new_line_x = YAWMP::Layout[:text][:plain]
end
pos[:x] = new_line_x
pos[:y] = 0
pos[:new_x] = new_line_x
pos[:height] = calc_line_height(text)
clear_flags
end
alias :yawmp_process_escape_character :process_escape_character
def process_escape_character code, text, pos
control = YAWMP::Text[:control]
case code.upcase
when control[:shake].upcase
param = obtain_escape_param_string text
@portraits.shake_active param
when control[:shake_dialogbox].upcase
param = obtain_escape_param_string text
@dialogbox.shake param
when control[:wait_for_shake].upcase
if YAWMP.get_switch YAWMP::Text[:swi_disable_skip]
Fiber.yield while @dialogbox.busy? || @portraits.busy?
else
while @dialogbox.busy? || @portraits.busy?
if Input.press? YAWMP::Text[:skip_button]
@dialogbox.skip
@portraits.skip
break
end
Fiber.yield
end
end
when control[:wait_frame].upcase
[obtain_escape_param(text),0].max.times do |i|
update_show_fast
Fiber.yield unless @show_fast || @line_show_fast
end
when control[:wait_frame_hard].upcase
([obtain_escape_param(text),0].max).times { Fiber.yield }
when control[:switch_portrait].upcase
param = obtain_escape_param_string text
@portraits.switch_active_to param
when control[:se].upcase
param = obtain_escape_param_string text
params = param.split ','
params[0] = 'Audio/SE/' + params[0]
params[1] = (params[1] || 80).to_i
params[2] = (params[2] || 100).to_i
Audio.se_stop
Audio.se_play *params
else
yawmp_process_escape_character code, text, pos
end
end
def obtain_escape_param_string text
text.slice!(/^\[[^\[\]]+\]/)[/[^\[\]]+/] rescue ''
end
def input_pause
if YAWMP.get_switch YAWMP::Text[:swi_disable_skip]
self.pause = true
wait(10)
Fiber.yield until Input.trigger?(:B) || Input.trigger?(:C)
Input.update
self.pause = false
else
self.pause = true
wait(10)
Fiber.yield until Input.trigger?(:B) || Input.trigger?(:C) ||
Input.press?(YAWMP::Text[:skip_button])
Input.update
self.pause = false
end
end
def input_choice
@choice_window.start
if YAWMP.get_switch YAWMP::Layout[:swi_choice_opposite]
@choice_window.x = 0 if @portraits.current_right
end
Fiber.yield while @choice_window.active
end
end
module Cache
def self.portrait name, index, frame, type = :normal
filename = YAWMP.portrait_name name, index, frame
key = [:yawmp, filename, type]
unless include? key
case type
when :blur
@cache[key] = portrait name, index, frame
@cache[key] = @cache[key].clone.blur
else
@cache[key] = normal_bitmap filename
end
end
@cache[key]
end
def self.face_blur name
key = [:yawmp, :face, name, :blur]
unless include? key
@cache[key] = face name
@cache[key] = @cache[key].clone.blur
end
@caceh[key]
end
end
class YAWMP::C::SpriteContainer
def initialize
@sprite = Sprite.new
clear_sequence
@sprite.opacity = 0
@state = :out
@intermediate_states = {
entering: :in,
exiting: :out,
shaking: :in
}
end
def clear_sequence
@sequence = {
x: [],
y: [],
opacity: []
}
end
%w[ x= y= z= ].each do |setter|
define_method setter do |value|
@sprite.send setter, value
end
end
%w[ x y z width height ].each do |getter|
define_method getter do
@sprite.send getter
end
end
def update
self.x = @sequence[:x].pop || self.x
self.y = @sequence[:y].pop || self.y
@sprite.opacity = @sequence[:opacity].pop || @sprite.opacity
if @intermediate_states.key? @state
@state = @intermediate_states[@state] unless busy?
end
@sprite.update
end
def skip
self.x = @sequence[:x][0] || self.x
self.y = @sequence[:y][0] || self.y
@sprite.opacity = @sequence[:opacity][0] || @sprite.opacity
clear_sequence
if @intermediate_states.key? @state
@state = @intermediate_states[@state]
end
end
def busy?
!@sequence.values.all?(&:empty?)
end
def dispose
@sprite.dispose
end
def shake param
return unless @state == :in
@state = :shaking
type, halfperiod, count, amplitude = param.split ','
type = (type || :x).downcase.to_sym
halfperiod = (halfperiod || 5).to_i
count = (count || 3).to_i
amplitude = (amplitude || 5).to_i
if type == :opacity
list = (2*halfperiod).times.map do |i|
amplitude * Math.cos(Math::PI * i / halfperiod)
end * count
list.map!{ |v| v + 255 - amplitude }
else
base_value = send type
list = (2*halfperiod).times.map do |i|
amplitude * Math.sin(Math::PI * i / halfperiod) + base_value
end * count
end
@sequence[type] = list
end
end
class YAWMP::C::Dialogbox < YAWMP::C::SpriteContainer
attr_reader :valid
def initialize
super
@valid = false
end
def visible= visible
@sprite.visible = visible
end
def visible
@sprite.visible
end
def update
@state = :out unless @valid
return unless @valid
super
end
def load_skin skin_id
skin_name = YAWMP.dialogbox_skin_name skin_id
@sprite.bitmap = Cache.system skin_name
@valid = true
rescue Errno::ENOENT
@valid = false
end
def enter
return unless @state == :out
@state = :entering
n = YAWMP::Dynamic[:dialogbox_in]
@sequence[:opacity] = n.times.map do |i|
255.0 * (i + 1) / n
end.reverse
@sprite.opacity = 0
end
def exit
return if @state == :out
@state = :exiting
n = YAWMP::Dynamic[:dialogbox_out]
@sequence[:opacity] = n.times.map do |i|
@sprite.opacity.to_f * i / n
end
end
def busy?
@valid && super
end
end
class YAWMP::C::Portrait < YAWMP::C::SpriteContainer
attr_reader :name
attr_reader :index
attr_reader :type
def initialize name, index, side, z
super()
@intermediate_states[:deactivating] = :inactive
@intermediate_states[:activating] = :in
@helper = Sprite.new
@side = side
@base_z = z
load name, index
end
def clear_sequence
super
@sequence[:helper] = []
end
def skip
@helper.opacity = @sequence[:helper][0] || @helper.opacity
super
end
%w[ x= y= z= ].each do |setter|
define_method setter do |value|
@sprite.send setter, value
@helper.send setter, value
end
end
def update
super
@helper.opacity = @sequence[:helper].pop || @helper.opacity
@helper.update
update_animation
end
def dispose
super
@helper.dispose
end
def update_animation
return if YAWMP.get_switch YAWMP::Dynamic[:swi_disable]
return if busy?
return if @intermediate_states.include? @state
return if @state == :out
return if @animation[:stopped]
if @animation[:max_loops] > 0 && # finite
@animation[:loops] == @animation[:max_loops] && # last loop
@animation[:frame] == @animation[:final_frame] # last frame
@animation[:stopped] = true
return
end
@animation[:counter] += 1
if YAWMP.has_portrait? @name, @index, @animation[:frame] + 1
# to next frame
if @animation[:counter] >= @animation[:interval]
@animation[:counter] = 0
@animation[:frame] += 1
end
else
# to next loop
if @animation[:counter] >= @animation[:cached_loop_interval]
@animation[:counter] = 0
@animation[:frame] = 0
@animation[:loops] += 1
loop_interval = @animation[:loop_interval]
@animation[:cached_loop_interval] =
loop_interval[0] - loop_interval[1] +
(2*loop_interval[1] + 1).times.to_a.sample
end
end
hotload @name, @index, @animation[:frame]
end
def load name, index
is_same = name == @name && index == @index
hotload name, index, 0
reset_animation unless is_same
reset_mirror
reset_z
end
def hotload name, index, frame
@name = name
@index = index
if YAWMP.has_portrait? @name, @index, frame
@type = :portrait
@sprite.bitmap = Cache.portrait @name, @index, frame
@sprite.src_rect = @sprite.bitmap.rect
else
@type = :face
@sprite.bitmap = Cache.face @name
@sprite.src_rect = Rect.new 96*(@index%4), 96*(@index/4), 96, 96
end
type = YAWMP.deactivation_type
rate = YAWMP::Dialogue[:deactivation][:rate]
case type
when :dim
@helper.bitmap = @sprite.bitmap
@helper.src_rect = @sprite.src_rect
@helper.tone = Tone.new -rate, -rate, -rate
when :opacity
@helper.bitmap = nil
when :blur
if @type == :portrait
@helper.bitmap = Cache.portrait @name, @index, frame, :blur
else
@helper.bitmap = Cache.face_blur @name
end
@helper.src_rect = @sprite.src_rect
@helper.tone = Tone.new
end
if @state == :inactive
@sprite.opacity = 0
@helper.opacity = 255
if type == :opacity
@sprite.opacity = 255 - rate
end
else
@sprite.opacity = 255
@helper.opacity = 0
end
end
def reset_animation
@animation = {
stopped: true
}
if @type == :portrait && YAWMP.has_portrait?(@name, @index, 1)
@animation = {
frame: 0,
loops: 0,
interval: YAWMP.get_variable(YAWMP::Dynamic[:var_interval]),
max_loops: YAWMP.get_variable(YAWMP::Dynamic[:var_max_loops]),
final_frame: YAWMP.get_variable(YAWMP::Dynamic[:var_final_frame]),
loop_interval:
YAWMP::Dynamic[:var_loop_interval].map do |v|
YAWMP.get_variable v
end,
counter: 0,
stopped: false
}
loop_interval = @animation[:loop_interval]
@animation[:cached_loop_interval] =
loop_interval[0] - loop_interval[1] +
(2*loop_interval[1] + 1).times.to_a.sample
end
end
def reset_mirror
if @side == :left
@sprite.mirror = YAWMP.get_switch YAWMP::Portrait[:swi_mirror_left]
@helper.mirror = @sprite.mirror
else
@sprite.mirror = YAWMP.get_switch YAWMP::Portrait[:swi_mirror_right]
@helper.mirror = @sprite.mirror
end
end
def reset_z
if YAWMP.get_switch YAWMP::Layout[:swi_under_dialogbox]
self.z = @base_z - 2
else
self.z = @base_z + 1
end
end
def enter
return unless @state == :out
@state = :entering
n = YAWMP::Dynamic[:portrait_in]
if @side == :left
tx = YAWMP::Layout[@type][:left]
sx = tx - YAWMP::Dynamic[:portrait_dist]
ty = Graphics.height - self.height
ty -= YAWMP::Layout[@type][:left_bottom]
sy = ty
else
tx = Graphics.width - self.width
tx -= YAWMP::Layout[@type][:right]
sx = tx + YAWMP::Dynamic[:portrait_dist]
ty = Graphics.height - self.height
ty -= YAWMP::Layout[@type][:right_bottom]
sy = ty
end
@sequence[:x] = n.times.map do |i|
tx + (sx - tx).to_f * i / n
end
@sequence[:y] = []
@sequence[:opacity] = n.times.map do |i|
255.0 * (i + 1) / n
end.reverse
self.x = sx
self.y = sy
@sprite.opacity = 0
@helper.opacity = 0
end
def exit
return if @state == :out
@state = :exiting
n = YAWMP::Dynamic[:portrait_out]
if @side == :left
tx = YAWMP::Layout[@type][:left]
tx -= YAWMP::Dynamic[:portrait_dist]
else
tx = Graphics.width - self.width
tx -= YAWMP::Layout[@type][:right]
tx += YAWMP::Dynamic[:portrait_dist]
end
sx = self.x
@sequence[:x] = n.times.map do |i|
tx + (sx - tx).to_f * i / n
end
@sequence[:opacity] = n.times.map do |i|
@sprite.opacity.to_f * i / n
end
@sequence[:helper] = n.times.map do |i|
@helper.opacity.to_f * i / n
end
end
def activate
return unless @state == :inactive || @state == :deactivating
@state = :activating
deactivation = YAWMP::Dialogue[:deactivation]
n = deactivation[:duration]
if @side == :left
tx = YAWMP::Layout[@type][:left]
ty = Graphics.height - self.height
ty -= YAWMP::Layout[@type][:left_bottom]
else
tx = Graphics.width - self.width
tx -= YAWMP::Layout[@type][:right]
ty = Graphics.height - self.height
ty -= YAWMP::Layout[@type][:right_bottom]
end
sx = self.x
sy = self.y
@sequence[:x] = n.times.map do |i|
tx + (sx - tx).to_f * i / n
end
@sequence[:y] = n.times.map do |i|
ty + (sy - ty).to_f * i / n
end
@sequence[:opacity] = n.times.map do |i|
@sprite.opacity + (255.0 - @sprite.opacity) * (i + 1) / n
end.reverse
@sequence[:helper] = n.times.map do |i|
@helper.opacity.to_f * i / n
end
end
def deactivate
return if @state == :inactive
return if @state == :exiting
return if @state == :out
return if @state == :deactivating
@state = :deactivating
deactivation = YAWMP::Dialogue[:deactivation]
n = deactivation[:duration]
if @side == :left
tx = YAWMP::Layout[@type][:left]
tx -= deactivation[:offset_back]
ty = Graphics.height - self.height
ty -= YAWMP::Layout[@type][:left_bottom]
ty += deactivation[:offset_down]
else
tx = Graphics.width - self.width
tx -= YAWMP::Layout[@type][:right]
tx += deactivation[:offset_back]
ty = Graphics.height - self.height
ty -= YAWMP::Layout[@type][:right_bottom]
ty += deactivation[:offset_down]
end
sx = self.x
sy = self.y
@sequence[:x] = n.times.map do |i|
tx + (sx - tx).to_f * i / n
end
@sequence[:y] = n.times.map do |i|
ty + (sy - ty).to_f * i / n
end
topacity = 0
if YAWMP.deactivation_type == :opacity
rate = deactivation[:rate]
topacity = 255 - rate
end
@sequence[:opacity] = n.times.map do |i|
topacity + (@sprite.opacity - topacity).to_f * i / n
end
@sequence[:helper] = n.times.map do |i|
255.0 * (i + 1) / n
end.reverse
end
end
class YAWMP::C::PortraitManager
attr_accessor :z
def initialize
@current = {
left: nil,
right: nil
}
@exiting = {
left: nil,
right: nil
}
@opposite_side = {left: :right, right: :left}
@active = nil
end
def mode
if YAWMP.get_switch YAWMP::Dialogue[:swi_enable]
if YAWMP.get_switch YAWMP::Dialogue[:swi_host_mode]
:host
else
:turn
end
else
:normal
end
end
def dispose
(@current.values + @exiting.values).compact.each &:dispose
end
def update
@active = nil if mode == :normal
dispose_exited
(@current.values + @exiting.values).compact.each &:update
end
def skip
(@current.values + @exiting.values).compact.each &:skip
end
def busy?
(@current.values + @exiting.values).compact.any? &:busy?
end
def major_side
if YAWMP.get_switch YAWMP::Portrait[:swi_major_right]
:right
else
:left
end
end
def push name, index
case mode
when :normal
push_normal name, index
when :turn
push_turn name, index
when :host
push_host name, index
end
end
def push_normal name, index
side = major_side
clear_side @opposite_side[side]
push_to_side name, index, side
end
def push_turn name, index
side = major_side
oside = @opposite_side[side]
if @current[side] # major side is filled
if @current[oside] # both sides are filled
if YAWMP.same_character? name, @current[@active].name
# active side remains active
else
deactivate @active
@active = @opposite_side[@active]
end
else # opposite side is empty
if YAWMP.same_character? name, @current[side].name
@active = side
else
deactivate side
@active = oside
end
end
else # major side is empty
if @current[oside] # opposite side is filled
if YAWMP.same_character? name, @current[oside].name
@active = oside
else
deactivate oside
@active = side
end
else # both sides are empty
@active = side
end
end
push_to_side name, index, @active
end
def push_host name, index
side = major_side
oside = @opposite_side[side]
if @current[side] # has host
if YAWMP.same_character? name, @current[side].name # is host
deactivate oside
@active = side
else
deactivate side
@active = oside
end
else # no host
if @current[oside] # has guest
if YAWMP.same_character? name, @current[oside].name # is guest
@active = oside
else
deactivate oside
@active = side
end
else
@active = side
end
end
push_to_side name, index, @active
end
def push_to_side name, index, side
if @current[side] &&
YAWMP.same_character?(name, @current[side].name)
@current[side].load name, index
@current[side].activate
else
clear_side side
unless name.empty?
@current[side] = YAWMP::C::Portrait.new name, index, side, z
@current[side].enter
end
end
end
def deactivate side
type = YAWMP.deactivation_type
if type == :exit
clear_side side
else
@current[side].deactivate
end
end
def shake_active param
portrait = active_portrait
if portrait.nil?
msgbox YAWMP::ErrorMessage[:no_portrait]
return
end
portrait.shake param
end
def switch_active_to param
portrait = active_portrait
if portrait.nil?
msgbox YAWMP::ErrorMessage[:no_portrait]
return
end
if param =~ /^\d+$/
index = param.to_i
portrait.load portrait.name, index
else
name, index = param.split '_L'
index = index.to_i
if YAWMP.same_character? name, portrait.name
portrait.load name, index
else
msgbox YAWMP::ErrorMessage[:invalid_switch_wrong_name]
end
end
end
def active_portrait
side = major_side
case mode
when :normal
@current[side]
when :turn
if @current[side] && @current[@opposite_side[side]]
@current[@active]
elsif @current[side]
@current[side]
else
@current[@opposite[side]]
end
when :host
if @current[side] && @current[@opposite_side[side]]
@current[@active]
elsif @current[side]
@current[side]
else
@current[@opposite_side[side]]
end
end
end
def current_left
@current[:left]
end
def current_right
@current[:right]
end
def clear_side side
if @current[side]
@exiting[side].dispose if @exiting[side]
@current[side].exit
@exiting[side] = @current[side]
@current[side] = nil
end
end
def dispose_exited
[:left, :right].each do |side|
if @exiting[side] && !@exiting[side].busy?
@exiting[side].dispose
@exiting[side] = nil
end
end
end
def exit_all
clear_side :left
clear_side :right
end
end
|
def plugins
@@plugins ||=
(
plugins = {}
Plugin.list.each do |name, path|
begin
plugins[name] = Plugin.new name
rescue => e
STDERR.puts e
next
end
end
plugins
)
end
plugins
print plugin name on load #23
def plugins
@@plugins ||=
(
plugins = {}
Plugin.list.each do |name, path|
puts "load plugin \"#{name}\" - #{path}"
begin
plugins[name] = Plugin.new name
rescue => e
STDERR.puts e
next
end
end
plugins
)
end
plugins
|
require 'spec_helper'
describe Biblio::Refs do
before :each do
@ref1 = Biblio::Refs::Referencia.new(["Dave Thomas", "Andy Hunt", "Chad Fowler"], "Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide", "The Facets of Ruby", "Pragmatic Bookshelf", 4, Date.parse('7th July 2013'))
@ref2 = Biblio::Refs::Referencia.new("J.R.R Tolkien", "El Hobbit", "Minotauro", 2, Date.parse('1st February 1982'))
end
it 'Tiene un número de versión' do
expect(Biblio::Refs::VERSION).not_to be nil
end
it 'Deben de existir uno o más autores' do
expect(@ref1.autores).not_to be nil
end
it 'Debe de existir un título' do
expect(@ref1.titulo).not_to be nil
end
it 'Debe o no existir una serie' do
expect(@ref1.serie).not_to be nil
expect(@ref2.serie).to be nil
end
it 'Debe existir una editorial' do
expect(@ref1.editorial).not_to be nil
expect(@ref2.editorial).not_to be nil
end
it 'Debe existir un número de edición' do
expect(@ref1.num_edicion).not_to be nil
expect(@ref2.num_edicion).not_to be nil
end
it 'Debe existir una fecha de publicación' do
expect(@ref1.fecha_publicacion).not_to be nil
expect(@ref2.fecha_publicacion).not_to be nil
end
end
Añadida expectativa para comprobar la existencia de uno o más números ISBN
require 'spec_helper'
describe Biblio::Refs do
before :each do
@ref1 = Biblio::Refs::Referencia.new(["Dave Thomas", "Andy Hunt", "Chad Fowler"], "Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide", "The Facets of Ruby", "Pragmatic Bookshelf", 4, Date.parse('7th July 2013'), ['978-1937785499', 1937785491])
@ref2 = Biblio::Refs::Referencia.new("J.R.R Tolkien", "El Hobbit", "Minotauro", 2, Date.parse('1st February 1982'), 0345538374)
end
it 'Tiene un número de versión' do
expect(Biblio::Refs::VERSION).not_to be nil
end
it 'Deben de existir uno o más autores' do
expect(@ref1.autores).not_to be nil
end
it 'Debe de existir un título' do
expect(@ref1.titulo).not_to be nil
end
it 'Debe o no existir una serie' do
expect(@ref1.serie).not_to be nil
expect(@ref2.serie).to be nil
end
it 'Debe existir una editorial' do
expect(@ref1.editorial).not_to be nil
expect(@ref2.editorial).not_to be nil
end
it 'Debe existir un número de edición' do
expect(@ref1.num_edicion).not_to be nil
expect(@ref2.num_edicion).not_to be nil
end
it 'Debe existir una fecha de publicación' do
expect(@ref1.fecha_publicacion).not_to be nil
expect(@ref2.fecha_publicacion).not_to be nil
end
it 'Debe existir uno o más números ISBN' do
expect(@ref1.isbn).not_to be nil
expect(@ref2.isbn).not_to be nil
end
end
|
require 'spec_helper'
describe BiblioRefs do
before :each do
@ref1 = BiblioRefs::Referencia.new(["Dave Thomas", "Andy Hunt", "Chad Fowler"], "Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide", "The Facets of Ruby", "Pragmatic Bookshelf", 4, Date.parse('7th July 2013'), ['978-1937785499', '1937785491'])
@ref2 = BiblioRefs::Referencia.new("J.R.R Tolkien", "El Hobbit", "Minotauro", 2, Date.parse('1st February 1982'), '0345538374')
end
describe "Comprobación de la inicialización de los atributos de la clase" do
it 'Tiene un número de versión' do
expect(BiblioRefs::VERSION).not_to be nil
end
it 'Deben de existir uno o más autores' do
expect(@ref1.autores).not_to be nil
end
it 'Debe de existir un título' do
expect(@ref1.titulo).not_to be nil
end
it 'Debe o no existir una serie' do
expect(@ref1.serie).not_to be nil
expect(@ref2.serie).to be nil
end
it 'Debe existir una editorial' do
expect(@ref1.editorial).not_to be nil
expect(@ref2.editorial).not_to be nil
end
it 'Debe existir un número de edición' do
expect(@ref1.num_edicion).not_to be nil
expect(@ref2.num_edicion).not_to be nil
end
it 'Debe existir una fecha de publicación' do
expect(@ref1.fecha_publicacion).not_to be nil
expect(@ref2.fecha_publicacion).not_to be nil
end
it 'Debe existir uno o más números ISBN' do
expect(@ref1.isbn).not_to be nil
expect(@ref2.isbn).not_to be nil
end
end
describe "Comprobación de métodos to_s" do
it 'Debe existir un método que devuelva los autores' do
expect(@ref1.autores_to_s).to eq("Dave Thomas, Andy Hunt, Chad Fowler.")
expect(@ref2.autores_to_s).to eq("J.R.R Tolkien.")
end
it 'Debe existir un método que devuelva el título' do
expect(@ref1.titulo_to_s).to eq("Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide")
expect(@ref2.titulo_to_s).to eq("El Hobbit")
end
it 'Debe existir un método que devuelva la serie' do
expect(@ref1.serie_to_s).to eq("(The Facets of Ruby)")
expect(@ref2.serie_to_s).to be nil
end
it 'Debe existir un método que devuelva la editorial' do
expect(@ref1.editorial_to_s).to eq("Pragmatic Bookshelf")
expect(@ref2.editorial_to_s).to eq("Minotauro")
end
it 'Debe existir un método que devuelva el número de edición' do
expect(@ref1.num_edicion_to_s).to eq("4 edition")
expect(@ref2.num_edicion_to_s).to eq("2 edition")
end
it 'Debe existir un método que devuelva la fecha de publicación' do
expect(@ref1.fecha_publicacion_to_s).to eq("July 7, 2013")
expect(@ref2.fecha_publicacion_to_s).to eq("February 1, 1982")
end
it 'Debe existir un método que devuelva el listado de números ISBN' do
expect(@ref1.isbn_to_s).to eq("ISBN-13: 978-1937785499\nISBN-10: 1937785491")
expect(@ref2.isbn_to_s).to eq("ISBN-10: 0345538374")
end
it 'Debe existir un método que devuelva la referencia formateada' do
expect(@ref1.to_s).to eq ("Dave Thomas, Andy Hunt, Chad Fowler.\nProgramming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide\n(The Facets of Ruby)\nPragmatic Bookshelf; 4 edition (July 7, 2013)\nISBN-13: 978-1937785499\nISBN-10: 1937785491")
expect(@ref2.to_s).to eq ("J.R.R Tolkien.\nEl Hobbit\nMinotauro; 2 edition (February 1, 1982)\nISBN-10: 0345538374")
end
end
describe "Nodo" do
before :each do
@nodo1 = Nodo.new("último", nil, nil)
@nodo2 = Nodo.new("primero", @nodo1, nil)
@nodo1[:prev] = @nodo2
end
it '#Debe existir un Nodo en la lista con sus datos y su siguiente' do
expect(@nodo2[:value]).to eq("primero")
expect(@nodo2[:next]).to eq(@nodo1)
end
it '#Debe existir un Nodo con su anterior' do
expect(@nodo1[:prev]).to eq(@nodo2)
end
end
describe "List" do
before :each do
@lista1 = BiblioRefs::List.new("elemento")
@lista2 = BiblioRefs::List.new("elemento1", "elemento2")
end
it '#Debe existir una lista con su cabeza' do
expect(@lista1.head[:value]).to eq("elemento")
expect(@lista2.head[:value]).to eq("elemento1")
end
it '#Debe existir una lista con su cola' do
expect(@lista1.tail[:value]).to eq("elemento")
expect(@lista2.tail[:value]).to eq("elemento2")
end
it '#Se extrae el primer elemento de la lista' do
expect(@lista1.pop).to eq("elemento")
expect(@lista2.pop).to eq("elemento1")
end
it '#Se puede insertar un elemento' do
@lista1.push("nuevo")
expect(@lista1.head[:next][:value]).to eq("nuevo")
expect(@lista1.tail[:prev][:value]).to eq("elemento")
end
it '#Se pueden insertar varios elementos' do
@lista1.push("nuevo1", "nuevo2")
expect(@lista1.head[:next][:value]).to eq("nuevo1")
expect(@lista1.head[:next][:next][:value]).to eq("nuevo2")
expect(@lista1.tail[:prev][:value]).to eq("nuevo1")
expect(@lista1.tail[:prev][:prev][:value]).to eq("elemento")
end
it '#Debe existir un método que devuelve la lista formateada' do
@lista1.push("elemento2", "elemento3")
expect(@lista1.to_s).to eq("Lista: elemento -> elemento2 -> elemento3")
end
end
describe "Lista de referencias" do
before :each do
@refa = BiblioRefs::Referencia.new(["Dave Thomas", "Andy Hunt", "Chad Fowler"], "Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide", "The Facets of Ruby", "Pragmatic Bookshelf", 4, Date.parse('7th July 2013'), ['978-1937785499', '1937785491'])
@refb = BiblioRefs::Referencia.new("Scott Chacon", "Pro Git 2009th Edition", "Pro", "Apress", 2009, Date.parse('27th August 2009'), ['978-1430218333', '1430218339'])
@refc = BiblioRefs::Referencia.new(["David Flanagan", "Yukihiro Matsumoto"], "The Ruby Programming Language", "O'Reilly Media", 1, Date.parse('4th February 2008'), ['0596516177', '978-0596516178'])
@refd = BiblioRefs::Referencia.new(["David Chelimsky", "Dave Astels", "Bryan Helmkamp", "Dan North", "Zach Dennis", "Aslak Hellesoy"], "The RSpec Book: Behaviour Driven Development with RSpec, Cucumber, and Friends", "The Facets of Ruby", "Pragmatic Bookshelf", 1, Date.parse('25th December 2010'), ['1934356379', '978-1934356371'])
@refe = BiblioRefs::Referencia.new("Richard E. Silverman", "Git Pocket Guide", "O'Reilly Media", 1, Date.parse('2nd August 2013'), ['1449325866', '978-1449325862'])
@lista = BiblioRefs::List.new(@refa, @refb, @refc, @refd, @refe)
end
it '#Se puede crear una lista de Referencias Biográficas' do
expect(@lista.to_s).to eq("Lista: #{@refa} -> #{@refb} -> #{@refc} -> #{@refd} -> #{@refe}")
end
end
describe "Jerarquía de clases" do
before :each do
@libro = BiblioRefs::Libro.new
@publicacion = BiblioRefs::PublicacionPeriodica.new
@revista = BiblioRefs::Revista.new
@articulo = BiblioRefs::ArticuloPeriodico.new
@documento = BiblioRefs::DocumentoElectronico.new
end
it "#El objeto de la clase Libro es hijo de la clase Referencia" do
expect(@libro).to be_a BiblioRefs::Referencia
end
it "#El objeto de la clase PublicacionPeriodica es hijo de la clase Referencia" do
expect(@publicacion).to be_a BiblioRefs::Referencia
end
it "#El objeto de la clase Revista es hijo de la clase PublicacionPeriodica" do
expect(@publicacion).to be_a BiblioRefs::PublicacionPeriodica
expect(@publicacion).to be_a BiblioRefs::Referencia
end
it "#El objeto de la clase ArticuloPeriodico es hijo de la clase PublicacionPeriodica" do
expect(@articulo).to be_a BiblioRefs::PublicacionPeriodica
expect(@publicacion).to be_a BiblioRefs::Referencia
end
it "#El objeto de la clase DocumentoElectronico es hijo de la clase PublicacionPeriodica" do
expect(@documento).to be_a BiblioRefs::PublicacionPeriodica
expect(@publicacion).to be_a BiblioRefs::Referencia
end
end
describe "Instancias de la clase Referencia comparables" do
before :each do
@refa = BiblioRefs::Referencia.new(["Dave Thomas", "Andy Hunt", "Chad Fowler"], "Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide", "The Facets of Ruby", "Pragmatic Bookshelf", 4, Date.parse('7th July 2013'), ['978-1937785499', '1937785491'])
@refb = BiblioRefs::Referencia.new(["Dave Thomas", "Andy Hunt", "Chad Fowler"], "Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide", "The Facets of Ruby", "Pragmatic Bookshelf", 4, Date.parse('7th July 2013'), ['978-1937785499', '1937785491'])
@refc = BiblioRefs::Referencia.new("Scott Chacon", "Pro Git 2009th Edition", "Pro", "Apress", 2009, Date.parse('27th August 2009'), ['978-1430218333', '1430218339'])
@refd = BiblioRefs::Referencia.new(["David Flanagan", "Yukihiro Matsumoto"], "The Ruby Programming Language", "O'Reilly Media", 1, Date.parse('4th February 2008'), ['0596516177', '978-0596516178'])
end
it "#Se puede comparar dos objetos Referencias para saber si son iguales" do
expect(@refa == @refb).to be true
end
context "#Se puede comparar dos objetos Referencias para saber cual es mayor o menor según la fecha de publicación" do
it "#La fecha de publicación de la referencia A es más reciente que la de C" do
expect(@refa > @refc).to be true
end
it "#La fecha de publicación de la referencia A es más reciente o igual que la de C" do
expect(@refa >= @refc).to be true
end
it "#La fecha de publicación de la referencia D es más antigua que la de C" do
expect(@refd < @refc).to be true
end
it "#La fecha de publicación de la referencia D es más antigua o igual que la de C" do
expect(@refd < @refc).to be true
end
end
end
describe "Haciendo la clase Lista enumerable" do
before :each do
@list1 = BiblioRefs::List.new(3, 2, 1)
@list2 = BiblioRefs::List.new(4, 5, 6, 7)
@list3 = BiblioRefs::List.new(0, 1, 0)
@list4 = BiblioRefs::List.new(1, 0, 1, 0)
@list5 = BiblioRefs::List.new(false, nil)
end
it "#Comprobrando el método all? con un bloque vacío" do
expect(@list1.all?).to eq(true)
expect(@list2.all?).to eq(true)
expect(@list5.all?).to eq(false)
end
it "#Comprobrando el método any?" do
expect(@list3.any?).to eq(true)
expect(@list4.any?).to eq(true)
expect(@list5.any?).to eq(false)
end
it "#Comprobrando el método collect" do
expect(@list1.map{|i| i*i}).to eq([9, 4, 1])
expect(@list2.map{|i| i*i}).to eq([16, 25, 36, 49])
expect(@list3.collect{|i| i*i}).to eq([0, 1, 0])
expect(@list4.collect{|i| i*i}).to eq([1, 0, 1, 0])
end
it "#Comprobrando el método count" do
expect(@list1.count).to eq(3)
expect(@list2.count).to eq(4)
end
it "#Comprobrando el método detect" do
expect(@list3.detect {|i| i == 0}).to eq(2)
expect(@list4.detect {|i| i == 0}).to eq(1)
expect(@list1.find {|i| i == 1}).to eq(3)
expect(@list2.find {|i| i == 1}).to eq(nil)
end
it "#Comprobrando drop" do
expect(@list3.drop(1)).to eq([1, 0])
expect(@list4.drop(2)).to eq([1, 0])
end
it "#Comprobrando max" do
expect(@list1.max).to eq(3)
expect(@list2.max).to eq(7)
end
it "#Comprobrando min" do
expect(@list3.min).to eq(0)
expect(@list4.min).to eq(0)
end
it "#Comprobrando sort" do
expect(@list1.sort).to eq([1, 2, 3])
expect(@list2.sort).to eq([4, 5, 6, 7])
expect(@list3.sort).to eq([0, 0, 1])
expect(@list4.sort).to eq([0, 0, 1, 1])
end
end
end
Mejorada la expectativa de la clase Lista enumerable para el método detect
require 'spec_helper'
describe BiblioRefs do
before :each do
@ref1 = BiblioRefs::Referencia.new(["Dave Thomas", "Andy Hunt", "Chad Fowler"], "Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide", "The Facets of Ruby", "Pragmatic Bookshelf", 4, Date.parse('7th July 2013'), ['978-1937785499', '1937785491'])
@ref2 = BiblioRefs::Referencia.new("J.R.R Tolkien", "El Hobbit", "Minotauro", 2, Date.parse('1st February 1982'), '0345538374')
end
describe "Comprobación de la inicialización de los atributos de la clase" do
it 'Tiene un número de versión' do
expect(BiblioRefs::VERSION).not_to be nil
end
it 'Deben de existir uno o más autores' do
expect(@ref1.autores).not_to be nil
end
it 'Debe de existir un título' do
expect(@ref1.titulo).not_to be nil
end
it 'Debe o no existir una serie' do
expect(@ref1.serie).not_to be nil
expect(@ref2.serie).to be nil
end
it 'Debe existir una editorial' do
expect(@ref1.editorial).not_to be nil
expect(@ref2.editorial).not_to be nil
end
it 'Debe existir un número de edición' do
expect(@ref1.num_edicion).not_to be nil
expect(@ref2.num_edicion).not_to be nil
end
it 'Debe existir una fecha de publicación' do
expect(@ref1.fecha_publicacion).not_to be nil
expect(@ref2.fecha_publicacion).not_to be nil
end
it 'Debe existir uno o más números ISBN' do
expect(@ref1.isbn).not_to be nil
expect(@ref2.isbn).not_to be nil
end
end
describe "Comprobación de métodos to_s" do
it 'Debe existir un método que devuelva los autores' do
expect(@ref1.autores_to_s).to eq("Dave Thomas, Andy Hunt, Chad Fowler.")
expect(@ref2.autores_to_s).to eq("J.R.R Tolkien.")
end
it 'Debe existir un método que devuelva el título' do
expect(@ref1.titulo_to_s).to eq("Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide")
expect(@ref2.titulo_to_s).to eq("El Hobbit")
end
it 'Debe existir un método que devuelva la serie' do
expect(@ref1.serie_to_s).to eq("(The Facets of Ruby)")
expect(@ref2.serie_to_s).to be nil
end
it 'Debe existir un método que devuelva la editorial' do
expect(@ref1.editorial_to_s).to eq("Pragmatic Bookshelf")
expect(@ref2.editorial_to_s).to eq("Minotauro")
end
it 'Debe existir un método que devuelva el número de edición' do
expect(@ref1.num_edicion_to_s).to eq("4 edition")
expect(@ref2.num_edicion_to_s).to eq("2 edition")
end
it 'Debe existir un método que devuelva la fecha de publicación' do
expect(@ref1.fecha_publicacion_to_s).to eq("July 7, 2013")
expect(@ref2.fecha_publicacion_to_s).to eq("February 1, 1982")
end
it 'Debe existir un método que devuelva el listado de números ISBN' do
expect(@ref1.isbn_to_s).to eq("ISBN-13: 978-1937785499\nISBN-10: 1937785491")
expect(@ref2.isbn_to_s).to eq("ISBN-10: 0345538374")
end
it 'Debe existir un método que devuelva la referencia formateada' do
expect(@ref1.to_s).to eq ("Dave Thomas, Andy Hunt, Chad Fowler.\nProgramming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide\n(The Facets of Ruby)\nPragmatic Bookshelf; 4 edition (July 7, 2013)\nISBN-13: 978-1937785499\nISBN-10: 1937785491")
expect(@ref2.to_s).to eq ("J.R.R Tolkien.\nEl Hobbit\nMinotauro; 2 edition (February 1, 1982)\nISBN-10: 0345538374")
end
end
describe "Nodo" do
before :each do
@nodo1 = Nodo.new("último", nil, nil)
@nodo2 = Nodo.new("primero", @nodo1, nil)
@nodo1[:prev] = @nodo2
end
it '#Debe existir un Nodo en la lista con sus datos y su siguiente' do
expect(@nodo2[:value]).to eq("primero")
expect(@nodo2[:next]).to eq(@nodo1)
end
it '#Debe existir un Nodo con su anterior' do
expect(@nodo1[:prev]).to eq(@nodo2)
end
end
describe "List" do
before :each do
@lista1 = BiblioRefs::List.new("elemento")
@lista2 = BiblioRefs::List.new("elemento1", "elemento2")
end
it '#Debe existir una lista con su cabeza' do
expect(@lista1.head[:value]).to eq("elemento")
expect(@lista2.head[:value]).to eq("elemento1")
end
it '#Debe existir una lista con su cola' do
expect(@lista1.tail[:value]).to eq("elemento")
expect(@lista2.tail[:value]).to eq("elemento2")
end
it '#Se extrae el primer elemento de la lista' do
expect(@lista1.pop).to eq("elemento")
expect(@lista2.pop).to eq("elemento1")
end
it '#Se puede insertar un elemento' do
@lista1.push("nuevo")
expect(@lista1.head[:next][:value]).to eq("nuevo")
expect(@lista1.tail[:prev][:value]).to eq("elemento")
end
it '#Se pueden insertar varios elementos' do
@lista1.push("nuevo1", "nuevo2")
expect(@lista1.head[:next][:value]).to eq("nuevo1")
expect(@lista1.head[:next][:next][:value]).to eq("nuevo2")
expect(@lista1.tail[:prev][:value]).to eq("nuevo1")
expect(@lista1.tail[:prev][:prev][:value]).to eq("elemento")
end
it '#Debe existir un método que devuelve la lista formateada' do
@lista1.push("elemento2", "elemento3")
expect(@lista1.to_s).to eq("Lista: elemento -> elemento2 -> elemento3")
end
end
describe "Lista de referencias" do
before :each do
@refa = BiblioRefs::Referencia.new(["Dave Thomas", "Andy Hunt", "Chad Fowler"], "Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide", "The Facets of Ruby", "Pragmatic Bookshelf", 4, Date.parse('7th July 2013'), ['978-1937785499', '1937785491'])
@refb = BiblioRefs::Referencia.new("Scott Chacon", "Pro Git 2009th Edition", "Pro", "Apress", 2009, Date.parse('27th August 2009'), ['978-1430218333', '1430218339'])
@refc = BiblioRefs::Referencia.new(["David Flanagan", "Yukihiro Matsumoto"], "The Ruby Programming Language", "O'Reilly Media", 1, Date.parse('4th February 2008'), ['0596516177', '978-0596516178'])
@refd = BiblioRefs::Referencia.new(["David Chelimsky", "Dave Astels", "Bryan Helmkamp", "Dan North", "Zach Dennis", "Aslak Hellesoy"], "The RSpec Book: Behaviour Driven Development with RSpec, Cucumber, and Friends", "The Facets of Ruby", "Pragmatic Bookshelf", 1, Date.parse('25th December 2010'), ['1934356379', '978-1934356371'])
@refe = BiblioRefs::Referencia.new("Richard E. Silverman", "Git Pocket Guide", "O'Reilly Media", 1, Date.parse('2nd August 2013'), ['1449325866', '978-1449325862'])
@lista = BiblioRefs::List.new(@refa, @refb, @refc, @refd, @refe)
end
it '#Se puede crear una lista de Referencias Biográficas' do
expect(@lista.to_s).to eq("Lista: #{@refa} -> #{@refb} -> #{@refc} -> #{@refd} -> #{@refe}")
end
end
describe "Jerarquía de clases" do
before :each do
@libro = BiblioRefs::Libro.new
@publicacion = BiblioRefs::PublicacionPeriodica.new
@revista = BiblioRefs::Revista.new
@articulo = BiblioRefs::ArticuloPeriodico.new
@documento = BiblioRefs::DocumentoElectronico.new
end
it "#El objeto de la clase Libro es hijo de la clase Referencia" do
expect(@libro).to be_a BiblioRefs::Referencia
end
it "#El objeto de la clase PublicacionPeriodica es hijo de la clase Referencia" do
expect(@publicacion).to be_a BiblioRefs::Referencia
end
it "#El objeto de la clase Revista es hijo de la clase PublicacionPeriodica" do
expect(@publicacion).to be_a BiblioRefs::PublicacionPeriodica
expect(@publicacion).to be_a BiblioRefs::Referencia
end
it "#El objeto de la clase ArticuloPeriodico es hijo de la clase PublicacionPeriodica" do
expect(@articulo).to be_a BiblioRefs::PublicacionPeriodica
expect(@publicacion).to be_a BiblioRefs::Referencia
end
it "#El objeto de la clase DocumentoElectronico es hijo de la clase PublicacionPeriodica" do
expect(@documento).to be_a BiblioRefs::PublicacionPeriodica
expect(@publicacion).to be_a BiblioRefs::Referencia
end
end
describe "Instancias de la clase Referencia comparables" do
before :each do
@refa = BiblioRefs::Referencia.new(["Dave Thomas", "Andy Hunt", "Chad Fowler"], "Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide", "The Facets of Ruby", "Pragmatic Bookshelf", 4, Date.parse('7th July 2013'), ['978-1937785499', '1937785491'])
@refb = BiblioRefs::Referencia.new(["Dave Thomas", "Andy Hunt", "Chad Fowler"], "Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide", "The Facets of Ruby", "Pragmatic Bookshelf", 4, Date.parse('7th July 2013'), ['978-1937785499', '1937785491'])
@refc = BiblioRefs::Referencia.new("Scott Chacon", "Pro Git 2009th Edition", "Pro", "Apress", 2009, Date.parse('27th August 2009'), ['978-1430218333', '1430218339'])
@refd = BiblioRefs::Referencia.new(["David Flanagan", "Yukihiro Matsumoto"], "The Ruby Programming Language", "O'Reilly Media", 1, Date.parse('4th February 2008'), ['0596516177', '978-0596516178'])
end
it "#Se puede comparar dos objetos Referencias para saber si son iguales" do
expect(@refa == @refb).to be true
end
context "#Se puede comparar dos objetos Referencias para saber cual es mayor o menor según la fecha de publicación" do
it "#La fecha de publicación de la referencia A es más reciente que la de C" do
expect(@refa > @refc).to be true
end
it "#La fecha de publicación de la referencia A es más reciente o igual que la de C" do
expect(@refa >= @refc).to be true
end
it "#La fecha de publicación de la referencia D es más antigua que la de C" do
expect(@refd < @refc).to be true
end
it "#La fecha de publicación de la referencia D es más antigua o igual que la de C" do
expect(@refd < @refc).to be true
end
end
end
describe "Haciendo la clase Lista enumerable" do
before :each do
@list1 = BiblioRefs::List.new(3, 2, 1)
@list2 = BiblioRefs::List.new(4, 5, 6, 7)
@list3 = BiblioRefs::List.new(0, 1, 0)
@list4 = BiblioRefs::List.new(1, 0, 1, 0)
@list5 = BiblioRefs::List.new(false, nil)
end
it "#Comprobrando el método all? con un bloque vacío" do
expect(@list1.all?).to eq(true)
expect(@list2.all?).to eq(true)
expect(@list5.all?).to eq(false)
end
it "#Comprobrando el método any?" do
expect(@list3.any?).to eq(true)
expect(@list4.any?).to eq(true)
expect(@list5.any?).to eq(false)
end
it "#Comprobrando el método collect" do
expect(@list1.map{|i| i*i}).to eq([9, 4, 1])
expect(@list2.map{|i| i*i}).to eq([16, 25, 36, 49])
expect(@list3.collect{|i| i*i}).to eq([0, 1, 0])
expect(@list4.collect{|i| i*i}).to eq([1, 0, 1, 0])
end
it "#Comprobrando el método count" do
expect(@list1.count).to eq(3)
expect(@list2.count).to eq(4)
end
it "#Comprobrando el método detect" do
expect(@list3.detect {|i| i == 0}).to eq(0)
expect(@list4.detect {|i| i % 1 == 0}).to eq(1)
expect(@list1.find {|i| i == 4}).to eq(nil)
expect(@list2.find {|i| i % 6 == 1}).to eq(7)
end
it "#Comprobrando drop" do
expect(@list3.drop(1)).to eq([1, 0])
expect(@list4.drop(2)).to eq([1, 0])
end
it "#Comprobrando max" do
expect(@list1.max).to eq(3)
expect(@list2.max).to eq(7)
end
it "#Comprobrando min" do
expect(@list3.min).to eq(0)
expect(@list4.min).to eq(0)
end
it "#Comprobrando sort" do
expect(@list1.sort).to eq([1, 2, 3])
expect(@list2.sort).to eq([4, 5, 6, 7])
expect(@list3.sort).to eq([0, 0, 1])
expect(@list4.sort).to eq([0, 0, 1, 1])
end
end
end |
require 'fileutils'
class Dir
class << self
alias_method :orig_bracket, :[]
end
def self.[](*args)
orig_bracket(*args).sort
end
end
describe Rscons do
BUILD_TEST_RUN_DIR = "build_test_run"
def rm_rf(dir)
FileUtils.rm_rf(dir)
if File.exists?(dir)
sleep 0.2
FileUtils.rm_rf(dir)
if File.exists?(dir)
sleep 0.5
FileUtils.rm_rf(dir)
if File.exists?(dir)
sleep 1.0
FileUtils.rm_rf(dir)
if File.exists?(dir)
raise "Could not remove #{dir}"
end
end
end
end
end
before(:all) do
rm_rf(BUILD_TEST_RUN_DIR)
@owd = Dir.pwd
end
before(:each) do
@saved_stdout = $stdout
$stdout = StringIO.new
@saved_stderr = $stderr
$stderr = StringIO.new
end
after(:each) do
$stdout = @saved_stdout
$stderr = @saved_stderr
Dir.chdir(@owd)
rm_rf(BUILD_TEST_RUN_DIR)
end
def test_dir(build_test_directory)
FileUtils.cp_r("build_tests/#{build_test_directory}", BUILD_TEST_RUN_DIR)
Dir.chdir(BUILD_TEST_RUN_DIR)
end
def file_sub(fname)
contents = File.read(fname)
replaced = ''
contents.each_line do |line|
replaced += yield(line)
end
File.open(fname, 'wb') do |fh|
fh.write(replaced)
end
end
def lines
rv = ($stdout.string + $stderr.string).lines.map(&:rstrip)
$stdout.string = ""
$stderr.string = ""
rv
end
###########################################################################
# Tests
###########################################################################
it 'builds a C program with one source file' do
test_dir('simple')
Rscons::Environment.new do |env|
env.Program('simple', Dir['*.c'])
end
expect(File.exists?('simple.o')).to be_truthy
expect(`./simple`).to eq "This is a simple C program\n"
end
it 'prints commands as they are executed' do
test_dir('simple')
env = Rscons::Environment.new(echo: :command) do |env|
env["LD"] = "gcc"
env.Program('simple', Dir['*.c'])
end
expect(lines).to eq [
'gcc -c -o simple.o -MMD -MF simple.mf simple.c',
"gcc -o simple#{env["PROGSUFFIX"]} simple.o",
]
end
it 'prints short representations of the commands being executed' do
test_dir('header')
env = Rscons::Environment.new do |env|
env.Program('header', Dir['*.c'])
end
expect(lines).to eq [
'CC header.o',
"LD header#{env["PROGSUFFIX"]}",
]
end
it 'builds a C program with one source file and one header file' do
test_dir('header')
Rscons::Environment.new do |env|
env.Program('header', Dir['*.c'])
end
expect(File.exists?('header.o')).to be_truthy
expect(`./header`).to eq "The value is 2\n"
end
it 'rebuilds a C module when a header it depends on changes' do
test_dir('header')
make_env = lambda do
Rscons::Environment.new do |env|
env.Program('header', Dir['*.c'])
end
end
make_env[]
expect(`./header`).to eq "The value is 2\n"
file_sub('header.h') {|line| line.sub(/2/, '5')}
make_env[]
expect(`./header`).to eq "The value is 5\n"
end
it 'does not rebuild a C module when its dependencies have not changed' do
test_dir('header')
make_env = lambda do
Rscons::Environment.new do |env|
env.Program('header', Dir['*.c'])
end
end
env = make_env[]
expect(`./header`).to eq "The value is 2\n"
expect(lines).to eq [
'CC header.o',
"LD header#{env["PROGSUFFIX"]}",
]
make_env[]
expect(lines).to eq []
end
it "does not rebuild a C module when only the file's timestamp has changed" do
test_dir('header')
make_env = lambda do
Rscons::Environment.new do |env|
env.Program('header', Dir['*.c'])
end
end
env = make_env[]
expect(`./header`).to eq "The value is 2\n"
expect(lines).to eq [
'CC header.o',
"LD header#{env["PROGSUFFIX"]}",
]
sleep 0.05
file_sub('header.c') {|line| line}
make_env[]
expect(lines).to eq []
end
it 're-links a program when the link flags have changed' do
test_dir('simple')
env = Rscons::Environment.new(echo: :command) do |env|
env.Program('simple', Dir['*.c'])
end
expect(lines).to eq [
'gcc -c -o simple.o -MMD -MF simple.mf simple.c',
"gcc -o simple#{env["PROGSUFFIX"]} simple.o",
]
e2 = Rscons::Environment.new(echo: :command) do |env|
env["LIBPATH"] += ["libdir"]
env.Program('simple', Dir['*.c'])
end
expect(lines).to eq ["gcc -o simple#{env["PROGSUFFIX"]} simple.o -Llibdir"]
end
it 'builds object files in a different build directory' do
test_dir('build_dir')
Rscons::Environment.new do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_dir(%r{^src/([^/]+)/}, 'build_\\1/')
env.Program('build_dir', Dir['src/**/*.c'])
end
expect(`./build_dir`).to eq "Hello from two()\n"
expect(File.exists?('build_one/one.o')).to be_truthy
expect(File.exists?('build_two/two.o')).to be_truthy
end
it "supports trailing slashes at the end of build_dir sources and destinations" do
test_dir("build_dir")
Rscons::Environment.new do |env|
env.append("CPPPATH" => Dir["src/**/*/"])
env.build_dir("src/one/", "build_one/")
env.build_dir("src/two", "build_two")
env.Program("build_dir", Dir["src/**/*.c"])
end
expect(`./build_dir`).to eq "Hello from two()\n"
expect(File.exists?("build_one/one.o")).to be_truthy
expect(File.exists?("build_two/two.o")).to be_truthy
end
it 'uses build directories before build root' do
test_dir('build_dir')
env = Rscons::Environment.new do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_dir("src", "build")
env.build_root = "build_root"
env.Program('build_dir', Dir['src/**/*.c'])
end
expect(lines).to eq ["CC build/one/one.o", "CC build/two/two.o", "LD build_dir#{env["PROGSUFFIX"]}"]
end
it 'uses build_root if no build directories match' do
test_dir('build_dir')
Rscons::Environment.new do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_dir("src2", "build")
env.build_root = "build_root"
env.Program('build_dir.exe', Dir['src/**/*.c'])
end
expect(lines).to eq ["CC build_root/src/one/one.o", "CC build_root/src/two/two.o", "LD build_dir.exe"]
end
it "expands target and source paths starting with ^/ to be relative to the build root" do
test_dir('build_dir')
env = Rscons::Environment.new(echo: :command) do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_root = "build_root"
FileUtils.mkdir_p(env.build_root)
FileUtils.mv("src/one/one.c", "build_root")
env.Object("^/one.o", "^/one.c")
env.Program('build_dir', Dir['src/**/*.c'] + ["^/one.o"])
end
expect(lines).to eq [
%q{gcc -c -o build_root/one.o -MMD -MF build_root/one.mf -Isrc/one/ -Isrc/two/ build_root/one.c},
%q{gcc -c -o build_root/src/two/two.o -MMD -MF build_root/src/two/two.mf -Isrc/one/ -Isrc/two/ src/two/two.c},
%Q{gcc -o build_dir#{env["PROGSUFFIX"]} build_root/src/two/two.o build_root/one.o},
]
end
it 'supports simple builders' do
test_dir('json_to_yaml')
Rscons::Environment.new do |env|
require 'json'
require 'yaml'
env.add_builder(:JsonToYaml) do |target, sources, cache, env, vars|
unless cache.up_to_date?(target, :JsonToYaml, sources, env)
cache.mkdir_p(File.dirname(target))
File.open(target, 'w') do |f|
f.write(YAML.dump(JSON.load(IO.read(sources.first))))
end
cache.register_build(target, :JsonToYaml, sources, env)
end
target
end
env.JsonToYaml('foo.yml','foo.json')
end
expect(File.exists?('foo.yml')).to be_truthy
expect(IO.read('foo.yml')).to eq("---\nkey: value\n")
end
it 'cleans built files' do
test_dir('build_dir')
Rscons::Environment.new do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_dir(%r{^src/([^/]+)/}, 'build_\\1/')
env.Program('build_dir', Dir['src/**/*.c'])
end
expect(`./build_dir`).to eq "Hello from two()\n"
expect(File.exists?('build_one/one.o')).to be_truthy
expect(File.exists?('build_two/two.o')).to be_truthy
Rscons.clean
expect(File.exists?('build_one/one.o')).to be_falsey
expect(File.exists?('build_two/two.o')).to be_falsey
expect(File.exists?('build_one')).to be_falsey
expect(File.exists?('build_two')).to be_falsey
expect(File.exists?('src/one/one.c')).to be_truthy
end
it 'does not clean created directories if other non-rscons-generated files reside there' do
test_dir('build_dir')
Rscons::Environment.new do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_dir(%r{^src/([^/]+)/}, 'build_\\1/')
env.Program('build_dir', Dir['src/**/*.c'])
end
expect(`./build_dir`).to eq "Hello from two()\n"
expect(File.exists?('build_one/one.o')).to be_truthy
expect(File.exists?('build_two/two.o')).to be_truthy
File.open('build_two/tmp', 'w') { |fh| fh.puts "dum" }
Rscons.clean
expect(File.exists?('build_one/one.o')).to be_falsey
expect(File.exists?('build_two/two.o')).to be_falsey
expect(File.exists?('build_one')).to be_falsey
expect(File.exists?('build_two')).to be_truthy
expect(File.exists?('src/one/one.c')).to be_truthy
end
it 'allows Ruby classes as custom builders to be used to construct files' do
test_dir('custom_builder')
class MySource < Rscons::Builder
def run(target, sources, cache, env, vars)
File.open(target, 'w') do |fh|
fh.puts <<EOF
#define THE_VALUE 5678
EOF
end
target
end
end
env = Rscons::Environment.new do |env|
env.add_builder(MySource.new)
env.MySource('inc.h', [])
env.Program('program', Dir['*.c'])
end
expect(lines).to eq ["CC program.o", "LD program#{env["PROGSUFFIX"]}"]
expect(File.exists?('inc.h')).to be_truthy
expect(`./program`).to eq "The value is 5678\n"
end
it 'supports custom builders with multiple targets' do
test_dir('custom_builder')
class CHGen < Rscons::Builder
def run(target, sources, cache, env, vars)
c_fname = target
h_fname = target.sub(/\.c$/, ".h")
unless cache.up_to_date?([c_fname, h_fname], "", sources, env)
puts "CHGen #{c_fname}"
File.open(c_fname, "w") {|fh| fh.puts "int THE_VALUE = 42;"}
File.open(h_fname, "w") {|fh| fh.puts "extern int THE_VALUE;"}
cache.register_build([c_fname, h_fname], "", sources, env)
end
target
end
end
make_env = lambda do
Rscons::Environment.new do |env|
env.add_builder(CHGen.new)
env.CHGen("inc.c", ["program.c"])
env.Program("program", %w[program.c inc.c])
end
end
env = make_env[]
expect(lines).to eq ["CHGen inc.c", "CC program.o", "CC inc.o", "LD program#{env["PROGSUFFIX"]}"]
expect(File.exists?("inc.c")).to be_truthy
expect(File.exists?("inc.h")).to be_truthy
expect(`./program`).to eq "The value is 42\n"
File.open("inc.c", "w") {|fh| fh.puts "int THE_VALUE = 33;"}
make_env[]
expect(lines).to eq ["CHGen inc.c"]
expect(`./program`).to eq "The value is 42\n"
end
it 'allows cloning Environment objects' do
test_dir('clone_env')
debug = Rscons::Environment.new(echo: :command) do |env|
env.build_dir('src', 'debug')
env['CFLAGS'] = '-O2'
env['CPPFLAGS'] = '-DSTRING="Debug Version"'
env.Program('program-debug', Dir['src/*.c'])
end
release = debug.clone do |env|
env["CPPFLAGS"] = '-DSTRING="Release Version"'
env.build_dir('src', 'release')
env.Program('program-release', Dir['src/*.c'])
end
expect(lines).to eq [
%q{gcc -c -o debug/program.o -MMD -MF debug/program.mf '-DSTRING="Debug Version"' -O2 src/program.c},
%Q{gcc -o program-debug#{debug["PROGSUFFIX"]} debug/program.o},
%q{gcc -c -o release/program.o -MMD -MF release/program.mf '-DSTRING="Release Version"' -O2 src/program.c},
%Q{gcc -o program-release#{debug["PROGSUFFIX"]} release/program.o},
]
end
it 'allows cloning all attributes of an Environment object' do
test_dir('clone_env')
built_targets = []
env1 = Rscons::Environment.new(echo: :command) do |env|
env.build_dir('src', 'build')
env['CFLAGS'] = '-O2'
env.add_build_hook do |build_op|
build_op[:vars]['CPPFLAGS'] = '-DSTRING="Hello"'
end
env.add_post_build_hook do |build_op|
built_targets << build_op[:target]
end
env.Program('program', Dir['src/*.c'])
end
env2 = env1.clone(clone: :all) do |env|
env.Program('program2', Dir['src/*.c'])
end
expect(lines).to eq [
%q{gcc -c -o build/program.o -MMD -MF build/program.mf -DSTRING="Hello" -O2 src/program.c},
%Q{gcc -o program#{env1["PROGSUFFIX"]} build/program.o},
%Q{gcc -o program2#{env2["PROGSUFFIX"]} build/program.o},
]
expect(built_targets).to eq([
"build/program.o",
"program#{env1['PROGSUFFIX']}",
"build/program.o",
"program2#{env1['PROGSUFFIX']}",
])
end
it 'builds a C++ program with one source file' do
test_dir('simple_cc')
Rscons::Environment.new do |env|
env.Program('simple', Dir['*.cc'])
end
expect(File.exists?('simple.o')).to be_truthy
expect(`./simple`).to eq "This is a simple C++ program\n"
end
it 'allows overriding construction variables for individual builder calls' do
test_dir('two_sources')
env = Rscons::Environment.new(echo: :command) do |env|
env.Object("one.o", "one.c", 'CPPFLAGS' => ['-DONE'])
env.Program('two_sources', ['one.o', 'two.c'])
end
expect(lines).to eq [
'gcc -c -o one.o -MMD -MF one.mf -DONE one.c',
'gcc -c -o two.o -MMD -MF two.mf two.c',
"gcc -o two_sources#{env["PROGSUFFIX"]} one.o two.o",
]
expect(File.exists?("two_sources#{env["PROGSUFFIX"]}")).to be_truthy
expect(`./two_sources`).to eq "This is a C program with two sources.\n"
end
it 'builds a static library archive' do
test_dir('library')
env = Rscons::Environment.new(echo: :command) do |env|
env.Program('library', ['lib.a', 'three.c'])
env.Library("lib.a", ['one.c', 'two.c'], 'CPPFLAGS' => ['-Dmake_lib'])
end
expect(lines).to eq [
'gcc -c -o one.o -MMD -MF one.mf -Dmake_lib one.c',
'gcc -c -o two.o -MMD -MF two.mf -Dmake_lib two.c',
'ar rcs lib.a one.o two.o',
'gcc -c -o three.o -MMD -MF three.mf three.c',
"gcc -o library#{env["PROGSUFFIX"]} lib.a three.o",
]
expect(File.exists?("library#{env["PROGSUFFIX"]}")).to be_truthy
expect(`ar t lib.a`).to eq "one.o\ntwo.o\n"
end
it 'supports build hooks to override construction variables' do
test_dir("build_dir")
env = Rscons::Environment.new(echo: :command) do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_dir(%r{^src/([^/]+)/}, 'build_\\1/')
env.add_build_hook do |build_op|
if build_op[:target] =~ %r{build_one/.*\.o}
build_op[:vars]["CFLAGS"] << "-O1"
elsif build_op[:target] =~ %r{build_two/.*\.o}
build_op[:vars]["CFLAGS"] << "-O2"
end
end
env.Program('build_hook.exe', Dir['src/**/*.c'])
end
expect(`./build_hook.exe`).to eq "Hello from two()\n"
expect(lines).to match_array [
'gcc -c -o build_one/one.o -MMD -MF build_one/one.mf -Isrc/one/ -Isrc/two/ -O1 src/one/one.c',
'gcc -c -o build_two/two.o -MMD -MF build_two/two.mf -Isrc/one/ -Isrc/two/ -O2 src/two/two.c',
'gcc -o build_hook.exe build_one/one.o build_two/two.o',
]
end
it 'rebuilds when user-specified dependencies change' do
test_dir('simple')
env = Rscons::Environment.new do |env|
env.Program('simple.exe', Dir['*.c']).depends("file.ld")
File.open("file.ld", "w") do |fh|
fh.puts("foo")
end
end
expect(lines).to eq ["CC simple.o", "LD simple.exe"]
expect(File.exists?('simple.o')).to be_truthy
expect(`./simple.exe`).to eq "This is a simple C program\n"
e2 = Rscons::Environment.new do |env|
program = env.Program('simple.exe', Dir['*.c'])
env.depends(program, "file.ld")
File.open("file.ld", "w") do |fh|
fh.puts("bar")
end
end
expect(lines).to eq ["LD simple.exe"]
e3 = Rscons::Environment.new do |env|
env.Program('simple.exe', Dir['*.c'])
File.unlink("file.ld")
end
expect(lines).to eq ["LD simple.exe"]
Rscons::Environment.new do |env|
env.Program('simple.exe', Dir['*.c'])
end
expect(lines).to eq []
end
unless ENV["omit_gdc_tests"]
it "supports building D sources" do
test_dir("d")
Rscons::Environment.new(echo: :command) do |env|
env.Program("hello-d.exe", Dir["*.d"])
end
expect(lines).to eq [
"gdc -c -o main.o main.d",
"gdc -o hello-d.exe main.o",
]
expect(`./hello-d.exe`.rstrip).to eq "Hello from D!"
end
end
it "supports disassembling object files" do
test_dir("simple")
Rscons::Environment.new do |env|
env.Object("simple.o", "simple.c")
env.Disassemble("simple.txt", "simple.o")
end
expect(File.exists?("simple.txt")).to be_truthy
expect(File.read("simple.txt")).to match /Disassembly of section .text:/
end
it "supports preprocessing C sources" do
test_dir("simple")
Rscons::Environment.new do |env|
env.Preprocess("simplepp.c", "simple.c")
env.Program("simple", "simplepp.c")
end
expect(File.read("simplepp.c")).to match /# \d+ "simple.c"/
expect(`./simple`).to eq "This is a simple C program\n"
end
it "supports preprocessing C++ sources" do
test_dir("simple_cc")
Rscons::Environment.new do |env|
env.Preprocess("simplepp.cc", "simple.cc")
env.Program("simple", "simplepp.cc")
end
expect(File.read("simplepp.cc")).to match /# \d+ "simple.cc"/
expect(`./simple`).to eq "This is a simple C++ program\n"
end
it "supports invoking builders with no sources and a build_root defined" do
class TestBuilder < Rscons::Builder
def run(target, sources, cache, env, vars)
target
end
end
test_dir("simple")
Rscons::Environment.new do |env|
env.build_root = "build"
env.add_builder(TestBuilder.new)
env.TestBuilder("file")
end
end
it "expands construction variables in builder target and sources before invoking the builder" do
test_dir('custom_builder')
class MySource < Rscons::Builder
def run(target, sources, cache, env, vars)
File.open(target, 'w') do |fh|
fh.puts <<EOF
#define THE_VALUE 678
EOF
end
target
end
end
env = Rscons::Environment.new do |env|
env["hdr"] = "inc.h"
env["src"] = "program.c"
env.add_builder(MySource.new)
env.MySource('${hdr}')
env.Program('program', "${src}")
end
expect(lines).to eq ["CC program.o", "LD program#{env["PROGSUFFIX"]}"]
expect(File.exists?('inc.h')).to be_truthy
expect(`./program`).to eq "The value is 678\n"
end
it "supports lambdas as construction variable values" do
env = Rscons::Environment.new do |env|
env["prefix"] = "-H"
env["suffix"] = "xyz"
env[:cfg] = {val: 44}
env["computed"] = lambda do |args|
"#{args[:env]['prefix']}#{args[:env][:cfg][:val]}#{args[:env]['suffix']}"
end
env["lambda_recurse"] = lambda do |args|
"${prefix}ello"
end
end
e2 = env.clone
e2[:cfg][:val] = 38
expect(env.expand_varref("${computed}")).to eq("-H44xyz")
expect(e2.expand_varref("${computed}")).to eq("-H38xyz")
expect(env.expand_varref("${lambda_recurse}")).to eq("-Hello")
end
it "supports registering build targets from within a build hook" do
test_dir("simple")
Rscons::Environment.new do |env|
env.Program("simple", Dir["*.c"])
env.add_build_hook do |build_op|
if build_op[:target].end_with?(".o")
env.Disassemble("#{build_op[:target]}.txt", build_op[:target])
end
end
end
expect(File.exists?("simple.o")).to be_truthy
expect(File.exists?("simple.o.txt")).to be_truthy
expect(`./simple`).to eq "This is a simple C program\n"
end
it "supports post-build hooks" do
test_dir("simple")
built_targets = []
env = Rscons::Environment.new do |env|
env.Program("simple", Dir["*.c"])
env.add_post_build_hook do |build_op|
built_targets << build_op[:target]
expect(File.exists?(build_op[:target])).to be_truthy
end
end
expect(File.exists?("simple.o")).to be_truthy
expect(`./simple`).to eq "This is a simple C program\n"
expect(built_targets).to eq ["simple.o", "simple#{env["PROGSUFFIX"]}"]
end
it "supports multiple values for CXXSUFFIX" do
test_dir("simple_cc")
File.open("other.cccc", "w") {|fh| fh.puts}
Rscons::Environment.new do |env|
env["CXXSUFFIX"] = %w[.cccc .cc]
env["CXXFLAGS"] += %w[-x c++]
env.Program("simple", Dir["*.cc"] + ["other.cccc"])
end
expect(File.exists?("simple.o")).to be_truthy
expect(File.exists?("other.o")).to be_truthy
expect(`./simple`).to eq "This is a simple C++ program\n"
end
it "supports multiple values for CSUFFIX" do
test_dir("build_dir")
FileUtils.mv("src/one/one.c", "src/one/one.yargh")
Rscons::Environment.new do |env|
env["CSUFFIX"] = %w[.yargh .c]
env["CFLAGS"] += %w[-x c]
env["CPPPATH"] += Dir["src/**/"]
env.Program("build_dir", Dir["src/**/*.{c,yargh}"])
end
expect(File.exists?("src/one/one.o")).to be_truthy
expect(File.exists?("src/two/two.o")).to be_truthy
expect(`./build_dir`).to eq "Hello from two()\n"
end
it "supports multiple values for OBJSUFFIX" do
test_dir("two_sources")
env = Rscons::Environment.new() do |env|
env["OBJSUFFIX"] = %w[.oooo .ooo]
env.Object("one.oooo", "one.c", "CPPFLAGS" => ["-DONE"])
env.Object("two.ooo", "two.c")
env.Program("two_sources", %w[one.oooo two.ooo])
end
expect(File.exists?("two_sources#{env["PROGSUFFIX"]}")).to be_truthy
expect(`./two_sources`).to eq "This is a C program with two sources.\n"
end
it "supports multiple values for LIBSUFFIX" do
test_dir("two_sources")
env = Rscons::Environment.new() do |env|
env["LIBSUFFIX"] = %w[.aaaa .aaa]
env.Library("one.aaaa", "one.c", "CPPFLAGS" => ["-DONE"])
env.Library("two.aaa", "two.c")
env.Program("two_sources", %w[one.aaaa two.aaa])
end
expect(File.exists?("two_sources#{env["PROGSUFFIX"]}")).to be_truthy
expect(`./two_sources`).to eq "This is a C program with two sources.\n"
end
it "supports multiple values for ASSUFFIX" do
test_dir("two_sources")
env = Rscons::Environment.new() do |env|
env["ASSUFFIX"] = %w[.ssss .sss]
env["CFLAGS"] += %w[-S]
env.Object("one.ssss", "one.c", "CPPFLAGS" => ["-DONE"])
env.Object("two.sss", "two.c")
env.Program("two_sources", %w[one.ssss two.sss], "ASFLAGS" => env["ASFLAGS"] + %w[-x assembler])
end
expect(lines).to eq([
"CC one.ssss",
"CC two.sss",
"AS one.o",
"AS two.o",
"LD two_sources#{env["PROGSUFFIX"]}",
])
expect(File.exists?("two_sources#{env["PROGSUFFIX"]}")).to be_truthy
expect(`./two_sources`).to eq "This is a C program with two sources.\n"
end
it "supports dumping an Environment's construction variables" do
test_dir("simple")
env = Rscons::Environment.new do |env|
env["CFLAGS"] += %w[-O2 -fomit-frame-pointer]
env[:foo] = :bar
end
env.dump
result = lines
expect(result.include?(%{:foo => :bar})).to be_truthy
expect(result.include?(%{CFLAGS => ["-O2", "-fomit-frame-pointer"]})).to be_truthy
expect(result.include?(%{CPPPATH => []})).to be_truthy
end
it "considers deep dependencies when deciding whether to rerun Preprocess builder" do
test_dir("preprocess")
env = Rscons::Environment.new do |env|
env.Preprocess("pp", "foo.h")
end
expect(File.read("pp")).to match(%r{xyz42abc}m)
expect(lines).to eq(["Preprocess pp"])
env.Preprocess("pp", "foo.h")
env.process
expect(lines).to eq([])
File.open("bar.h", "w") do |fh|
fh.puts "#define BAR abc88xyz"
end
$ttt = true
env.Preprocess("pp", "foo.h")
env.process
expect(lines).to eq(["Preprocess pp"])
expect(File.read("pp")).to match(%r{abc88xyz}m)
end
it "allows construction variable references which expand to arrays in sources of a build target" do
test_dir("simple")
Rscons::Environment.new do |env|
env["sources"] = Dir["*.c"]
env.Program("simple", "${sources}")
end
expect(File.exists?("simple.o")).to be_truthy
expect(`./simple`).to eq "This is a simple C program\n"
end
it "supports registering multiple build targets with the same target path" do
test_dir("build_dir")
Rscons::Environment.new do |env|
env["CPPPATH"] << "src/two"
env.Object("one.o", "src/one/one.c")
env.Object("one.o", "src/two/two.c")
end
expect(File.exists?("one.o")).to be_truthy
expect(lines).to eq([
"CC one.o",
"CC one.o",
])
end
end
test expanding paths after a build target is registered from within a build hook
require 'fileutils'
class Dir
class << self
alias_method :orig_bracket, :[]
end
def self.[](*args)
orig_bracket(*args).sort
end
end
describe Rscons do
BUILD_TEST_RUN_DIR = "build_test_run"
def rm_rf(dir)
FileUtils.rm_rf(dir)
if File.exists?(dir)
sleep 0.2
FileUtils.rm_rf(dir)
if File.exists?(dir)
sleep 0.5
FileUtils.rm_rf(dir)
if File.exists?(dir)
sleep 1.0
FileUtils.rm_rf(dir)
if File.exists?(dir)
raise "Could not remove #{dir}"
end
end
end
end
end
before(:all) do
rm_rf(BUILD_TEST_RUN_DIR)
@owd = Dir.pwd
end
before(:each) do
@saved_stdout = $stdout
$stdout = StringIO.new
@saved_stderr = $stderr
$stderr = StringIO.new
end
after(:each) do
$stdout = @saved_stdout
$stderr = @saved_stderr
Dir.chdir(@owd)
rm_rf(BUILD_TEST_RUN_DIR)
end
def test_dir(build_test_directory)
FileUtils.cp_r("build_tests/#{build_test_directory}", BUILD_TEST_RUN_DIR)
Dir.chdir(BUILD_TEST_RUN_DIR)
end
def file_sub(fname)
contents = File.read(fname)
replaced = ''
contents.each_line do |line|
replaced += yield(line)
end
File.open(fname, 'wb') do |fh|
fh.write(replaced)
end
end
def lines
rv = ($stdout.string + $stderr.string).lines.map(&:rstrip)
$stdout.string = ""
$stderr.string = ""
rv
end
###########################################################################
# Tests
###########################################################################
it 'builds a C program with one source file' do
test_dir('simple')
Rscons::Environment.new do |env|
env.Program('simple', Dir['*.c'])
end
expect(File.exists?('simple.o')).to be_truthy
expect(`./simple`).to eq "This is a simple C program\n"
end
it 'prints commands as they are executed' do
test_dir('simple')
env = Rscons::Environment.new(echo: :command) do |env|
env["LD"] = "gcc"
env.Program('simple', Dir['*.c'])
end
expect(lines).to eq [
'gcc -c -o simple.o -MMD -MF simple.mf simple.c',
"gcc -o simple#{env["PROGSUFFIX"]} simple.o",
]
end
it 'prints short representations of the commands being executed' do
test_dir('header')
env = Rscons::Environment.new do |env|
env.Program('header', Dir['*.c'])
end
expect(lines).to eq [
'CC header.o',
"LD header#{env["PROGSUFFIX"]}",
]
end
it 'builds a C program with one source file and one header file' do
test_dir('header')
Rscons::Environment.new do |env|
env.Program('header', Dir['*.c'])
end
expect(File.exists?('header.o')).to be_truthy
expect(`./header`).to eq "The value is 2\n"
end
it 'rebuilds a C module when a header it depends on changes' do
test_dir('header')
make_env = lambda do
Rscons::Environment.new do |env|
env.Program('header', Dir['*.c'])
end
end
make_env[]
expect(`./header`).to eq "The value is 2\n"
file_sub('header.h') {|line| line.sub(/2/, '5')}
make_env[]
expect(`./header`).to eq "The value is 5\n"
end
it 'does not rebuild a C module when its dependencies have not changed' do
test_dir('header')
make_env = lambda do
Rscons::Environment.new do |env|
env.Program('header', Dir['*.c'])
end
end
env = make_env[]
expect(`./header`).to eq "The value is 2\n"
expect(lines).to eq [
'CC header.o',
"LD header#{env["PROGSUFFIX"]}",
]
make_env[]
expect(lines).to eq []
end
it "does not rebuild a C module when only the file's timestamp has changed" do
test_dir('header')
make_env = lambda do
Rscons::Environment.new do |env|
env.Program('header', Dir['*.c'])
end
end
env = make_env[]
expect(`./header`).to eq "The value is 2\n"
expect(lines).to eq [
'CC header.o',
"LD header#{env["PROGSUFFIX"]}",
]
sleep 0.05
file_sub('header.c') {|line| line}
make_env[]
expect(lines).to eq []
end
it 're-links a program when the link flags have changed' do
test_dir('simple')
env = Rscons::Environment.new(echo: :command) do |env|
env.Program('simple', Dir['*.c'])
end
expect(lines).to eq [
'gcc -c -o simple.o -MMD -MF simple.mf simple.c',
"gcc -o simple#{env["PROGSUFFIX"]} simple.o",
]
e2 = Rscons::Environment.new(echo: :command) do |env|
env["LIBPATH"] += ["libdir"]
env.Program('simple', Dir['*.c'])
end
expect(lines).to eq ["gcc -o simple#{env["PROGSUFFIX"]} simple.o -Llibdir"]
end
it 'builds object files in a different build directory' do
test_dir('build_dir')
Rscons::Environment.new do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_dir(%r{^src/([^/]+)/}, 'build_\\1/')
env.Program('build_dir', Dir['src/**/*.c'])
end
expect(`./build_dir`).to eq "Hello from two()\n"
expect(File.exists?('build_one/one.o')).to be_truthy
expect(File.exists?('build_two/two.o')).to be_truthy
end
it "supports trailing slashes at the end of build_dir sources and destinations" do
test_dir("build_dir")
Rscons::Environment.new do |env|
env.append("CPPPATH" => Dir["src/**/*/"])
env.build_dir("src/one/", "build_one/")
env.build_dir("src/two", "build_two")
env.Program("build_dir", Dir["src/**/*.c"])
end
expect(`./build_dir`).to eq "Hello from two()\n"
expect(File.exists?("build_one/one.o")).to be_truthy
expect(File.exists?("build_two/two.o")).to be_truthy
end
it 'uses build directories before build root' do
test_dir('build_dir')
env = Rscons::Environment.new do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_dir("src", "build")
env.build_root = "build_root"
env.Program('build_dir', Dir['src/**/*.c'])
end
expect(lines).to eq ["CC build/one/one.o", "CC build/two/two.o", "LD build_dir#{env["PROGSUFFIX"]}"]
end
it 'uses build_root if no build directories match' do
test_dir('build_dir')
Rscons::Environment.new do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_dir("src2", "build")
env.build_root = "build_root"
env.Program('build_dir.exe', Dir['src/**/*.c'])
end
expect(lines).to eq ["CC build_root/src/one/one.o", "CC build_root/src/two/two.o", "LD build_dir.exe"]
end
it "expands target and source paths starting with ^/ to be relative to the build root" do
test_dir('build_dir')
env = Rscons::Environment.new(echo: :command) do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_root = "build_root"
FileUtils.mkdir_p(env.build_root)
FileUtils.mv("src/one/one.c", "build_root")
env.Object("^/one.o", "^/one.c")
env.Program('build_dir', Dir['src/**/*.c'] + ["^/one.o"])
end
expect(lines).to eq [
%q{gcc -c -o build_root/one.o -MMD -MF build_root/one.mf -Isrc/one/ -Isrc/two/ build_root/one.c},
%q{gcc -c -o build_root/src/two/two.o -MMD -MF build_root/src/two/two.mf -Isrc/one/ -Isrc/two/ src/two/two.c},
%Q{gcc -o build_dir#{env["PROGSUFFIX"]} build_root/src/two/two.o build_root/one.o},
]
end
it 'supports simple builders' do
test_dir('json_to_yaml')
Rscons::Environment.new do |env|
require 'json'
require 'yaml'
env.add_builder(:JsonToYaml) do |target, sources, cache, env, vars|
unless cache.up_to_date?(target, :JsonToYaml, sources, env)
cache.mkdir_p(File.dirname(target))
File.open(target, 'w') do |f|
f.write(YAML.dump(JSON.load(IO.read(sources.first))))
end
cache.register_build(target, :JsonToYaml, sources, env)
end
target
end
env.JsonToYaml('foo.yml','foo.json')
end
expect(File.exists?('foo.yml')).to be_truthy
expect(IO.read('foo.yml')).to eq("---\nkey: value\n")
end
it 'cleans built files' do
test_dir('build_dir')
Rscons::Environment.new do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_dir(%r{^src/([^/]+)/}, 'build_\\1/')
env.Program('build_dir', Dir['src/**/*.c'])
end
expect(`./build_dir`).to eq "Hello from two()\n"
expect(File.exists?('build_one/one.o')).to be_truthy
expect(File.exists?('build_two/two.o')).to be_truthy
Rscons.clean
expect(File.exists?('build_one/one.o')).to be_falsey
expect(File.exists?('build_two/two.o')).to be_falsey
expect(File.exists?('build_one')).to be_falsey
expect(File.exists?('build_two')).to be_falsey
expect(File.exists?('src/one/one.c')).to be_truthy
end
it 'does not clean created directories if other non-rscons-generated files reside there' do
test_dir('build_dir')
Rscons::Environment.new do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_dir(%r{^src/([^/]+)/}, 'build_\\1/')
env.Program('build_dir', Dir['src/**/*.c'])
end
expect(`./build_dir`).to eq "Hello from two()\n"
expect(File.exists?('build_one/one.o')).to be_truthy
expect(File.exists?('build_two/two.o')).to be_truthy
File.open('build_two/tmp', 'w') { |fh| fh.puts "dum" }
Rscons.clean
expect(File.exists?('build_one/one.o')).to be_falsey
expect(File.exists?('build_two/two.o')).to be_falsey
expect(File.exists?('build_one')).to be_falsey
expect(File.exists?('build_two')).to be_truthy
expect(File.exists?('src/one/one.c')).to be_truthy
end
it 'allows Ruby classes as custom builders to be used to construct files' do
test_dir('custom_builder')
class MySource < Rscons::Builder
def run(target, sources, cache, env, vars)
File.open(target, 'w') do |fh|
fh.puts <<EOF
#define THE_VALUE 5678
EOF
end
target
end
end
env = Rscons::Environment.new do |env|
env.add_builder(MySource.new)
env.MySource('inc.h', [])
env.Program('program', Dir['*.c'])
end
expect(lines).to eq ["CC program.o", "LD program#{env["PROGSUFFIX"]}"]
expect(File.exists?('inc.h')).to be_truthy
expect(`./program`).to eq "The value is 5678\n"
end
it 'supports custom builders with multiple targets' do
test_dir('custom_builder')
class CHGen < Rscons::Builder
def run(target, sources, cache, env, vars)
c_fname = target
h_fname = target.sub(/\.c$/, ".h")
unless cache.up_to_date?([c_fname, h_fname], "", sources, env)
puts "CHGen #{c_fname}"
File.open(c_fname, "w") {|fh| fh.puts "int THE_VALUE = 42;"}
File.open(h_fname, "w") {|fh| fh.puts "extern int THE_VALUE;"}
cache.register_build([c_fname, h_fname], "", sources, env)
end
target
end
end
make_env = lambda do
Rscons::Environment.new do |env|
env.add_builder(CHGen.new)
env.CHGen("inc.c", ["program.c"])
env.Program("program", %w[program.c inc.c])
end
end
env = make_env[]
expect(lines).to eq ["CHGen inc.c", "CC program.o", "CC inc.o", "LD program#{env["PROGSUFFIX"]}"]
expect(File.exists?("inc.c")).to be_truthy
expect(File.exists?("inc.h")).to be_truthy
expect(`./program`).to eq "The value is 42\n"
File.open("inc.c", "w") {|fh| fh.puts "int THE_VALUE = 33;"}
make_env[]
expect(lines).to eq ["CHGen inc.c"]
expect(`./program`).to eq "The value is 42\n"
end
it 'allows cloning Environment objects' do
test_dir('clone_env')
debug = Rscons::Environment.new(echo: :command) do |env|
env.build_dir('src', 'debug')
env['CFLAGS'] = '-O2'
env['CPPFLAGS'] = '-DSTRING="Debug Version"'
env.Program('program-debug', Dir['src/*.c'])
end
release = debug.clone do |env|
env["CPPFLAGS"] = '-DSTRING="Release Version"'
env.build_dir('src', 'release')
env.Program('program-release', Dir['src/*.c'])
end
expect(lines).to eq [
%q{gcc -c -o debug/program.o -MMD -MF debug/program.mf '-DSTRING="Debug Version"' -O2 src/program.c},
%Q{gcc -o program-debug#{debug["PROGSUFFIX"]} debug/program.o},
%q{gcc -c -o release/program.o -MMD -MF release/program.mf '-DSTRING="Release Version"' -O2 src/program.c},
%Q{gcc -o program-release#{debug["PROGSUFFIX"]} release/program.o},
]
end
it 'allows cloning all attributes of an Environment object' do
test_dir('clone_env')
built_targets = []
env1 = Rscons::Environment.new(echo: :command) do |env|
env.build_dir('src', 'build')
env['CFLAGS'] = '-O2'
env.add_build_hook do |build_op|
build_op[:vars]['CPPFLAGS'] = '-DSTRING="Hello"'
end
env.add_post_build_hook do |build_op|
built_targets << build_op[:target]
end
env.Program('program', Dir['src/*.c'])
end
env2 = env1.clone(clone: :all) do |env|
env.Program('program2', Dir['src/*.c'])
end
expect(lines).to eq [
%q{gcc -c -o build/program.o -MMD -MF build/program.mf -DSTRING="Hello" -O2 src/program.c},
%Q{gcc -o program#{env1["PROGSUFFIX"]} build/program.o},
%Q{gcc -o program2#{env2["PROGSUFFIX"]} build/program.o},
]
expect(built_targets).to eq([
"build/program.o",
"program#{env1['PROGSUFFIX']}",
"build/program.o",
"program2#{env1['PROGSUFFIX']}",
])
end
it 'builds a C++ program with one source file' do
test_dir('simple_cc')
Rscons::Environment.new do |env|
env.Program('simple', Dir['*.cc'])
end
expect(File.exists?('simple.o')).to be_truthy
expect(`./simple`).to eq "This is a simple C++ program\n"
end
it 'allows overriding construction variables for individual builder calls' do
test_dir('two_sources')
env = Rscons::Environment.new(echo: :command) do |env|
env.Object("one.o", "one.c", 'CPPFLAGS' => ['-DONE'])
env.Program('two_sources', ['one.o', 'two.c'])
end
expect(lines).to eq [
'gcc -c -o one.o -MMD -MF one.mf -DONE one.c',
'gcc -c -o two.o -MMD -MF two.mf two.c',
"gcc -o two_sources#{env["PROGSUFFIX"]} one.o two.o",
]
expect(File.exists?("two_sources#{env["PROGSUFFIX"]}")).to be_truthy
expect(`./two_sources`).to eq "This is a C program with two sources.\n"
end
it 'builds a static library archive' do
test_dir('library')
env = Rscons::Environment.new(echo: :command) do |env|
env.Program('library', ['lib.a', 'three.c'])
env.Library("lib.a", ['one.c', 'two.c'], 'CPPFLAGS' => ['-Dmake_lib'])
end
expect(lines).to eq [
'gcc -c -o one.o -MMD -MF one.mf -Dmake_lib one.c',
'gcc -c -o two.o -MMD -MF two.mf -Dmake_lib two.c',
'ar rcs lib.a one.o two.o',
'gcc -c -o three.o -MMD -MF three.mf three.c',
"gcc -o library#{env["PROGSUFFIX"]} lib.a three.o",
]
expect(File.exists?("library#{env["PROGSUFFIX"]}")).to be_truthy
expect(`ar t lib.a`).to eq "one.o\ntwo.o\n"
end
it 'supports build hooks to override construction variables' do
test_dir("build_dir")
env = Rscons::Environment.new(echo: :command) do |env|
env.append('CPPPATH' => Dir['src/**/*/'])
env.build_dir(%r{^src/([^/]+)/}, 'build_\\1/')
env.add_build_hook do |build_op|
if build_op[:target] =~ %r{build_one/.*\.o}
build_op[:vars]["CFLAGS"] << "-O1"
elsif build_op[:target] =~ %r{build_two/.*\.o}
build_op[:vars]["CFLAGS"] << "-O2"
end
end
env.Program('build_hook.exe', Dir['src/**/*.c'])
end
expect(`./build_hook.exe`).to eq "Hello from two()\n"
expect(lines).to match_array [
'gcc -c -o build_one/one.o -MMD -MF build_one/one.mf -Isrc/one/ -Isrc/two/ -O1 src/one/one.c',
'gcc -c -o build_two/two.o -MMD -MF build_two/two.mf -Isrc/one/ -Isrc/two/ -O2 src/two/two.c',
'gcc -o build_hook.exe build_one/one.o build_two/two.o',
]
end
it 'rebuilds when user-specified dependencies change' do
test_dir('simple')
env = Rscons::Environment.new do |env|
env.Program('simple.exe', Dir['*.c']).depends("file.ld")
File.open("file.ld", "w") do |fh|
fh.puts("foo")
end
end
expect(lines).to eq ["CC simple.o", "LD simple.exe"]
expect(File.exists?('simple.o')).to be_truthy
expect(`./simple.exe`).to eq "This is a simple C program\n"
e2 = Rscons::Environment.new do |env|
program = env.Program('simple.exe', Dir['*.c'])
env.depends(program, "file.ld")
File.open("file.ld", "w") do |fh|
fh.puts("bar")
end
end
expect(lines).to eq ["LD simple.exe"]
e3 = Rscons::Environment.new do |env|
env.Program('simple.exe', Dir['*.c'])
File.unlink("file.ld")
end
expect(lines).to eq ["LD simple.exe"]
Rscons::Environment.new do |env|
env.Program('simple.exe', Dir['*.c'])
end
expect(lines).to eq []
end
unless ENV["omit_gdc_tests"]
it "supports building D sources" do
test_dir("d")
Rscons::Environment.new(echo: :command) do |env|
env.Program("hello-d.exe", Dir["*.d"])
end
expect(lines).to eq [
"gdc -c -o main.o main.d",
"gdc -o hello-d.exe main.o",
]
expect(`./hello-d.exe`.rstrip).to eq "Hello from D!"
end
end
it "supports disassembling object files" do
test_dir("simple")
Rscons::Environment.new do |env|
env.Object("simple.o", "simple.c")
env.Disassemble("simple.txt", "simple.o")
end
expect(File.exists?("simple.txt")).to be_truthy
expect(File.read("simple.txt")).to match /Disassembly of section .text:/
end
it "supports preprocessing C sources" do
test_dir("simple")
Rscons::Environment.new do |env|
env.Preprocess("simplepp.c", "simple.c")
env.Program("simple", "simplepp.c")
end
expect(File.read("simplepp.c")).to match /# \d+ "simple.c"/
expect(`./simple`).to eq "This is a simple C program\n"
end
it "supports preprocessing C++ sources" do
test_dir("simple_cc")
Rscons::Environment.new do |env|
env.Preprocess("simplepp.cc", "simple.cc")
env.Program("simple", "simplepp.cc")
end
expect(File.read("simplepp.cc")).to match /# \d+ "simple.cc"/
expect(`./simple`).to eq "This is a simple C++ program\n"
end
it "supports invoking builders with no sources and a build_root defined" do
class TestBuilder < Rscons::Builder
def run(target, sources, cache, env, vars)
target
end
end
test_dir("simple")
Rscons::Environment.new do |env|
env.build_root = "build"
env.add_builder(TestBuilder.new)
env.TestBuilder("file")
end
end
it "expands construction variables in builder target and sources before invoking the builder" do
test_dir('custom_builder')
class MySource < Rscons::Builder
def run(target, sources, cache, env, vars)
File.open(target, 'w') do |fh|
fh.puts <<EOF
#define THE_VALUE 678
EOF
end
target
end
end
env = Rscons::Environment.new do |env|
env["hdr"] = "inc.h"
env["src"] = "program.c"
env.add_builder(MySource.new)
env.MySource('${hdr}')
env.Program('program', "${src}")
end
expect(lines).to eq ["CC program.o", "LD program#{env["PROGSUFFIX"]}"]
expect(File.exists?('inc.h')).to be_truthy
expect(`./program`).to eq "The value is 678\n"
end
it "supports lambdas as construction variable values" do
env = Rscons::Environment.new do |env|
env["prefix"] = "-H"
env["suffix"] = "xyz"
env[:cfg] = {val: 44}
env["computed"] = lambda do |args|
"#{args[:env]['prefix']}#{args[:env][:cfg][:val]}#{args[:env]['suffix']}"
end
env["lambda_recurse"] = lambda do |args|
"${prefix}ello"
end
end
e2 = env.clone
e2[:cfg][:val] = 38
expect(env.expand_varref("${computed}")).to eq("-H44xyz")
expect(e2.expand_varref("${computed}")).to eq("-H38xyz")
expect(env.expand_varref("${lambda_recurse}")).to eq("-Hello")
end
it "supports registering build targets from within a build hook" do
test_dir("simple")
Rscons::Environment.new do |env|
env.Program("simple", Dir["*.c"])
env.add_build_hook do |build_op|
if build_op[:target].end_with?(".o")
env.Disassemble("#{build_op[:target]}.txt", build_op[:target])
end
end
end
expect(File.exists?("simple.o")).to be_truthy
expect(File.exists?("simple.o.txt")).to be_truthy
expect(`./simple`).to eq "This is a simple C program\n"
end
it "supports post-build hooks" do
test_dir("simple")
built_targets = []
env = Rscons::Environment.new do |env|
env.Program("simple", Dir["*.c"])
env.add_post_build_hook do |build_op|
built_targets << build_op[:target]
expect(File.exists?(build_op[:target])).to be_truthy
end
end
expect(File.exists?("simple.o")).to be_truthy
expect(`./simple`).to eq "This is a simple C program\n"
expect(built_targets).to eq ["simple.o", "simple#{env["PROGSUFFIX"]}"]
end
it "supports multiple values for CXXSUFFIX" do
test_dir("simple_cc")
File.open("other.cccc", "w") {|fh| fh.puts}
Rscons::Environment.new do |env|
env["CXXSUFFIX"] = %w[.cccc .cc]
env["CXXFLAGS"] += %w[-x c++]
env.Program("simple", Dir["*.cc"] + ["other.cccc"])
end
expect(File.exists?("simple.o")).to be_truthy
expect(File.exists?("other.o")).to be_truthy
expect(`./simple`).to eq "This is a simple C++ program\n"
end
it "supports multiple values for CSUFFIX" do
test_dir("build_dir")
FileUtils.mv("src/one/one.c", "src/one/one.yargh")
Rscons::Environment.new do |env|
env["CSUFFIX"] = %w[.yargh .c]
env["CFLAGS"] += %w[-x c]
env["CPPPATH"] += Dir["src/**/"]
env.Program("build_dir", Dir["src/**/*.{c,yargh}"])
end
expect(File.exists?("src/one/one.o")).to be_truthy
expect(File.exists?("src/two/two.o")).to be_truthy
expect(`./build_dir`).to eq "Hello from two()\n"
end
it "supports multiple values for OBJSUFFIX" do
test_dir("two_sources")
env = Rscons::Environment.new() do |env|
env["OBJSUFFIX"] = %w[.oooo .ooo]
env.Object("one.oooo", "one.c", "CPPFLAGS" => ["-DONE"])
env.Object("two.ooo", "two.c")
env.Program("two_sources", %w[one.oooo two.ooo])
end
expect(File.exists?("two_sources#{env["PROGSUFFIX"]}")).to be_truthy
expect(`./two_sources`).to eq "This is a C program with two sources.\n"
end
it "supports multiple values for LIBSUFFIX" do
test_dir("two_sources")
env = Rscons::Environment.new() do |env|
env["LIBSUFFIX"] = %w[.aaaa .aaa]
env.Library("one.aaaa", "one.c", "CPPFLAGS" => ["-DONE"])
env.Library("two.aaa", "two.c")
env.Program("two_sources", %w[one.aaaa two.aaa])
end
expect(File.exists?("two_sources#{env["PROGSUFFIX"]}")).to be_truthy
expect(`./two_sources`).to eq "This is a C program with two sources.\n"
end
it "supports multiple values for ASSUFFIX" do
test_dir("two_sources")
env = Rscons::Environment.new() do |env|
env["ASSUFFIX"] = %w[.ssss .sss]
env["CFLAGS"] += %w[-S]
env.Object("one.ssss", "one.c", "CPPFLAGS" => ["-DONE"])
env.Object("two.sss", "two.c")
env.Program("two_sources", %w[one.ssss two.sss], "ASFLAGS" => env["ASFLAGS"] + %w[-x assembler])
end
expect(lines).to eq([
"CC one.ssss",
"CC two.sss",
"AS one.o",
"AS two.o",
"LD two_sources#{env["PROGSUFFIX"]}",
])
expect(File.exists?("two_sources#{env["PROGSUFFIX"]}")).to be_truthy
expect(`./two_sources`).to eq "This is a C program with two sources.\n"
end
it "supports dumping an Environment's construction variables" do
test_dir("simple")
env = Rscons::Environment.new do |env|
env["CFLAGS"] += %w[-O2 -fomit-frame-pointer]
env[:foo] = :bar
end
env.dump
result = lines
expect(result.include?(%{:foo => :bar})).to be_truthy
expect(result.include?(%{CFLAGS => ["-O2", "-fomit-frame-pointer"]})).to be_truthy
expect(result.include?(%{CPPPATH => []})).to be_truthy
end
it "considers deep dependencies when deciding whether to rerun Preprocess builder" do
test_dir("preprocess")
env = Rscons::Environment.new do |env|
env.Preprocess("pp", "foo.h")
end
expect(File.read("pp")).to match(%r{xyz42abc}m)
expect(lines).to eq(["Preprocess pp"])
env.Preprocess("pp", "foo.h")
env.process
expect(lines).to eq([])
File.open("bar.h", "w") do |fh|
fh.puts "#define BAR abc88xyz"
end
$ttt = true
env.Preprocess("pp", "foo.h")
env.process
expect(lines).to eq(["Preprocess pp"])
expect(File.read("pp")).to match(%r{abc88xyz}m)
end
it "allows construction variable references which expand to arrays in sources of a build target" do
test_dir("simple")
Rscons::Environment.new do |env|
env["sources"] = Dir["*.c"]
env.Program("simple", "${sources}")
end
expect(File.exists?("simple.o")).to be_truthy
expect(`./simple`).to eq "This is a simple C program\n"
end
it "supports registering multiple build targets with the same target path" do
test_dir("build_dir")
Rscons::Environment.new do |env|
env["CPPPATH"] << "src/two"
env.Object("one.o", "src/one/one.c")
env.Object("one.o", "src/two/two.c")
end
expect(File.exists?("one.o")).to be_truthy
expect(lines).to eq([
"CC one.o",
"CC one.o",
])
end
it "expands target and source paths when builders are registered in build hooks" do
test_dir("build_dir")
Rscons::Environment.new do |env|
env["CPPPATH"] << "src/two"
env.Object("one.o", "src/one/one.c")
env.add_post_build_hook do |build_op|
if build_op[:target] == "one.o"
env["MODULE"] = "two"
env.Object("${MODULE}.o", "src/${MODULE}/${MODULE}.c")
end
end
end
expect(File.exists?("one.o")).to be_truthy
expect(File.exists?("two.o")).to be_truthy
expect(lines).to eq([
"CC one.o",
"CC two.o",
])
end
end
|
require 'tmpdir'
require 'webrick'
require_relative 'spec_helper'
module LetsCert
TEST_SERVER = 'http://172.17.0.1:4000'
TEST_KEY_LENGTH = 512
describe Certificate do
before(:all) { Certificate.logger = Logger.new('/dev/null') }
before(:all) do
root_key = OpenSSL::PKey::RSA.new(TEST_KEY_LENGTH)
@domains = %w(example.org www.example.org)
key = OpenSSL::PKey::RSA.new(TEST_KEY_LENGTH)
@cert = OpenSSL::X509::Certificate.new
@cert.version = 2
@cert.serial = 2
@cert.issuer = OpenSSL::X509::Name.parse "/DC=letscert/CN=CA"
@cert.public_key = key.public_key
@cert.not_before = Time.now
# 20 days validity
@cert.not_after = @cert.not_before + 20 * 24 * 60 * 60
ef = OpenSSL::X509::ExtensionFactory.new
ef.subject_certificate = @cert
@domains.each do |domain|
@cert.add_extension(ef.create_extension('subjectAltName',
"DNS:#{domain}",
false))
end
@cert.sign(root_key, OpenSSL::Digest::SHA256.new)
# minimum size accepted by ACME server
@account_key2048 = OpenSSL::PKey::RSA.new(2048)
# Create temporary directory
@tmpdir = Dir.mktmpdir('test_letscert')
end
after(:all) do
# Remove temporary directory
system "rm -rf #@tmpdir"
end
let(:certificate) { Certificate.new(@cert) }
let(:options) { { roots: { 'example.com' => @tmpdir },
server: TEST_SERVER,
email: 'test@example.org',
cert_key_size: 2048 } }
context '#get' do
it 'checks all domains have a root' do
runner = Runner.new
ARGV.clear
ARGV << '-d' << 'example.com:/var/ww/html'
ARGV << '--server' << TEST_SERVER
runner.parse_options
VCR.use_cassette('single-domain') do
# raise error because no e-mail address was given
expect { certificate.get(nil, nil, runner.options) }.
to raise_error(Acme::Client::Error)
end
ARGV.clear
ARGV << '-d' << 'example.com:/var/www/html'
ARGV << '-d' << 'www.example.com'
ARGV << '--server' << TEST_SERVER
runner.options[:domains] = []
runner.parse_options
expect { certificate.get(nil, nil, runner.options) }.
to raise_error(LetsCert::Error).
with_message(/not specified: www\.example\.com\./)
ARGV.clear
ARGV << '-d' << 'example.com:/var/www/html'
ARGV << '-d' << 'www.example.com'
ARGV << '--default-root' << '/opt/www'
ARGV << '--server' << TEST_SERVER
runner.parse_options
VCR.use_cassette('default-root') do
# raise error because no e-mail address was given
expect { certificate.get(nil, nil, runner.options) }.
to raise_error(Acme::Client::Error)
end
expect(runner.options[:roots]['example.com']).to eq('/var/www/html')
expect(runner.options[:roots]['www.example.com']).to eq('/opt/www')
end
it 'uses existing account key' do
opts = { roots: options[:roots] }
VCR.use_cassette('no-server') do
# Connection error: no server to connect to
expect { certificate.get(@account_key2048, nil, opts) }.
to raise_error(Faraday::ConnectionFailed)
end
expect(certificate.client.private_key).to eq(@account_key2048)
end
it 'creates an ACME account key if none exists' do
opts = {
roots: options[:roots],
account_key_size: 128,
}
VCR.use_cassette('no-server') do
# Connection error: no server to connect to
expect { certificate.get(nil, nil, opts) }.
to raise_error(Faraday::ConnectionFailed)
end
expect(certificate.client.private_key).to be_a(OpenSSL::PKey::RSA)
end
it 'creates an ACME client with provided account key and end point' do
VCR.use_cassette('create-acme-client') do
# Acme error: not valid e-mail address
expect { certificate.get(@account_key2048, nil, options) }.
to raise_error(Acme::Client::Error)
end
expect(certificate.client.private_key).to eq(@account_key2048)
expect(certificate.client.instance_eval { @endpoint }).to eq(options[:server])
end
it 'raises when register without e-mail' do
options.delete :email
VCR.use_cassette('create-acme-client-but-bad-email') do
# Acme error: not valid e-mail address
expect { certificate.get(@account_key2048, nil, options) }.
to raise_error(Acme::Client::Error).
with_message('not a valid e-mail address')
end
end
it 'responds to HTTP-01 challenge' do
VCR.use_cassette('http-01-challenge') do
serve_files_from @tmpdir do
certificate.get_acme_client(@account_key2048, options)
expect { certificate.get(@account_key2048, nil, options) }.
to_not raise_error
end
end
expect(certificate.cert).to_not eq(@cert)
end
it 'raises if HTTP-01 challenge is unavailable' do
VCR.use_cassette('no-http-01-challenge') do
certificate.get_acme_client(@account_key2048, options) do |client|
client.connection.builder.insert 0, RemoveHttp01Middleware
end
expect { certificate.get(@account_key2048, nil, options) }.
to raise_error(LetsCert::Error).with_message(/not offer http-01/)
end
end
it 'creates a new private key if --reuse-key is not present' do
options[:files] = %w(fake)
key = OpenSSL::PKey::RSA.new(TEST_KEY_LENGTH)
VCR.use_cassette('http-01-challenge') do
serve_files_from @tmpdir do
expect { certificate.get(@account_key2048, key, options) }.
to_not raise_error
end
end
expect(certificate.cert).to_not eq(@cert)
expect(IOPluginHelper::FakeIOPlugin.saved_data[:key]).to_not eq(key)
end
it 'reuses existing private key if --reuse-key is present' do
options[:files] = %w(fake)
options[:reuse_key] = true
key = OpenSSL::PKey::RSA.new(TEST_KEY_LENGTH)
VCR.use_cassette('http-01-challenge') do
serve_files_from @tmpdir do
expect { certificate.get(@account_key2048, key, options) }.
to_not raise_error
end
end
expect(certificate.cert).to_not eq(@cert)
expect(IOPluginHelper::FakeIOPlugin.saved_data[:key]).to eq(key)
end
end
context '#revoke' do
it 'raises if no certificate is given' do
certificate = Certificate.new(nil)
expect { certificate.revoke(@account_key2048) }.
to raise_error(LetsCert::Error)
end
it 'revokes an existing certificate'
end
context '#valid?' do
it 'checks whether a certificate is valid given a minimum valid duration' do
expect(certificate.valid?(@domains)).to be(true)
expect(certificate.valid?(@domains, 19)).to be(true)
expect(certificate.valid?(@domains, 21 * 24 * 3600)).to be(false)
end
it 'raises whether a certificate does not validate a given domain' do
expect(certificate.valid?(@domains)).to be(true)
expect(certificate.valid?(@domains[0, 1])).to be(true)
domains = @domains + %w(another.tld)
expect { certificate.valid?(domains) }.to raise_error(LetsCert::Error)
expect { certificate.valid?(%w(another.tld)) }.to raise_error(LetsCert::Error)
end
end
end
end
Remove unnecessary code in 'Certificate#get responds to HTTP-01 challenge'
spec.
require 'tmpdir'
require 'webrick'
require_relative 'spec_helper'
module LetsCert
TEST_SERVER = 'http://172.17.0.1:4000'
TEST_KEY_LENGTH = 512
describe Certificate do
before(:all) { Certificate.logger = Logger.new('/dev/null') }
before(:all) do
root_key = OpenSSL::PKey::RSA.new(TEST_KEY_LENGTH)
@domains = %w(example.org www.example.org)
key = OpenSSL::PKey::RSA.new(TEST_KEY_LENGTH)
@cert = OpenSSL::X509::Certificate.new
@cert.version = 2
@cert.serial = 2
@cert.issuer = OpenSSL::X509::Name.parse "/DC=letscert/CN=CA"
@cert.public_key = key.public_key
@cert.not_before = Time.now
# 20 days validity
@cert.not_after = @cert.not_before + 20 * 24 * 60 * 60
ef = OpenSSL::X509::ExtensionFactory.new
ef.subject_certificate = @cert
@domains.each do |domain|
@cert.add_extension(ef.create_extension('subjectAltName',
"DNS:#{domain}",
false))
end
@cert.sign(root_key, OpenSSL::Digest::SHA256.new)
# minimum size accepted by ACME server
@account_key2048 = OpenSSL::PKey::RSA.new(2048)
# Create temporary directory
@tmpdir = Dir.mktmpdir('test_letscert')
end
after(:all) do
# Remove temporary directory
system "rm -rf #@tmpdir"
end
let(:certificate) { Certificate.new(@cert) }
let(:options) { { roots: { 'example.com' => @tmpdir },
server: TEST_SERVER,
email: 'test@example.org',
cert_key_size: 2048 } }
context '#get' do
it 'checks all domains have a root' do
runner = Runner.new
ARGV.clear
ARGV << '-d' << 'example.com:/var/ww/html'
ARGV << '--server' << TEST_SERVER
runner.parse_options
VCR.use_cassette('single-domain') do
# raise error because no e-mail address was given
expect { certificate.get(nil, nil, runner.options) }.
to raise_error(Acme::Client::Error)
end
ARGV.clear
ARGV << '-d' << 'example.com:/var/www/html'
ARGV << '-d' << 'www.example.com'
ARGV << '--server' << TEST_SERVER
runner.options[:domains] = []
runner.parse_options
expect { certificate.get(nil, nil, runner.options) }.
to raise_error(LetsCert::Error).
with_message(/not specified: www\.example\.com\./)
ARGV.clear
ARGV << '-d' << 'example.com:/var/www/html'
ARGV << '-d' << 'www.example.com'
ARGV << '--default-root' << '/opt/www'
ARGV << '--server' << TEST_SERVER
runner.parse_options
VCR.use_cassette('default-root') do
# raise error because no e-mail address was given
expect { certificate.get(nil, nil, runner.options) }.
to raise_error(Acme::Client::Error)
end
expect(runner.options[:roots]['example.com']).to eq('/var/www/html')
expect(runner.options[:roots]['www.example.com']).to eq('/opt/www')
end
it 'uses existing account key' do
opts = { roots: options[:roots] }
VCR.use_cassette('no-server') do
# Connection error: no server to connect to
expect { certificate.get(@account_key2048, nil, opts) }.
to raise_error(Faraday::ConnectionFailed)
end
expect(certificate.client.private_key).to eq(@account_key2048)
end
it 'creates an ACME account key if none exists' do
opts = {
roots: options[:roots],
account_key_size: 128,
}
VCR.use_cassette('no-server') do
# Connection error: no server to connect to
expect { certificate.get(nil, nil, opts) }.
to raise_error(Faraday::ConnectionFailed)
end
expect(certificate.client.private_key).to be_a(OpenSSL::PKey::RSA)
end
it 'creates an ACME client with provided account key and end point' do
VCR.use_cassette('create-acme-client') do
# Acme error: not valid e-mail address
expect { certificate.get(@account_key2048, nil, options) }.
to raise_error(Acme::Client::Error)
end
expect(certificate.client.private_key).to eq(@account_key2048)
expect(certificate.client.instance_eval { @endpoint }).to eq(options[:server])
end
it 'raises when register without e-mail' do
options.delete :email
VCR.use_cassette('create-acme-client-but-bad-email') do
# Acme error: not valid e-mail address
expect { certificate.get(@account_key2048, nil, options) }.
to raise_error(Acme::Client::Error).
with_message('not a valid e-mail address')
end
end
it 'responds to HTTP-01 challenge' do
VCR.use_cassette('http-01-challenge') do
serve_files_from @tmpdir do
expect { certificate.get(@account_key2048, nil, options) }.
to_not raise_error
end
end
expect(certificate.cert).to_not eq(@cert)
end
it 'raises if HTTP-01 challenge is unavailable' do
VCR.use_cassette('no-http-01-challenge') do
certificate.get_acme_client(@account_key2048, options) do |client|
client.connection.builder.insert 0, RemoveHttp01Middleware
end
expect { certificate.get(@account_key2048, nil, options) }.
to raise_error(LetsCert::Error).with_message(/not offer http-01/)
end
end
it 'creates a new private key if --reuse-key is not present' do
options[:files] = %w(fake)
key = OpenSSL::PKey::RSA.new(TEST_KEY_LENGTH)
VCR.use_cassette('http-01-challenge') do
serve_files_from @tmpdir do
expect { certificate.get(@account_key2048, key, options) }.
to_not raise_error
end
end
expect(certificate.cert).to_not eq(@cert)
expect(IOPluginHelper::FakeIOPlugin.saved_data[:key]).to_not eq(key)
end
it 'reuses existing private key if --reuse-key is present' do
options[:files] = %w(fake)
options[:reuse_key] = true
key = OpenSSL::PKey::RSA.new(TEST_KEY_LENGTH)
VCR.use_cassette('http-01-challenge') do
serve_files_from @tmpdir do
expect { certificate.get(@account_key2048, key, options) }.
to_not raise_error
end
end
expect(certificate.cert).to_not eq(@cert)
expect(IOPluginHelper::FakeIOPlugin.saved_data[:key]).to eq(key)
end
end
context '#revoke' do
it 'raises if no certificate is given' do
certificate = Certificate.new(nil)
expect { certificate.revoke(@account_key2048) }.
to raise_error(LetsCert::Error)
end
it 'revokes an existing certificate'
end
context '#valid?' do
it 'checks whether a certificate is valid given a minimum valid duration' do
expect(certificate.valid?(@domains)).to be(true)
expect(certificate.valid?(@domains, 19)).to be(true)
expect(certificate.valid?(@domains, 21 * 24 * 3600)).to be(false)
end
it 'raises whether a certificate does not validate a given domain' do
expect(certificate.valid?(@domains)).to be(true)
expect(certificate.valid?(@domains[0, 1])).to be(true)
domains = @domains + %w(another.tld)
expect { certificate.valid?(domains) }.to raise_error(LetsCert::Error)
expect { certificate.valid?(%w(another.tld)) }.to raise_error(LetsCert::Error)
end
end
end
end
|
require 'spec_helper'
describe 'apt', :type => :class do
let(:facts) { { :lsbdistid => 'Debian', :osfamily => 'Debian' } }
let :default_params do
{
:disable_keys => :undef,
:always_apt_update => false,
:purge_sources_list => false,
:purge_sources_list_d => false,
}
end
[{},
{
:disable_keys => true,
:always_apt_update => true,
:proxy_host => true,
:proxy_port => '3128',
:purge_sources_list => true,
:purge_sources_list_d => true,
},
{
:purge_preferences => true,
:purge_preferences_d => true,
},
{
:disable_keys => false
}
].each do |param_set|
describe "when #{param_set == {} ? "using default" : "specifying"} class parameters" do
let :param_hash do
default_params.merge(param_set)
end
let :params do
param_set
end
let :refresh_only_apt_update do
if param_hash[:always_apt_update]
false
else
true
end
end
it { should contain_class("apt::params") }
it {
if param_hash[:purge_sources_list]
should contain_file("sources.list").with({
'path' => "/etc/apt/sources.list",
'ensure' => "present",
'owner' => "root",
'group' => "root",
'mode' => "0644",
"content" => "# Repos managed by puppet.\n"
})
else
should contain_file("sources.list").with({
'path' => "/etc/apt/sources.list",
'ensure' => "present",
'owner' => "root",
'group' => "root",
'mode' => "0644",
'content' => nil
})
end
}
it {
if param_hash[:purge_sources_list_d]
should create_file("sources.list.d").with({
'path' => "/etc/apt/sources.list.d",
'ensure' => "directory",
'owner' => "root",
'group' => "root",
'purge' => true,
'recurse' => true,
'notify' => 'Exec[apt_update]'
})
else
should create_file("sources.list.d").with({
'path' => "/etc/apt/sources.list.d",
'ensure' => "directory",
'owner' => "root",
'group' => "root",
'purge' => false,
'recurse' => false,
'notify' => 'Exec[apt_update]'
})
end
}
it {
if param_hash[:purge_preferences]
should create_file('apt-preferences').with({
:ensure => 'absent',
:path => '/etc/apt/preferences',
})
end
}
it {
if param_hash[:purge_preferences_d]
should create_file("preferences.d").with({
'path' => "/etc/apt/preferences.d",
'ensure' => "directory",
'owner' => "root",
'group' => "root",
'purge' => true,
'recurse' => true,
})
else
should create_file("preferences.d").with({
'path' => "/etc/apt/preferences.d",
'ensure' => "directory",
'owner' => "root",
'group' => "root",
'purge' => false,
'recurse' => false,
})
end
}
it {
should contain_exec("apt_update").with({
'command' => "/usr/bin/apt-get update",
'refreshonly' => refresh_only_apt_update
})
}
it {
if param_hash[:disable_keys] == true
should create_file("99unauth").with({
'content' => "APT::Get::AllowUnauthenticated 1;\n",
'ensure' => "present",
'path' => "/etc/apt/apt.conf.d/99unauth"
})
elsif param_hash[:disable_keys] == false
should create_file("99unauth").with({
'ensure' => "absent",
'path' => "/etc/apt/apt.conf.d/99unauth"
})
elsif param_hash[:disable_keys] != :undef
should_not create_file("99unauth").with({
'path' => "/etc/apt/apt.conf.d/99unauth"
})
end
}
describe 'when setting a proxy' do
it {
if param_hash[:proxy_host]
should contain_file('01proxy').with(
'path' => '/etc/apt/apt.conf.d/01proxy',
'content' => "Acquire::http::Proxy \"http://#{param_hash[:proxy_host]}:#{param_hash[:proxy_port]}\";\n",
'notify' => "Exec[apt_update]"
)
else
should contain_file('01proxy').with(
'path' => '/etc/apt/apt.conf.d/01proxy',
'notify' => 'Exec[apt_update]',
'ensure' => 'absent'
)
end
}
end
end
end
end
Testing if we are not touching the preference file when purge mode is off
require 'spec_helper'
describe 'apt', :type => :class do
let(:facts) { { :lsbdistid => 'Debian', :osfamily => 'Debian' } }
let :default_params do
{
:disable_keys => :undef,
:always_apt_update => false,
:purge_sources_list => false,
:purge_sources_list_d => false,
}
end
[{},
{
:disable_keys => true,
:always_apt_update => true,
:proxy_host => true,
:proxy_port => '3128',
:purge_sources_list => true,
:purge_sources_list_d => true,
},
{
:purge_preferences => true,
:purge_preferences_d => true,
},
{
:disable_keys => false
}
].each do |param_set|
describe "when #{param_set == {} ? "using default" : "specifying"} class parameters" do
let :param_hash do
default_params.merge(param_set)
end
let :params do
param_set
end
let :refresh_only_apt_update do
if param_hash[:always_apt_update]
false
else
true
end
end
it { should contain_class("apt::params") }
it {
if param_hash[:purge_sources_list]
should contain_file("sources.list").with({
'path' => "/etc/apt/sources.list",
'ensure' => "present",
'owner' => "root",
'group' => "root",
'mode' => "0644",
"content" => "# Repos managed by puppet.\n"
})
else
should contain_file("sources.list").with({
'path' => "/etc/apt/sources.list",
'ensure' => "present",
'owner' => "root",
'group' => "root",
'mode' => "0644",
'content' => nil
})
end
}
it {
if param_hash[:purge_sources_list_d]
should create_file("sources.list.d").with({
'path' => "/etc/apt/sources.list.d",
'ensure' => "directory",
'owner' => "root",
'group' => "root",
'purge' => true,
'recurse' => true,
'notify' => 'Exec[apt_update]'
})
else
should create_file("sources.list.d").with({
'path' => "/etc/apt/sources.list.d",
'ensure' => "directory",
'owner' => "root",
'group' => "root",
'purge' => false,
'recurse' => false,
'notify' => 'Exec[apt_update]'
})
end
}
it {
if param_hash[:purge_preferences]
should create_file('apt-preferences').with({
:ensure => 'absent',
:path => '/etc/apt/preferences',
})
else
should_not contain_file('apt-preferences')
end
}
it {
if param_hash[:purge_preferences_d]
should create_file("preferences.d").with({
'path' => "/etc/apt/preferences.d",
'ensure' => "directory",
'owner' => "root",
'group' => "root",
'purge' => true,
'recurse' => true,
})
else
should create_file("preferences.d").with({
'path' => "/etc/apt/preferences.d",
'ensure' => "directory",
'owner' => "root",
'group' => "root",
'purge' => false,
'recurse' => false,
})
end
}
it {
should contain_exec("apt_update").with({
'command' => "/usr/bin/apt-get update",
'refreshonly' => refresh_only_apt_update
})
}
it {
if param_hash[:disable_keys] == true
should create_file("99unauth").with({
'content' => "APT::Get::AllowUnauthenticated 1;\n",
'ensure' => "present",
'path' => "/etc/apt/apt.conf.d/99unauth"
})
elsif param_hash[:disable_keys] == false
should create_file("99unauth").with({
'ensure' => "absent",
'path' => "/etc/apt/apt.conf.d/99unauth"
})
elsif param_hash[:disable_keys] != :undef
should_not create_file("99unauth").with({
'path' => "/etc/apt/apt.conf.d/99unauth"
})
end
}
describe 'when setting a proxy' do
it {
if param_hash[:proxy_host]
should contain_file('01proxy').with(
'path' => '/etc/apt/apt.conf.d/01proxy',
'content' => "Acquire::http::Proxy \"http://#{param_hash[:proxy_host]}:#{param_hash[:proxy_port]}\";\n",
'notify' => "Exec[apt_update]"
)
else
should contain_file('01proxy').with(
'path' => '/etc/apt/apt.conf.d/01proxy',
'notify' => 'Exec[apt_update]',
'ensure' => 'absent'
)
end
}
end
end
end
end
|
RAILS_ROOT = File.dirname(__FILE__) + "/../"
RAILS_ENV = ENV['RAILS_ENV'] || 'development'
# Mocks first.
ADDITIONAL_LOAD_PATHS = ["#{RAILS_ROOT}/test/mocks/#{RAILS_ENV}"]
# Then model subdirectories.
ADDITIONAL_LOAD_PATHS.concat(Dir["#{RAILS_ROOT}/app/models/[_a-z]*"])
ADDITIONAL_LOAD_PATHS.concat(Dir["#{RAILS_ROOT}/components/[_a-z]*"])
# Followed by the standard includes.
ADDITIONAL_LOAD_PATHS.concat %w(
app
app/models
app/controllers
app/helpers
app/apis
components
config
lib
vendor
vendor/rails/railties
vendor/rails/railties/lib
vendor/rails/actionpack/lib
vendor/rails/activesupport/lib
vendor/rails/activerecord/lib
vendor/rails/actionmailer/lib
vendor/rails/actionwebservice/lib
).map { |dir| "#{RAILS_ROOT}/#{dir}" }.select { |dir| File.directory?(dir) }
# Prepend to $LOAD_PATH
ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) }
# Require Rails libraries.
require 'rubygems' unless File.directory?("#{RAILS_ROOT}/vendor/rails")
require 'active_support'
require 'active_record'
require 'action_controller'
require 'action_mailer'
require 'action_web_service'
# Environment-specific configuration.
require_dependency "environments/#{RAILS_ENV}"
ActiveRecord::Base.configurations = File.open("#{RAILS_ROOT}/config/database.yml") { |f| YAML::load(f) }
ActiveRecord::Base.establish_connection
# Configure defaults if the included environment did not.
begin
RAILS_DEFAULT_LOGGER = Logger.new("#{RAILS_ROOT}/log/#{RAILS_ENV}.log")
RAILS_DEFAULT_LOGGER.level = (RAILS_ENV == 'production' ? Logger::INFO : Logger::DEBUG)
rescue StandardError
RAILS_DEFAULT_LOGGER = Logger.new(STDERR)
RAILS_DEFAULT_LOGGER.level = Logger::WARN
RAILS_DEFAULT_LOGGER.warn(
"Rails Error: Unable to access log file. Please ensure that log/#{RAILS_ENV}.log exists and is chmod 0666. " +
"The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
)
end
[ActiveRecord, ActionController, ActionMailer].each { |mod| mod::Base.logger ||= RAILS_DEFAULT_LOGGER }
[ActionController, ActionMailer].each { |mod| mod::Base.template_root ||= "#{RAILS_ROOT}/app/views/" }
ActionController::Routing::Routes.reload
Controllers = Dependencies::LoadingModule.root(
File.join(RAILS_ROOT, 'app', 'controllers'),
File.join(RAILS_ROOT, 'components')
)
# Include your app's configuration here:
require_dependency 'aggregations/delicious'
require_dependency 'aggregations/tada'
require_dependency 'aggregations/flickr'
require_dependency 'aggregations/fortythree'
require_dependency 'configuration'
require_dependency 'spam_protection'
require_dependency 'xmlrpc_fix'
ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.update(:database_manager => CGI::Session::ActiveRecordStore)
ActiveRecord::Base.default_timezone = :utc
begin
require 'redcloth'
require 'bluecloth'
require 'rubypants'
rescue MissingSourceFile => e
end
* Force ruby into UTF-8 mode to make special characters in certain areas possible (fixes #121) [contagiouskimo@yahoo.com.tw]
git-svn-id: 70ab0960c3db1cbf656efd6df54a8f3de72dc710@306 820eb932-12ee-0310-9ca8-eeb645f39767
RAILS_ROOT = File.dirname(__FILE__) + "/../"
RAILS_ENV = ENV['RAILS_ENV'] || 'development'
# Mocks first.
ADDITIONAL_LOAD_PATHS = ["#{RAILS_ROOT}/test/mocks/#{RAILS_ENV}"]
# Then model subdirectories.
ADDITIONAL_LOAD_PATHS.concat(Dir["#{RAILS_ROOT}/app/models/[_a-z]*"])
ADDITIONAL_LOAD_PATHS.concat(Dir["#{RAILS_ROOT}/components/[_a-z]*"])
# Followed by the standard includes.
ADDITIONAL_LOAD_PATHS.concat %w(
app
app/models
app/controllers
app/helpers
app/apis
components
config
lib
vendor
vendor/rails/railties
vendor/rails/railties/lib
vendor/rails/actionpack/lib
vendor/rails/activesupport/lib
vendor/rails/activerecord/lib
vendor/rails/actionmailer/lib
vendor/rails/actionwebservice/lib
).map { |dir| "#{RAILS_ROOT}/#{dir}" }.select { |dir| File.directory?(dir) }
# Prepend to $LOAD_PATH
ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) }
# Require Rails libraries.
require 'rubygems' unless File.directory?("#{RAILS_ROOT}/vendor/rails")
require 'active_support'
require 'active_record'
require 'action_controller'
require 'action_mailer'
require 'action_web_service'
# Environment-specific configuration.
require_dependency "environments/#{RAILS_ENV}"
ActiveRecord::Base.configurations = File.open("#{RAILS_ROOT}/config/database.yml") { |f| YAML::load(f) }
ActiveRecord::Base.establish_connection
# Configure defaults if the included environment did not.
begin
RAILS_DEFAULT_LOGGER = Logger.new("#{RAILS_ROOT}/log/#{RAILS_ENV}.log")
RAILS_DEFAULT_LOGGER.level = (RAILS_ENV == 'production' ? Logger::INFO : Logger::DEBUG)
rescue StandardError
RAILS_DEFAULT_LOGGER = Logger.new(STDERR)
RAILS_DEFAULT_LOGGER.level = Logger::WARN
RAILS_DEFAULT_LOGGER.warn(
"Rails Error: Unable to access log file. Please ensure that log/#{RAILS_ENV}.log exists and is chmod 0666. " +
"The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
)
end
[ActiveRecord, ActionController, ActionMailer].each { |mod| mod::Base.logger ||= RAILS_DEFAULT_LOGGER }
[ActionController, ActionMailer].each { |mod| mod::Base.template_root ||= "#{RAILS_ROOT}/app/views/" }
ActionController::Routing::Routes.reload
Controllers = Dependencies::LoadingModule.root(
File.join(RAILS_ROOT, 'app', 'controllers'),
File.join(RAILS_ROOT, 'components')
)
# Include your app's configuration here:
$KCODE = 'u'
require_dependency 'jcode'
require_dependency 'aggregations/delicious'
require_dependency 'aggregations/tada'
require_dependency 'aggregations/flickr'
require_dependency 'aggregations/fortythree'
require_dependency 'configuration'
require_dependency 'spam_protection'
require_dependency 'xmlrpc_fix'
ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.update(:database_manager => CGI::Session::ActiveRecordStore)
ActiveRecord::Base.default_timezone = :utc
begin
require 'redcloth'
require 'bluecloth'
require 'rubypants'
rescue MissingSourceFile => e
end
|
require 'spec_helper'
describe 'dns' do
# by default the hiera integration uses hiera data from the shared_contexts.rb file
# but basically to mock hiera you first need to add a key/value pair
# to the specific context in the spec/shared_contexts.rb file
# Note: you can only use a single hiera context per describe/context block
# rspec-puppet does not allow you to swap out hiera data on a per test block
# include_context :hiera
let(:node) { 'dns.example.com' }
# below is the facts hash that gives you the ability to mock
# facts on a per describe/context block. If you use a fact in your
# manifest you should mock the facts below.
let(:facts) do
{}
end
# below is a list of the resource parameters that you can override.
# By default all non-required parameters are commented out,
# while all required parameters will require you to add a value
let(:params) do
{
#:daemon => "$::dns::params::daemon",
#:slaves_target => "$::dns::params::slaves_target",
#:tsigs_target => "$::dns::params::tsigs_target",
#:nsid => "$::dns::params::nsid",
#:identity => "$::dns::params::identity",
#:ip_addresses => [],
#:master => false,
instance: 'test',
#:ensure => "present",
#:enable_zonecheck => true,
#:zones => {},
#:files => {},
#:tsig => {},
#:enable_nagios => false,
}
end
# add these two lines in a single test block to enable puppet and hiera debug mode
# Puppet::Util::Log.level = :debug
# Puppet::Util::Log.newdestination(:console)
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts.merge(
'dns_slave_tsigs' => {},
'dns_slave_addresses' => {},
'ipaddress' => '192.0.2.2'
)
end
case facts[:operatingsystem]
when 'Ubuntu'
case facts['lsbdistcodename']
when 'precise'
let(:nsd_enable) { true }
let(:knot_enable) { false }
let(:dns_control) { '/usr/sbin/nsd-control' }
else
let(:nsd_enable) { false }
let(:knot_enable) { true }
let(:dns_control) { '/usr/sbin/knotc' }
end
else
let(:nsd_enable) { true }
let(:knot_enable) { false }
let(:dns_control) { '/usr/sbin/nsd-control' }
end
describe 'check default config' do
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_class('dns::params') }
it do
is_expected.to contain_package('zonecheck').with(
'ensure' => '1.0.14',
'provider' => 'pip'
)
end
it do
is_expected.to contain_file('/usr/local/etc/zone_check.conf').with(
'ensure' => 'present'
).with_content(
%r{192.0.2.2}
)
end
it do
is_expected.to contain_cron('/usr/local/bin/zonecheck').with(
'ensure' => 'present',
'command' => '/usr/bin/flock -n /var/lock/zonecheck.lock /usr/local/bin/zonecheck --puppet-facts -v',
'minute' => '*/15'
)
end
it do
is_expected.to contain_file('/usr/local/bin/dns-control').with(
'ensure' => 'link',
'target' => dns_control
)
end
it do
expect(exported_resources).to contain_concat__fragment('dns_slave_tsig_yaml_foo.example.com').with(
'target' => '/etc/puppetlabs/facter/facts.d/dns_slave_tsigs.yaml',
'tag' => 'dns::test_slave_tsigs',
'order' => '10'
).with_content(
%r{# foo.example.com}
).with_content(
%r{algo:\s+$}
).with_content(
%r{data:\s+''$}
)
end
it do
expect(exported_resources).to contain_concat__fragment('dns_slave_addresses_yaml_foo.example.com').with(
'target' => '/etc/puppetlabs/facter/facts.d/dns_slave_addresses.yaml',
'tag' => 'dns::test_slave_interface_yaml',
'content' => "# foo.example.com\n",
'order' => '10'
)
end
it do
is_expected.to contain_class('nsd').with(
'enable' => nsd_enable,
'ip_addresses' => ['192.0.2.2'],
'tsigs' => {},
'slave_addresses' => {},
'zones' => {},
'tsig' => {},
'server_count' => 1,
'files' => {},
'nsid' => 'foo.example.com',
'identity' => 'foo.example.com'
)
end
it do
is_expected.to contain_class('knot').with(
'enable' => knot_enable,
'ip_addresses' => ['192.0.2.2'],
'tsigs' => {},
'slave_addresses' => {},
'zones' => {},
'tsig' => {},
'server_count' => 1,
'files' => {},
'nsid' => 'foo.example.com',
'identity' => 'foo.example.com'
)
end
end
describe 'Change Defaults' do
context 'slaves_target' do
before { params.merge!(master: true, slaves_target: '/tmp') }
it { is_expected.to compile }
it { is_expected.to contain_concat('/tmp') }
it do
is_expected.to contain_concat__fragment('dns_slave_addresses_yaml_foo.example.com').with(
'target' => '/tmp',
'content' => "dns_slave_addresses:\n",
'order' => '01'
)
end
end
context 'tsigs_target' do
before { params.merge!(master: true, tsigs_target: '/tmp') }
it { is_expected.to compile }
it { is_expected.to contain_concat('/tmp') }
it do
is_expected.to contain_concat__fragment('dns_slave_tsigs_yaml_foo.example.com').with(
'target' => '/tmp',
'content' => "dns_slave_tsigs:\n",
'order' => '01'
)
end
end
context 'nsid' do
before { params.merge!(nsid: 'foobar') }
it { is_expected.to compile }
it { is_expected.to contain_class('knot').with('nsid' => 'foobar') }
it { is_expected.to contain_class('nsd').with('nsid' => 'foobar') }
end
context 'identity' do
before { params.merge!(identity: 'foobar') }
it { is_expected.to compile }
it { is_expected.to contain_class('knot').with('identity' => 'foobar') }
it { is_expected.to contain_class('nsd').with('identity' => 'foobar') }
end
context 'ip_addresses' do
before do
params.merge!(ip_addresses: ['192.0.2.2', '2001:DB8::1'])
end
it { is_expected.to compile }
it do
is_expected.to contain_file('/usr/local/etc/zone_check.conf').with_content(
%r{192.0.2.2}
).with_content(
%r{2001:DB8::1}
)
end
end
context 'master' do
before { params.merge!(master: true) }
it { is_expected.to compile }
it do
is_expected.to contain_concat('/etc/puppetlabs/facter/facts.d/dns_slave_tsigs.yaml')
end
it do
is_expected.to contain_concat__fragment('dns_slave_tsigs_yaml_foo.example.com').with(
'target' => '/etc/puppetlabs/facter/facts.d/dns_slave_tsigs.yaml',
'content' => "dns_slave_tsigs:\n",
'order' => '01'
)
end
it do
is_expected.to contain_concat('/etc/puppetlabs/facter/facts.d/dns_slave_addresses.yaml')
end
it do
is_expected.to contain_concat__fragment('dns_slave_addresses_yaml_foo.example.com').with(
'target' => '/etc/puppetlabs/facter/facts.d/dns_slave_addresses.yaml',
'content' => "dns_slave_addresses:\n",
'order' => '01'
)
end
end
context 'instance' do
before { params.merge!(instance: 'foobar') }
it { is_expected.to compile }
it do
expect(exported_resources).to contain_concat__fragment('dns_slave_addresses_yaml_foo.example.com').with(
'target' => '/etc/puppetlabs/facter/facts.d/dns_slave_addresses.yaml',
'tag' => 'dns::foobar_slave_interface_yaml',
'content' => "# foo.example.com\n",
'order' => '10'
)
end
end
context 'ensure' do
before { params.merge!(ensure: 'absent') }
it { is_expected.to compile }
it { is_expected.not_to contain_class('knot') }
it { is_expected.not_to contain_class('nsd') }
end
context 'enable_zonecheck' do
before { params.merge!(enable_zonecheck: false) }
it { is_expected.to compile }
it { is_expected.not_to contain_package('zonecheck') }
it do
is_expected.to contain_file('/usr/local/etc/zone_check.conf').with_ensure(
'absent'
)
end
it do
is_expected.to contain_cron('/usr/local/bin/zonecheck').with_ensure(
'absent'
)
end
end
context 'zone check log level critical' do
before { params.merge!(zonecheck_loglevel: 'critical') }
it { is_expected.to compile }
it do
is_expected.to contain_cron('/usr/local/bin/zonecheck').with(
'command' => '/usr/bin/flock -n /var/lock/zonecheck.lock /usr/local/bin/zonecheck --puppet-facts ',
)
end
end
context 'zone check log level warn' do
before { params.merge!(zonecheck_loglevel: 'warn') }
it { is_expected.to compile }
it do
is_expected.to contain_cron('/usr/local/bin/zonecheck').with(
'command' => '/usr/bin/flock -n /var/lock/zonecheck.lock /usr/local/bin/zonecheck --puppet-facts -vv',
)
end
end
context 'zone check log level info' do
before { params.merge!(zonecheck_loglevel: 'info') }
it { is_expected.to compile }
it do
is_expected.to contain_cron('/usr/local/bin/zonecheck').with(
'command' => '/usr/bin/flock -n /var/lock/zonecheck.lock /usr/local/bin/zonecheck --puppet-facts -vvv',
)
end
end
context 'zone check log level debug' do
before { params.merge!(zonecheck_loglevel: 'debug') }
it { is_expected.to compile }
it do
is_expected.to contain_cron('/usr/local/bin/zonecheck').with(
'command' => '/usr/bin/flock -n /var/lock/zonecheck.lock /usr/local/bin/zonecheck --puppet-facts -vvvv',
)
end
end
context 'zones' do
before do
params.merge!(
zones: {
'example.com' => {
'masters' => ['192.0.2.1'],
'notify_addresses' => ['192.0.2.1'],
'allow_notify' => ['192.0.2.1'],
'provide_xfr' => ['192.0.2.1'],
'zones' => ['example.com']
}
}
)
end
it { is_expected.to compile }
end
context 'files' do
before do
params.merge!(
files: { 'test' => { 'source' => 'puppet:///source' } }
)
end
it { is_expected.to compile }
end
context 'tsig' do
before { params.merge!(tsig: { 'name' => 'test', 'data' => 'aaaa' }) }
it { is_expected.to compile }
end
context 'enable_nagios' do
before do
params.merge!(
enable_nagios: true,
zones: {
'example.com' => {
'masters' => ['192.0.2.1'],
'notify_addresses' => ['192.0.2.1'],
'allow_notify' => ['192.0.2.1'],
'provide_xfr' => ['192.0.2.1'],
'zones' => ['example.com']
}
}
)
end
it { is_expected.to compile }
it do
expect(exported_resources).to contain_nagios_service(
'foo.example.com_DNS_ZONE_MASTERS_example.com'
).with(
'use' => 'generic-service',
'host_name' => 'foo.example.com',
'service_description' => 'DNS_ZONE_MASTERS_example.com',
'check_command' => 'check_nrpe_args!check_dns!example.com!192.0.2.1!192.0.2.2'
)
end
end
end
describe 'check bad type' do
context 'daemon' do
before { params.merge!(daemon: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'daemon bad option' do
before { params.merge!(daemon: 'foobar') }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'slaves_target' do
before { params.merge!(slaves_target: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'tsigs_target' do
before { params.merge!(tsigs_target: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'nsid' do
before { params.merge!(nsid: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'identity' do
before { params.merge!(identity: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'ip_addresses' do
before { params.merge!(ip_addresses: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'master' do
before { params.merge!(master: 'foobar') }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'instance' do
before { params.merge!(instance: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'ensure' do
before { params.merge!(ensure: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'ensure bad option' do
before { params.merge!(ensure: 'foobar') }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'enable_zonecheck' do
before { params.merge!(enable_zonecheck: 'foobar') }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'zones' do
before { params.merge!(zones: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'files' do
before { params.merge!(files: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'tsig' do
before { params.merge!(tsig: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'enable_nagios' do
before { params.merge!(tsig: '') }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
end
end
end
end
fix ruby syntax
require 'spec_helper'
describe 'dns' do
# by default the hiera integration uses hiera data from the shared_contexts.rb file
# but basically to mock hiera you first need to add a key/value pair
# to the specific context in the spec/shared_contexts.rb file
# Note: you can only use a single hiera context per describe/context block
# rspec-puppet does not allow you to swap out hiera data on a per test block
# include_context :hiera
let(:node) { 'dns.example.com' }
# below is the facts hash that gives you the ability to mock
# facts on a per describe/context block. If you use a fact in your
# manifest you should mock the facts below.
let(:facts) do
{}
end
# below is a list of the resource parameters that you can override.
# By default all non-required parameters are commented out,
# while all required parameters will require you to add a value
let(:params) do
{
#:daemon => "$::dns::params::daemon",
#:slaves_target => "$::dns::params::slaves_target",
#:tsigs_target => "$::dns::params::tsigs_target",
#:nsid => "$::dns::params::nsid",
#:identity => "$::dns::params::identity",
#:ip_addresses => [],
#:master => false,
instance: 'test',
#:ensure => "present",
#:enable_zonecheck => true,
#:zones => {},
#:files => {},
#:tsig => {},
#:enable_nagios => false,
}
end
# add these two lines in a single test block to enable puppet and hiera debug mode
# Puppet::Util::Log.level = :debug
# Puppet::Util::Log.newdestination(:console)
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts.merge(
'dns_slave_tsigs' => {},
'dns_slave_addresses' => {},
'ipaddress' => '192.0.2.2'
)
end
case facts[:operatingsystem]
when 'Ubuntu'
case facts['lsbdistcodename']
when 'precise'
let(:nsd_enable) { true }
let(:knot_enable) { false }
let(:dns_control) { '/usr/sbin/nsd-control' }
else
let(:nsd_enable) { false }
let(:knot_enable) { true }
let(:dns_control) { '/usr/sbin/knotc' }
end
else
let(:nsd_enable) { true }
let(:knot_enable) { false }
let(:dns_control) { '/usr/sbin/nsd-control' }
end
describe 'check default config' do
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_class('dns::params') }
it do
is_expected.to contain_package('zonecheck').with(
'ensure' => '1.0.14',
'provider' => 'pip'
)
end
it do
is_expected.to contain_file('/usr/local/etc/zone_check.conf').with(
'ensure' => 'present'
).with_content(
%r{192.0.2.2}
)
end
it do
is_expected.to contain_cron('/usr/local/bin/zonecheck').with(
'ensure' => 'present',
'command' => '/usr/bin/flock -n /var/lock/zonecheck.lock /usr/local/bin/zonecheck --puppet-facts -v',
'minute' => '*/15'
)
end
it do
is_expected.to contain_file('/usr/local/bin/dns-control').with(
'ensure' => 'link',
'target' => dns_control
)
end
it do
expect(exported_resources).to contain_concat__fragment('dns_slave_tsig_yaml_foo.example.com').with(
'target' => '/etc/puppetlabs/facter/facts.d/dns_slave_tsigs.yaml',
'tag' => 'dns::test_slave_tsigs',
'order' => '10'
).with_content(
%r{# foo.example.com}
).with_content(
%r{algo:\s+$}
).with_content(
%r{data:\s+''$}
)
end
it do
expect(exported_resources).to contain_concat__fragment('dns_slave_addresses_yaml_foo.example.com').with(
'target' => '/etc/puppetlabs/facter/facts.d/dns_slave_addresses.yaml',
'tag' => 'dns::test_slave_interface_yaml',
'content' => "# foo.example.com\n",
'order' => '10'
)
end
it do
is_expected.to contain_class('nsd').with(
'enable' => nsd_enable,
'ip_addresses' => ['192.0.2.2'],
'tsigs' => {},
'slave_addresses' => {},
'zones' => {},
'tsig' => {},
'server_count' => 1,
'files' => {},
'nsid' => 'foo.example.com',
'identity' => 'foo.example.com'
)
end
it do
is_expected.to contain_class('knot').with(
'enable' => knot_enable,
'ip_addresses' => ['192.0.2.2'],
'tsigs' => {},
'slave_addresses' => {},
'zones' => {},
'tsig' => {},
'server_count' => 1,
'files' => {},
'nsid' => 'foo.example.com',
'identity' => 'foo.example.com'
)
end
end
describe 'Change Defaults' do
context 'slaves_target' do
before { params.merge!(master: true, slaves_target: '/tmp') }
it { is_expected.to compile }
it { is_expected.to contain_concat('/tmp') }
it do
is_expected.to contain_concat__fragment('dns_slave_addresses_yaml_foo.example.com').with(
'target' => '/tmp',
'content' => "dns_slave_addresses:\n",
'order' => '01'
)
end
end
context 'tsigs_target' do
before { params.merge!(master: true, tsigs_target: '/tmp') }
it { is_expected.to compile }
it { is_expected.to contain_concat('/tmp') }
it do
is_expected.to contain_concat__fragment('dns_slave_tsigs_yaml_foo.example.com').with(
'target' => '/tmp',
'content' => "dns_slave_tsigs:\n",
'order' => '01'
)
end
end
context 'nsid' do
before { params.merge!(nsid: 'foobar') }
it { is_expected.to compile }
it { is_expected.to contain_class('knot').with('nsid' => 'foobar') }
it { is_expected.to contain_class('nsd').with('nsid' => 'foobar') }
end
context 'identity' do
before { params.merge!(identity: 'foobar') }
it { is_expected.to compile }
it { is_expected.to contain_class('knot').with('identity' => 'foobar') }
it { is_expected.to contain_class('nsd').with('identity' => 'foobar') }
end
context 'ip_addresses' do
before do
params.merge!(ip_addresses: ['192.0.2.2', '2001:DB8::1'])
end
it { is_expected.to compile }
it do
is_expected.to contain_file('/usr/local/etc/zone_check.conf').with_content(
%r{192.0.2.2}
).with_content(
%r{2001:DB8::1}
)
end
end
context 'master' do
before { params.merge!(master: true) }
it { is_expected.to compile }
it do
is_expected.to contain_concat('/etc/puppetlabs/facter/facts.d/dns_slave_tsigs.yaml')
end
it do
is_expected.to contain_concat__fragment('dns_slave_tsigs_yaml_foo.example.com').with(
'target' => '/etc/puppetlabs/facter/facts.d/dns_slave_tsigs.yaml',
'content' => "dns_slave_tsigs:\n",
'order' => '01'
)
end
it do
is_expected.to contain_concat('/etc/puppetlabs/facter/facts.d/dns_slave_addresses.yaml')
end
it do
is_expected.to contain_concat__fragment('dns_slave_addresses_yaml_foo.example.com').with(
'target' => '/etc/puppetlabs/facter/facts.d/dns_slave_addresses.yaml',
'content' => "dns_slave_addresses:\n",
'order' => '01'
)
end
end
context 'instance' do
before { params.merge!(instance: 'foobar') }
it { is_expected.to compile }
it do
expect(exported_resources).to contain_concat__fragment('dns_slave_addresses_yaml_foo.example.com').with(
'target' => '/etc/puppetlabs/facter/facts.d/dns_slave_addresses.yaml',
'tag' => 'dns::foobar_slave_interface_yaml',
'content' => "# foo.example.com\n",
'order' => '10'
)
end
end
context 'ensure' do
before { params.merge!(ensure: 'absent') }
it { is_expected.to compile }
it { is_expected.not_to contain_class('knot') }
it { is_expected.not_to contain_class('nsd') }
end
context 'enable_zonecheck' do
before { params.merge!(enable_zonecheck: false) }
it { is_expected.to compile }
it { is_expected.not_to contain_package('zonecheck') }
it do
is_expected.to contain_file('/usr/local/etc/zone_check.conf').with_ensure(
'absent'
)
end
it do
is_expected.to contain_cron('/usr/local/bin/zonecheck').with_ensure(
'absent'
)
end
end
context 'zone check log level critical' do
before { params.merge!(zonecheck_loglevel: 'critical') }
it { is_expected.to compile }
it do
is_expected.to contain_cron('/usr/local/bin/zonecheck').with(
'command' => '/usr/bin/flock -n /var/lock/zonecheck.lock /usr/local/bin/zonecheck --puppet-facts '
)
end
end
context 'zone check log level warn' do
before { params.merge!(zonecheck_loglevel: 'warn') }
it { is_expected.to compile }
it do
is_expected.to contain_cron('/usr/local/bin/zonecheck').with(
'command' => '/usr/bin/flock -n /var/lock/zonecheck.lock /usr/local/bin/zonecheck --puppet-facts -vv'
)
end
end
context 'zone check log level info' do
before { params.merge!(zonecheck_loglevel: 'info') }
it { is_expected.to compile }
it do
is_expected.to contain_cron('/usr/local/bin/zonecheck').with(
'command' => '/usr/bin/flock -n /var/lock/zonecheck.lock /usr/local/bin/zonecheck --puppet-facts -vvv'
)
end
end
context 'zone check log level debug' do
before { params.merge!(zonecheck_loglevel: 'debug') }
it { is_expected.to compile }
it do
is_expected.to contain_cron('/usr/local/bin/zonecheck').with(
'command' => '/usr/bin/flock -n /var/lock/zonecheck.lock /usr/local/bin/zonecheck --puppet-facts -vvvv'
)
end
end
context 'zones' do
before do
params.merge!(
zones: {
'example.com' => {
'masters' => ['192.0.2.1'],
'notify_addresses' => ['192.0.2.1'],
'allow_notify' => ['192.0.2.1'],
'provide_xfr' => ['192.0.2.1'],
'zones' => ['example.com']
}
}
)
end
it { is_expected.to compile }
end
context 'files' do
before do
params.merge!(
files: { 'test' => { 'source' => 'puppet:///source' } }
)
end
it { is_expected.to compile }
end
context 'tsig' do
before { params.merge!(tsig: { 'name' => 'test', 'data' => 'aaaa' }) }
it { is_expected.to compile }
end
context 'enable_nagios' do
before do
params.merge!(
enable_nagios: true,
zones: {
'example.com' => {
'masters' => ['192.0.2.1'],
'notify_addresses' => ['192.0.2.1'],
'allow_notify' => ['192.0.2.1'],
'provide_xfr' => ['192.0.2.1'],
'zones' => ['example.com']
}
}
)
end
it { is_expected.to compile }
it do
expect(exported_resources).to contain_nagios_service(
'foo.example.com_DNS_ZONE_MASTERS_example.com'
).with(
'use' => 'generic-service',
'host_name' => 'foo.example.com',
'service_description' => 'DNS_ZONE_MASTERS_example.com',
'check_command' => 'check_nrpe_args!check_dns!example.com!192.0.2.1!192.0.2.2'
)
end
end
end
describe 'check bad type' do
context 'daemon' do
before { params.merge!(daemon: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'daemon bad option' do
before { params.merge!(daemon: 'foobar') }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'slaves_target' do
before { params.merge!(slaves_target: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'tsigs_target' do
before { params.merge!(tsigs_target: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'nsid' do
before { params.merge!(nsid: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'identity' do
before { params.merge!(identity: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'ip_addresses' do
before { params.merge!(ip_addresses: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'master' do
before { params.merge!(master: 'foobar') }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'instance' do
before { params.merge!(instance: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'ensure' do
before { params.merge!(ensure: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'ensure bad option' do
before { params.merge!(ensure: 'foobar') }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'enable_zonecheck' do
before { params.merge!(enable_zonecheck: 'foobar') }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'zones' do
before { params.merge!(zones: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'files' do
before { params.merge!(files: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'tsig' do
before { params.merge!(tsig: true) }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
context 'enable_nagios' do
before { params.merge!(tsig: '') }
it { expect { subject.call }.to raise_error(Puppet::Error) }
end
end
end
end
end
|
RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
require File.join(File.dirname(__FILE__), 'boot')
unless File.exist?(config_filename = Rails.root + 'config/database.yml')
puts config_filename
require 'fileutils'
FileUtils.cp("#{config_filename}.example", config_filename)
end
PLUGIN_HOOKS = {
:more_page => []
}
Rails::Initializer.run do |config|
config.action_controller.session_store = :active_record_store
config.action_controller.cache_store = :file_store, Rails.root + 'cache'
config.log_path = File.join(File.dirname(__FILE__), "../log/#{RAILS_ENV}.log")
config.database_configuration_file = File.expand_path(File.join(File.dirname(__FILE__), 'database.yml'))
config.load_paths << Rails.root + 'app/sweepers'
config.plugin_paths << Rails.root + 'plugins'
config.time_zone = 'UTC'
# dependencies
config.gem 'liquid'
config.gem 'pdf-writer', :lib => 'pdf/writer'
config.gem 'highline'
config.gem 'mini_magick'
config.gem 'twitter'
config.gem 'xmpp4r'
config.gem 'mislav-will_paginate', :source => 'http://gems.github.com', :lib => 'will_paginate', :version => '~> 2.3.0'
config.gem 'seven1m-acts_as_scoped_globally', :source => 'http://gems.github.com', :lib => 'acts_as_scoped_globally'
config.gem 'seven1m-has_one_photo', :source => 'http://gems.github.com', :lib => 'has_one_photo'
config.gem 'seven1m-has_one_file', :source => 'http://gems.github.com', :lib => 'has_one_file'
config.gem 'seven1m-campaign_monitor', :source => 'http://gems.github.com', :lib => 'campaign_monitor'
config.gem 'chronic'
config.gem 'javan-whenever', :source => 'http://gems.github.com', :lib => 'whenever'
config.gem 'pauldix-feedzirra', :source => 'http://gems.github.com', :lib => 'feedzirra'
end
PHONE_HOME_FOR_VERSION_INFO = true unless defined? PHONE_HOME_FOR_VERSION_INFO
(Setting.update_all if Setting.table_exists?) rescue nil
Additional gem dependencies.
RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
require File.join(File.dirname(__FILE__), 'boot')
unless File.exist?(config_filename = Rails.root + 'config/database.yml')
puts config_filename
require 'fileutils'
FileUtils.cp("#{config_filename}.example", config_filename)
end
PLUGIN_HOOKS = {
:more_page => []
}
Rails::Initializer.run do |config|
config.action_controller.session_store = :active_record_store
config.action_controller.cache_store = :file_store, Rails.root + 'cache'
config.log_path = File.join(File.dirname(__FILE__), "../log/#{RAILS_ENV}.log")
config.database_configuration_file = File.expand_path(File.join(File.dirname(__FILE__), 'database.yml'))
config.load_paths << Rails.root + 'app/sweepers'
config.plugin_paths << Rails.root + 'plugins'
config.time_zone = 'UTC'
# dependencies
config.gem 'liquid'
config.gem 'pdf-writer', :lib => 'pdf/writer'
config.gem 'highline'
config.gem 'mini_magick'
config.gem 'twitter'
config.gem 'xmpp4r'
config.gem 'mislav-will_paginate', :source => 'http://gems.github.com', :lib => 'will_paginate', :version => '~> 2.3.0'
config.gem 'seven1m-acts_as_scoped_globally', :source => 'http://gems.github.com', :lib => 'acts_as_scoped_globally'
config.gem 'seven1m-has_one_photo', :source => 'http://gems.github.com', :lib => 'has_one_photo'
config.gem 'seven1m-has_one_file', :source => 'http://gems.github.com', :lib => 'has_one_file'
config.gem 'seven1m-campaign_monitor', :source => 'http://gems.github.com', :lib => 'campaign_monitor'
config.gem 'chronic'
config.gem 'javan-whenever', :source => 'http://gems.github.com', :lib => 'whenever'
config.gem 'nokogiri'
config.gem 'builder'
config.gem 'pauldix-feedzirra', :source => 'http://gems.github.com', :lib => 'feedzirra'
end
PHONE_HOME_FOR_VERSION_INFO = true unless defined? PHONE_HOME_FOR_VERSION_INFO
(Setting.update_all if Setting.table_exists?) rescue nil |
# encoding: utf-8
require 'spec_helper'
def package_provider_for_gems
Puppet.version =~ /^4/ ? 'puppet_gem' : 'gem'
end
describe 'zabbix::web' do
let :node do
'rspec.puppet.com'
end
let :params do
{
zabbix_url: 'zabbix.example.com'
}
end
# Running an RedHat OS.
context 'On a RedHat OS' do
let :facts do
{
osfamily: 'RedHat',
operatingsystem: 'RedHat',
operatingsystemrelease: '6.5',
operatingsystemmajrelease: '6',
architecture: 'x86_64',
lsbdistid: 'RedHat',
concat_basedir: '/tmp',
is_pe: false,
puppetversion: Puppet.version,
facterversion: Facter.version,
ipaddress: '192.168.1.10',
lsbdistcodename: '',
id: 'root',
kernel: 'Linux',
path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/sbin',
selinux_config_mode: ''
}
end
describe 'with default settings' do
it { should contain_file('/etc/zabbix/web').with_ensure('directory') }
end
describe 'with database_type as postgresql' do
let :params do
super().merge(database_type: 'postgresql')
end
it { should contain_package('zabbix-web-pgsql').with_name('zabbix-web-pgsql') }
it { should contain_package('zabbix-web') }
it { should contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(/^\$DB\['TYPE'\] = 'POSTGRESQL'/) }
end
describe 'with database_type as mysql' do
let :params do
super().merge(database_type: 'mysql')
end
it { should contain_package('zabbix-web-mysql').with_name('zabbix-web-mysql') }
it { should contain_package('zabbix-web') }
end
it { should contain_file('/etc/zabbix/web/zabbix.conf.php') }
describe 'when manage_resources is true' do
let :params do
super().merge(
manage_resources: true
)
end
it { should contain_class('zabbix::resources::web') }
it { should contain_package('zabbixapi').that_requires('Class[ruby::dev]').with_provider(package_provider_for_gems) }
it { should contain_class('ruby::dev') }
it { should contain_file('/etc/zabbix/imported_templates').with_ensure('directory') }
end
describe 'when manage_resources and is_pe are true' do
let :facts do
super().merge(
is_pe: true,
pe_version: '3.7.0'
)
end
let :params do
super().merge(manage_resources: true)
end
it { should contain_package('zabbixapi').with_provider('pe_puppetserver_gem') }
end
describe 'when manage_resources is false' do
let :params do
super().merge(manage_resources: false)
end
it { should_not contain_class('zabbix::resources::web') }
end
it { should contain_apache__vhost('zabbix.example.com').with_name('zabbix.example.com') }
context 'with database_* settings' do
let :params do
super().merge(
database_host: 'localhost',
database_name: 'zabbix-server',
database_user: 'zabbix-server',
database_password: 'zabbix-server',
zabbix_server: 'localhost')
end
it { should contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(/^\$DB\['SERVER'\] = 'localhost'/) }
it { should contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(/^\$DB\['DATABASE'\] = 'zabbix-server'/) }
it { should contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(/^\$DB\['USER'\] = 'zabbix-server'/) }
it { should contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(/^\$DB\['PASSWORD'\] = 'zabbix-server'/) }
it { should contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(/^\$ZBX_SERVER = 'localhost'/) }
end
end
end
describe 'zabbix::web' do
let :node do
'rspec.puppet.com'
end
let :params do
{
zabbix_url: 'zabbix.example.com'
}
end
context 'On Debian 6.0' do
let :facts do
{
osfamily: 'debian',
operatingsystem: 'debian',
operatingsystemrelease: '6.0',
operatingsystemmajrelease: '6',
architecture: 'x86_64',
lsbdistid: 'debian',
concat_basedir: '/tmp',
is_pe: false,
puppetversion: Puppet.version,
facterversion: Facter.version,
ipaddress: '192.168.1.10',
lsbdistcodename: 'squeeze',
id: 'root',
kernel: 'Linux',
path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/sbin',
selinux_config_mode: ''
}
end
it { should contain_package('zabbix-frontend-php') }
end
end
add selinux spec test for web
# encoding: utf-8
require 'spec_helper'
def package_provider_for_gems
Puppet.version =~ /^4/ ? 'puppet_gem' : 'gem'
end
describe 'zabbix::web' do
let :node do
'rspec.puppet.com'
end
let :params do
{
zabbix_url: 'zabbix.example.com'
}
end
# Running an RedHat OS.
context 'On a RedHat OS' do
let :facts do
{
osfamily: 'RedHat',
operatingsystem: 'RedHat',
operatingsystemrelease: '6.5',
operatingsystemmajrelease: '6',
architecture: 'x86_64',
lsbdistid: 'RedHat',
concat_basedir: '/tmp',
is_pe: false,
puppetversion: Puppet.version,
facterversion: Facter.version,
ipaddress: '192.168.1.10',
lsbdistcodename: '',
id: 'root',
kernel: 'Linux',
path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/sbin',
selinux_config_mode: ''
}
end
describe 'with default settings' do
it { should contain_file('/etc/zabbix/web').with_ensure('directory') }
it { should_not contain_selboolean('httpd_can_connect_zabbix') }
end
describe 'with enabled selinux' do
let :facts do
super().merge(selinux_config_mode: 'enforcing')
end
it { should contain_selboolean('httpd_can_connect_zabbix').with('value' => 'on', 'persistent' => true) }
end
describe 'with database_type as postgresql' do
let :params do
super().merge(database_type: 'postgresql')
end
it { should contain_package('zabbix-web-pgsql').with_name('zabbix-web-pgsql') }
it { should contain_package('zabbix-web') }
it { should contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(/^\$DB\['TYPE'\] = 'POSTGRESQL'/) }
end
describe 'with database_type as mysql' do
let :params do
super().merge(database_type: 'mysql')
end
it { should contain_package('zabbix-web-mysql').with_name('zabbix-web-mysql') }
it { should contain_package('zabbix-web') }
end
it { should contain_file('/etc/zabbix/web/zabbix.conf.php') }
describe 'when manage_resources is true' do
let :params do
super().merge(
manage_resources: true
)
end
it { should contain_class('zabbix::resources::web') }
it { should contain_package('zabbixapi').that_requires('Class[ruby::dev]').with_provider(package_provider_for_gems) }
it { should contain_class('ruby::dev') }
it { should contain_file('/etc/zabbix/imported_templates').with_ensure('directory') }
end
describe 'when manage_resources and is_pe are true' do
let :facts do
super().merge(
is_pe: true,
pe_version: '3.7.0'
)
end
let :params do
super().merge(manage_resources: true)
end
it { should contain_package('zabbixapi').with_provider('pe_puppetserver_gem') }
end
describe 'when manage_resources is false' do
let :params do
super().merge(manage_resources: false)
end
it { should_not contain_class('zabbix::resources::web') }
end
it { should contain_apache__vhost('zabbix.example.com').with_name('zabbix.example.com') }
context 'with database_* settings' do
let :params do
super().merge(
database_host: 'localhost',
database_name: 'zabbix-server',
database_user: 'zabbix-server',
database_password: 'zabbix-server',
zabbix_server: 'localhost')
end
it { should contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(/^\$DB\['SERVER'\] = 'localhost'/) }
it { should contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(/^\$DB\['DATABASE'\] = 'zabbix-server'/) }
it { should contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(/^\$DB\['USER'\] = 'zabbix-server'/) }
it { should contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(/^\$DB\['PASSWORD'\] = 'zabbix-server'/) }
it { should contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(/^\$ZBX_SERVER = 'localhost'/) }
end
end
end
describe 'zabbix::web' do
let :node do
'rspec.puppet.com'
end
let :params do
{
zabbix_url: 'zabbix.example.com'
}
end
context 'On Debian 6.0' do
let :facts do
{
osfamily: 'debian',
operatingsystem: 'debian',
operatingsystemrelease: '6.0',
operatingsystemmajrelease: '6',
architecture: 'x86_64',
lsbdistid: 'debian',
concat_basedir: '/tmp',
is_pe: false,
puppetversion: Puppet.version,
facterversion: Facter.version,
ipaddress: '192.168.1.10',
lsbdistcodename: 'squeeze',
id: 'root',
kernel: 'Linux',
path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/sbin',
selinux_config_mode: ''
}
end
it { should contain_package('zabbix-frontend-php') }
end
end
|
# Be sure to restart your server when you modify this file
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'development'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.2.2' # unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
require 'rails_generator/secret_key_generator'
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# See Rails::Configuration for more options.
# Skip frameworks you're not going to use (only works if using vendor/rails).
# To use Rails without a database, you must remove the Active Record framework
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Only load the plugins named here, in the order given. By default, all plugins
# in vendor/plugins are loaded in alphabetical order.
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
secret_file = File.join(RAILS_ROOT, "secret")
if File.exist?(secret_file)
secret = File.read(secret_file)
else
secret = Rails::SecretKeyGenerator.new("insoshi").generate_secret
File.open(secret_file, 'w') { |f| f.write(secret) }
end
config.action_controller.session = {
:session_key => '_communtu_session',
:secret => '367e4806af33b2cd7ddc839f908a7ed6844a3b369ce46724a3c419a633c1c68d612692d3f441ba2b31158e167c4bb5c81a5be173e83a2d6a7f7043111be4fdfc'
}
# use file system for session storing
# config.action_controller.session_store = :p_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
# Make Active Record use UTC-base instead of local time
# config.active_record.default_timezone = :utc
config.active_record.observers = :user_observer
config.action_mailer.delivery_method = :smtp
require 'german_date_names'
# The internationalization framework can be changed
# to have another default locale (standard is :en) or more load paths.
# All files from config/locales/*.rb,yml are added automatically.
config.i18n.load_path += Dir[File.join(RAILS_ROOT, 'config', 'locales', '*.{rb,yml}')]
#["#{RAILS_ROOT}/config/locales/template.yml","#{RAILS_ROOT}/config/locales/template-en.yml","#{RAILS_ROOT}/config/locales/numbers.yml"]
config.i18n.default_locale = :de
AVAILABLE_LOCALES = :de, :en
end
laguages
git-svn-id: e70f47238a868777ecefe75ba01929cffb2d8127@903 d8b24053-1f83-4035-b5c3-ce8b92cd91ad
# Be sure to restart your server when you modify this file
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'development'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.2.2' # unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
require 'rails_generator/secret_key_generator'
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# See Rails::Configuration for more options.
# Skip frameworks you're not going to use (only works if using vendor/rails).
# To use Rails without a database, you must remove the Active Record framework
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Only load the plugins named here, in the order given. By default, all plugins
# in vendor/plugins are loaded in alphabetical order.
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
secret_file = File.join(RAILS_ROOT, "secret")
if File.exist?(secret_file)
secret = File.read(secret_file)
else
secret = Rails::SecretKeyGenerator.new("insoshi").generate_secret
File.open(secret_file, 'w') { |f| f.write(secret) }
end
config.action_controller.session = {
:session_key => '_communtu_session',
:secret => '367e4806af33b2cd7ddc839f908a7ed6844a3b369ce46724a3c419a633c1c68d612692d3f441ba2b31158e167c4bb5c81a5be173e83a2d6a7f7043111be4fdfc'
}
# use file system for session storing
# config.action_controller.session_store = :p_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
# Make Active Record use UTC-base instead of local time
# config.active_record.default_timezone = :utc
config.active_record.observers = :user_observer
config.action_mailer.delivery_method = :smtp
require 'german_date_names'
# The internationalization framework can be changed
# to have another default locale (standard is :en) or more load paths.
# All files from config/locales/*.rb,yml are added automatically.
config.i18n.load_path += Dir[File.join(RAILS_ROOT, 'config', 'locales', '*.{rb,yml}')]
#["#{RAILS_ROOT}/config/locales/template.yml","#{RAILS_ROOT}/config/locales/template-en.yml","#{RAILS_ROOT}/config/locales/numbers.yml"]
config.i18n.default_locale = :de
AVAILABLE_LOCALES = [:de, :en]
end
|
require 'spec_helper'
class OrderParams
include Condensable
end
describe Condensable do
it 'has a version number' do
expect(Condensable::VERSION).not_to be nil
end
let(:order_params) { OrderParams.new }
describe OrderParams do
it "includes Condensable" do
OrderParams.include?(Condensable)
end
it "includes Condensable::GravityAbsorber" do
OrderParams.include?(Condensable::GravityAbsorber)
end
it "can make new variable on the fly" do
expect { order_params.order_id = 1 }.not_to raise_error()
expect(order_params.respond_to?(:order_id=)).to be_truthy
expect(order_params.respond_to?(:order_id)).to be_truthy
expect(order_params.order_id).to eq(1)
end
it "can re-assign variable value" do
order_params.order_id = 1
expect(order_params.order_id).to eq(1)
order_params.order_id = "BC23-19238-29910299"
expect(order_params.order_id).to eq("BC23-19238-29910299")
end
end
context "with default behaviour" do
context "if unspecified" do
it "returns nil" do
expect(order_params.adam).to eq(nil)
end
end
context "if set to returns a astring" do
it "returns string" do
class OrderParamsReturnStringC
include Condensable
condensable default: "adam"
end
op = OrderParamsReturnStringC.new
expect(op.name).to eq("adam")
end
end
context "if set to execute method" do
it "executes a method" do
class OrderParamsExecMethod
include Condensable
condensable default: :execute_me
def execute_me
"adam pahlevi"
end
end
opem = OrderParamsExecMethod.new
expect(opem.name).to eq("adam pahlevi")
end
it "executes a method with params" do
class OrderParamsExecMethodParams
include Condensable
condensable default: :execute_me
def execute_me(name, *args)
[name] + args
end
end
opemp = OrderParamsExecMethodParams.new
expect(opemp.name("adam")).to eq([:name, "adam"])
expect(opemp.age).to eq([:age])
expect(opemp.whatever("adam", "pahlevi")).to eq([:whatever, "adam", "pahlevi"])
end
end
context "if set to raise an error" do
it "raises an error" do
class OrderParamsRaiseError
include Condensable
condensable default: :raise_error
end
opre = OrderParamsRaiseError.new
expect { opre.name }.to raise_error(NoMethodError)
end
end
end
end
add test spec
require 'spec_helper'
class OrderParams
include Condensable
end
describe Condensable do
it 'has a version number' do
expect(Condensable::VERSION).not_to be nil
end
let(:order_params) { OrderParams.new }
describe OrderParams do
it "includes Condensable" do
OrderParams.include?(Condensable)
end
it "includes Condensable::GravityAbsorber" do
OrderParams.include?(Condensable::GravityAbsorber)
end
it "can make new variable on the fly" do
expect { order_params.order_id = 1 }.not_to raise_error()
expect(order_params.respond_to?(:order_id=)).to be_truthy
expect(order_params.respond_to?(:order_id)).to be_truthy
expect(order_params.order_id).to eq(1)
end
context "with condensed values" do
before do
order_params.order_id = "ABC-1234"
order_params.delivery = "Jl HR. Rasuna Said 23"
order_params.name = "Adam Pahlevi"
order_params.city = "Jakarta"
end
it "can respond to keys and return all condensed keys" do
expect(order_params.keys).to eq([:order_id, :delivery, :name, :city])
end
it "can respond to values and return all condensed values" do
expect(order_params.values).to eq(["ABC-1234", "Jl HR. Rasuna Said 23", "Adam Pahlevi", "Jakarta"])
end
it "can respond to each" do
expect(order_params.respond_to?(:each)).to be_truthy
each_vars = {}
order_params.each do |key, value|
each_vars[key] = value
end
expect(each_vars).to eq({:order_id=>"ABC-1234", :delivery=>"Jl HR. Rasuna Said 23", :name=>"Adam Pahlevi", :city=>"Jakarta"})
end
it "can tell whether a variable is a result of condensation or not" do
expect(order_params.is_condensed?(:order_id)).to be_truthy
expect(order_params.is_condensed?(:name)).to be_truthy
expect(order_params.is_condensed?(:delivery)).to be_truthy
expect(order_params.is_condensed?(:city)).to be_truthy
expect(order_params.is_condensed?(:address)).to be_falsey
end
end
it "can re-assign variable value" do
order_params.order_id = 1
expect(order_params.order_id).to eq(1)
order_params.order_id = "BC23-19238-29910299"
expect(order_params.order_id).to eq("BC23-19238-29910299")
end
end
context "with default behaviour" do
context "if unspecified" do
it "returns nil" do
expect(order_params.adam).to eq(nil)
end
end
context "if set to returns a astring" do
it "returns string" do
class OrderParamsReturnStringC
include Condensable
condensable default: "adam"
end
op = OrderParamsReturnStringC.new
expect(op.name).to eq("adam")
end
end
context "if set to execute method" do
it "executes a method" do
class OrderParamsExecMethod
include Condensable
condensable default: :execute_me
def execute_me
"adam pahlevi"
end
end
opem = OrderParamsExecMethod.new
expect(opem.name).to eq("adam pahlevi")
end
it "executes a method with params" do
class OrderParamsExecMethodParams
include Condensable
condensable default: :execute_me
def execute_me(name, *args)
[name] + args
end
end
opemp = OrderParamsExecMethodParams.new
expect(opemp.name("adam")).to eq([:name, "adam"])
expect(opemp.age).to eq([:age])
expect(opemp.whatever("adam", "pahlevi")).to eq([:whatever, "adam", "pahlevi"])
end
end
context "if set to raise an error" do
it "raises an error" do
class OrderParamsRaiseError
include Condensable
condensable default: :raise_error
end
opre = OrderParamsRaiseError.new
expect { opre.name }.to raise_error(NoMethodError)
end
end
end
end
|
# Copyright (c) 2010, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3. See
# the COPYRIGHT file.
# Load the rails application
require File.expand_path('../application', __FILE__)
Haml::Template.options[:format] = :html5
# Initialize the rails application
Diaspora::Application.initialize!
Adding Haml html escaping.
Haml's HTML escaping option was not on, leaving the site open for xss
attacks. This would seem to fix it.
# Copyright (c) 2010, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3. See
# the COPYRIGHT file.
# Load the rails application
require File.expand_path('../application', __FILE__)
Haml::Template.options[:format] = :html5
Haml::Template.options[:escape_html] = true
# Initialize the rails application
Diaspora::Application.initialize!
|
# Be sure to restart your web server when you modify this file.
RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION
#gem 'rack-cache'
#require 'rack/cache'
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence those specified here
config.action_controller.session = {
:key => '_journey_aegames_org-trunk_session',
:secret => 'ca837e0d9bfed2129139ac1712cf768687981f043aca55c15b424d1deee830babca9bf84afea63d9fd18164f9b026b5c5846b3cb1d64d8febeab9618d24a385f'
}
# Use Active Record's schema dumper instead of SQL when creating the test database
# (enables use of different database adapters for development and test environments)
config.active_record.schema_format = :ruby
config.gem 'paginator'
config.gem 'mislav-will_paginate', :version => '~> 2.3.2', :lib => 'will_paginate',
:source => 'http://gems.github.com'
config.gem 'rmagick', :lib => 'RMagick'
config.gem 'umang-gruff', :lib => 'gruff', :source => 'http://gems.github.com', :version => '~> 0.3.6'
config.action_view.sanitized_allowed_attributes = ['id', 'class', 'style']
# config.middleware.use(Rack::Cache) do
# import 'config/rack_cache_config'
# end
end
Mime::Type.register "image/png", :png
AeUsers.cache_permissions = false
require 'journey_questionnaire'
Journey::UserOptions.add_logged_out_option("Log in", {:controller => "auth", :action => "login" })
Journey::UserOptions.add_logged_in_option("Profile", {:controller => "account", :action => "edit_profile" })
Journey::UserOptions.add_logged_in_option("Admin", {:controller => "permission", :action => "admin" },
:conditional => lambda do |view|
view.logged_in? and view.logged_in_person.administrator?
end)
Journey::UserOptions.add_logged_in_option("Log out", {:controller => "auth", :action => "logout" })
Set session expiry time to 2 weeks
# Be sure to restart your web server when you modify this file.
RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION
#gem 'rack-cache'
#require 'rack/cache'
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence those specified here
config.action_controller.session = {
:key => '_journey_aegames_org-trunk_session',
:secret => 'ca837e0d9bfed2129139ac1712cf768687981f043aca55c15b424d1deee830babca9bf84afea63d9fd18164f9b026b5c5846b3cb1d64d8febeab9618d24a385f',
:expire_after => 2.weeks
}
# Use Active Record's schema dumper instead of SQL when creating the test database
# (enables use of different database adapters for development and test environments)
config.active_record.schema_format = :ruby
config.gem 'paginator'
config.gem 'mislav-will_paginate', :version => '~> 2.3.2', :lib => 'will_paginate',
:source => 'http://gems.github.com'
config.gem 'rmagick', :lib => 'RMagick'
config.gem 'umang-gruff', :lib => 'gruff', :source => 'http://gems.github.com', :version => '~> 0.3.6'
config.action_view.sanitized_allowed_attributes = ['id', 'class', 'style']
# config.middleware.use(Rack::Cache) do
# import 'config/rack_cache_config'
# end
end
Mime::Type.register "image/png", :png
AeUsers.cache_permissions = false
require 'journey_questionnaire'
Journey::UserOptions.add_logged_out_option("Log in", {:controller => "auth", :action => "login" })
Journey::UserOptions.add_logged_in_option("Profile", {:controller => "account", :action => "edit_profile" })
Journey::UserOptions.add_logged_in_option("Admin", {:controller => "permission", :action => "admin" },
:conditional => lambda do |view|
view.logged_in? and view.logged_in_person.administrator?
end)
Journey::UserOptions.add_logged_in_option("Log out", {:controller => "auth", :action => "logout" })
|
# Load the rails application
require File.expand_path('../application', __FILE__)
# this is very useful, specifically for the time_ago_in_words method
include ActionView::Helpers::DateHelper
# showing the output of log entries requires Pretty Print
require 'pp'
# Initialize the rails application
CraigsAdmin::Application.initialize!
DocRaptor.api_key 'tl8fHT64wxhkLUTW0Y6V'
Temporary Authorize.net credentials
# Load the rails application
require File.expand_path('../application', __FILE__)
# this is very useful, specifically for the time_ago_in_words method
include ActionView::Helpers::DateHelper
# showing the output of log entries requires Pretty Print
require 'pp'
# Initialize the rails application
CraigsAdmin::Application.initialize!
DocRaptor.api_key 'tl8fHT64wxhkLUTW0Y6V'
AUTHNET_LOGIN = "2y9kBc3rXn"
AUTHNET_KEY = "8SXA34Ag6qa28SuH"
AUTHNET_ENV = :sandbox |
# Be sure to restart your server when you modify this file
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'development'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.8' # unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require 'thread'
require File.join(File.dirname(__FILE__), 'boot')
#
# this was commented out for switching to 2.3.8
#
#require 'rails_generator/secret_key_generator'
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# See Rails::Configuration for more options.
# Skip frameworks you're not going to use (only works if using vendor/rails).
# To use Rails without a database, you must remove the Active Record framework
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Only load the plugins named here, in the order given. By default, all plugins
# in vendor/plugins are loaded in alphabetical order.
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
#
# the lines below are commented because they cause an error when switching to 2.3.8
#
# secret_file = File.join(RAILS_ROOT, "secret")
# if File.exist?(secret_file)
# secret = File.read(secret_file)
# else
# secret = Rails::SecretKeyGenerator.new("insoshi").generate_secret
# File.open(secret_file, 'w') { |f| f.write(secret) }
# end
config.action_controller.session = {
:key => '_communtu_session', # was session_key, changed for 2.3.8
:secret => '367e4806af33b2cd7ddc839f908a7ed6844a3b369ce46724a3c419a633c1c68d612692d3f441ba2b31158e167c4bb5c81a5be173e83a2d6a7f7043111be4fdfc'
}
# use file system for session storing
# config.action_controller.session_store = :p_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
# Make Active Record use UTC-base instead of local time
# config.active_record.default_timezone = :utc
config.active_record.observers = :user_observer
config.action_mailer.delivery_method = :smtp
require 'german_date_names'
# The internationalization framework can be changed
# to have another default locale (standard is :en) or more load paths.
# All files from config/locales/*.rb,yml are added automatically.
config.i18n.load_path += Dir[File.join(RAILS_ROOT, 'config', 'locales', '*.{rb,yml}')]
#["#{RAILS_ROOT}/config/locales/template.yml","#{RAILS_ROOT}/config/locales/template-en.yml","#{RAILS_ROOT}/config/locales/numbers.yml"]
config.i18n.default_locale = :en
AVAILABLE_LOCALES = ["de", "en","fr"]
SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml")
end
corrected default locale
# Be sure to restart your server when you modify this file
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'development'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.8' # unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require 'thread'
require File.join(File.dirname(__FILE__), 'boot')
#
# this was commented out for switching to 2.3.8
#
#require 'rails_generator/secret_key_generator'
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# See Rails::Configuration for more options.
# Skip frameworks you're not going to use (only works if using vendor/rails).
# To use Rails without a database, you must remove the Active Record framework
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Only load the plugins named here, in the order given. By default, all plugins
# in vendor/plugins are loaded in alphabetical order.
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
#
# the lines below are commented because they cause an error when switching to 2.3.8
#
# secret_file = File.join(RAILS_ROOT, "secret")
# if File.exist?(secret_file)
# secret = File.read(secret_file)
# else
# secret = Rails::SecretKeyGenerator.new("insoshi").generate_secret
# File.open(secret_file, 'w') { |f| f.write(secret) }
# end
config.action_controller.session = {
:key => '_communtu_session', # was session_key, changed for 2.3.8
:secret => '367e4806af33b2cd7ddc839f908a7ed6844a3b369ce46724a3c419a633c1c68d612692d3f441ba2b31158e167c4bb5c81a5be173e83a2d6a7f7043111be4fdfc'
}
# use file system for session storing
# config.action_controller.session_store = :p_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
# Make Active Record use UTC-base instead of local time
# config.active_record.default_timezone = :utc
config.active_record.observers = :user_observer
config.action_mailer.delivery_method = :smtp
require 'german_date_names'
# The internationalization framework can be changed
# to have another default locale (standard is :en) or more load paths.
# All files from config/locales/*.rb,yml are added automatically.
config.i18n.load_path += Dir[File.join(RAILS_ROOT, 'config', 'locales', '*.{rb,yml}')]
#["#{RAILS_ROOT}/config/locales/template.yml","#{RAILS_ROOT}/config/locales/template-en.yml","#{RAILS_ROOT}/config/locales/numbers.yml"]
config.i18n.default_locale = :de
AVAILABLE_LOCALES = ["de", "en","fr"]
SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml")
end
|
Pod::Spec.new do |s|
s.name = "JSBridge"
s.version = "0.1"
s.summary = "Make iOS and Android work in a same way"
s.homepage = "https://github.com/sun-fox-cj/JSBridge/tree/0.1"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "cjfire" => "cjfire@sina.cn" }
s.source = { :git => "https://github.com/sun-fox-cj/JSBridge.git", :tag => s.version}
s.platform = :ios, '6.0'
s.requires_arc = true
# s.ios.deployment_target = "5.0"
s.source_files = "JSBridge/JSBridge/*.{h, m}"
end
update podspec
Pod::Spec.new do |s|
s.name = "JSBridge"
s.version = "0.1"
s.summary = "Make iOS and Android work in a same way"
s.homepage = "https://github.com/sun-fox-cj/JSBridge/tree/0.1"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "cjfire" => "cjfire@sina.cn" }
s.source = { :git => "https://github.com/sun-fox-cj/JSBridge.git", :tag => s.version}
s.platform = :ios, '6.0'
s.requires_arc = true
s.source_files = "JSBridge/JSBridge/**/*.{h, m}"
end |
# Be sure to restart your web server when you modify this file.
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.11' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
# MySociety specific helper functions
$:.push(File.join(File.dirname(__FILE__), '../commonlib/rblib'))
# ... if these fail to include, you need the commonlib submodule from git
# (type "git submodule update --init" in the whatdotheyknow directory)
# ruby-ole and ruby-msg. We use a custom ruby-msg to avoid a name conflict
$:.unshift(File.join(File.dirname(__FILE__), '../vendor/ruby-ole/lib'))
$:.unshift(File.join(File.dirname(__FILE__), '../vendor/ruby-msg/lib'))
# FIXME: These gems needed to be installed using 'sude gem install ...' -
# apt-get install does not seem to install them where they can be found:
#
# fcgi
# memcache-client
# mongrel
# thin
require 'memcache'
load "validate.rb"
load "config.rb"
load "format.rb"
load "debug_helpers.rb"
load "util.rb"
Rails::Initializer.run do |config|
# Load intial mySociety config
MySociety::Config.set_file(File.join(config.root_path, 'config', 'general'), true)
MySociety::Config.load_default
# Settings in config/environments/* take precedence over those specified here
# Skip frameworks you're not going to use (only works if using vendor/rails)
# config.frameworks -= [ :action_web_service, :action_mailer ]
# Only load the plugins named here, by default all plugins in vendor/plugins are loaded
# config.plugins = %W( exception_notification ssl_requirement )
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# TEMP: uncomment this to turn on logging in production environments
# config.log_level = :debug
#
# Specify gems that this application depends on and have them installed with rake gems:install
config.gem "rack", :version => '1.1.0'
config.gem 'rspec-rails', :lib => false, :version => '1.3.3'
config.gem "recaptcha", :lib => "recaptcha/rails"
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_wdtk_cookie_session',
:secret => MySociety::Config.get("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')
}
config.action_controller.session_store = :cookie_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
config.active_record.schema_format = :sql
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
# Make Active Record use UTC-base instead of local time
config.active_record.default_timezone = :utc
# See Rails::Configuration for more options
ENV['RECAPTCHA_PUBLIC_KEY'] = MySociety::Config::get("RECAPTCHA_PUBLIC_KEY", 'x');
ENV['RECAPTCHA_PRIVATE_KEY'] = MySociety::Config::get("RECAPTCHA_PRIVATE_KEY", 'x');
end
# Add new inflection rules using the following format
# (all these examples are active by default):
# Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register "application/x-mobile", :mobile
# The Rails cache is set up by the Interlock plugin to use memcached
# Domain for URLs (so can work for scripts, not just web pages)
ActionMailer::Base.default_url_options[:host] = MySociety::Config.get("DOMAIN", 'localhost:3000')
# So that javascript assets use full URL, so proxied admin URLs read javascript OK
if (MySociety::Config.get("DOMAIN", "") != "")
ActionController::Base.asset_host = Proc.new { |source, request|
if request.fullpath.match(/^\/admin\//)
MySociety::Config.get("ADMIN_PUBLIC_URL", "/")
else
MySociety::Config.get("DOMAIN", 'localhost:3000')
end
}
end
# Load monkey patches and other things from lib/
require 'tmail_extensions.rb'
require 'activesupport_cache_extensions.rb'
require 'public_body_categories.rb'
require 'timezone_fixes.rb'
require 'use_spans_for_errors.rb'
require 'make_html_4_compliant.rb'
require 'activerecord_errors_extensions.rb'
require 'willpaginate_hack.rb'
require 'sendmail_return_path.rb'
require 'tnef.rb'
Adding dependency on will_paginate gem.
# Be sure to restart your web server when you modify this file.
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.11' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
# MySociety specific helper functions
$:.push(File.join(File.dirname(__FILE__), '../commonlib/rblib'))
# ... if these fail to include, you need the commonlib submodule from git
# (type "git submodule update --init" in the whatdotheyknow directory)
# ruby-ole and ruby-msg. We use a custom ruby-msg to avoid a name conflict
$:.unshift(File.join(File.dirname(__FILE__), '../vendor/ruby-ole/lib'))
$:.unshift(File.join(File.dirname(__FILE__), '../vendor/ruby-msg/lib'))
# FIXME: These gems needed to be installed using 'sude gem install ...' -
# apt-get install does not seem to install them where they can be found:
#
# fcgi
# memcache-client
# mongrel
# thin
require 'memcache'
load "validate.rb"
load "config.rb"
load "format.rb"
load "debug_helpers.rb"
load "util.rb"
Rails::Initializer.run do |config|
# Load intial mySociety config
MySociety::Config.set_file(File.join(config.root_path, 'config', 'general'), true)
MySociety::Config.load_default
# Settings in config/environments/* take precedence over those specified here
# Skip frameworks you're not going to use (only works if using vendor/rails)
# config.frameworks -= [ :action_web_service, :action_mailer ]
# Only load the plugins named here, by default all plugins in vendor/plugins are loaded
# config.plugins = %W( exception_notification ssl_requirement )
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# TEMP: uncomment this to turn on logging in production environments
# config.log_level = :debug
#
# Specify gems that this application depends on and have them installed with rake gems:install
config.gem "rack", :version => '1.1.0'
config.gem 'rspec-rails', :lib => false, :version => '1.3.3'
config.gem "recaptcha", :lib => "recaptcha/rails"
config.gem 'will_paginate', :version => '~> 2.3.11', :source => 'http://gemcutter.org'
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_wdtk_cookie_session',
:secret => MySociety::Config.get("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')
}
config.action_controller.session_store = :cookie_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
config.active_record.schema_format = :sql
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
# Make Active Record use UTC-base instead of local time
config.active_record.default_timezone = :utc
# See Rails::Configuration for more options
ENV['RECAPTCHA_PUBLIC_KEY'] = MySociety::Config::get("RECAPTCHA_PUBLIC_KEY", 'x');
ENV['RECAPTCHA_PRIVATE_KEY'] = MySociety::Config::get("RECAPTCHA_PRIVATE_KEY", 'x');
end
# Add new inflection rules using the following format
# (all these examples are active by default):
# Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register "application/x-mobile", :mobile
# The Rails cache is set up by the Interlock plugin to use memcached
# Domain for URLs (so can work for scripts, not just web pages)
ActionMailer::Base.default_url_options[:host] = MySociety::Config.get("DOMAIN", 'localhost:3000')
# So that javascript assets use full URL, so proxied admin URLs read javascript OK
if (MySociety::Config.get("DOMAIN", "") != "")
ActionController::Base.asset_host = Proc.new { |source, request|
if request.fullpath.match(/^\/admin\//)
MySociety::Config.get("ADMIN_PUBLIC_URL", "/")
else
MySociety::Config.get("DOMAIN", 'localhost:3000')
end
}
end
# Load monkey patches and other things from lib/
require 'tmail_extensions.rb'
require 'activesupport_cache_extensions.rb'
require 'public_body_categories.rb'
require 'timezone_fixes.rb'
require 'use_spans_for_errors.rb'
require 'make_html_4_compliant.rb'
require 'activerecord_errors_extensions.rb'
require 'willpaginate_hack.rb'
require 'sendmail_return_path.rb'
require 'tnef.rb'
|
Pod::Spec.new do |s|
s.name = 'LFImagePickerController'
s.version = '1.4.0.2'
s.summary = 'A clone of UIImagePickerController, support picking multiple photos、 video and edit photo'
s.homepage = 'https://github.com/lincf0912/LFImagePickerController'
s.license = 'MIT'
s.author = { 'lincf0912' => 'dayflyking@163.com' }
s.platform = :ios
s.ios.deployment_target = '7.0'
s.source = { :git => 'https://github.com/lincf0912/LFImagePickerController.git', :tag => s.version, :submodules => true }
s.requires_arc = true
s.default_subspec = 'Core'
s.subspec 'Core' do |ss|
ss.resources = 'LFImagePickerController/LFImagePickerController/class/*.bundle'
ss.source_files = 'LFImagePickerController/LFImagePickerController/class/*.{h,m}','LFImagePickerController/LFImagePickerController/class/**/*.{h,m}'
ss.public_header_files = 'LFImagePickerController/LFImagePickerController/class/*.h','LFImagePickerController/LFImagePickerController/class/manager/*.h','LFImagePickerController/LFImagePickerController/class/model/*.h','LFImagePickerController/LFImagePickerController/class/model/**/*.h','LFImagePickerController/LFImagePickerController/class/define/LFImagePickerPublicHeader.h'
ss.dependency 'LFImagePickerController/LFGifPlayer'
ss.dependency 'LFImagePickerController/LFToGIF'
end
# LFGifPlayer模块
s.subspec 'LFGifPlayer' do |ss|
ss.source_files = 'LFImagePickerController/LFImagePickerController/vendors/LFGifPlayer/*.{h,m}'
ss.public_header_files = 'LFImagePickerController/LFImagePickerController/vendors/LFGifPlayer/LFGifPlayerManager.h'
end
# LFToGIF模块
s.subspec 'LFToGIF' do |ss|
ss.source_files = 'LFImagePickerController/LFImagePickerController/vendors/LFToGIF/*.{h,m}'
ss.public_header_files = 'LFImagePickerController/LFImagePickerController/vendors/LFToGIF/LFToGIF.h'
end
# LFMediaEdit模块
s.subspec 'LFMediaEdit' do |ss|
ss.xcconfig = {
'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) LF_MEDIAEDIT=1'
}
ss.dependency 'LFImagePickerController/Core'
ss.dependency 'LFMediaEditingController'
end
end
-恢复首次访问权限时允许后自动加载数据功能
-预览界面适配iPhoneX
Pod::Spec.new do |s|
s.name = 'LFImagePickerController'
s.version = '1.4.1'
s.summary = 'A clone of UIImagePickerController, support picking multiple photos、 video and edit photo'
s.homepage = 'https://github.com/lincf0912/LFImagePickerController'
s.license = 'MIT'
s.author = { 'lincf0912' => 'dayflyking@163.com' }
s.platform = :ios
s.ios.deployment_target = '7.0'
s.source = { :git => 'https://github.com/lincf0912/LFImagePickerController.git', :tag => s.version, :submodules => true }
s.requires_arc = true
s.default_subspec = 'Core'
s.subspec 'Core' do |ss|
ss.resources = 'LFImagePickerController/LFImagePickerController/class/*.bundle'
ss.source_files = 'LFImagePickerController/LFImagePickerController/class/*.{h,m}','LFImagePickerController/LFImagePickerController/class/**/*.{h,m}'
ss.public_header_files = 'LFImagePickerController/LFImagePickerController/class/*.h','LFImagePickerController/LFImagePickerController/class/manager/*.h','LFImagePickerController/LFImagePickerController/class/model/*.h','LFImagePickerController/LFImagePickerController/class/model/**/*.h','LFImagePickerController/LFImagePickerController/class/define/LFImagePickerPublicHeader.h'
ss.dependency 'LFImagePickerController/LFGifPlayer'
ss.dependency 'LFImagePickerController/LFToGIF'
end
# LFGifPlayer模块
s.subspec 'LFGifPlayer' do |ss|
ss.source_files = 'LFImagePickerController/LFImagePickerController/vendors/LFGifPlayer/*.{h,m}'
ss.public_header_files = 'LFImagePickerController/LFImagePickerController/vendors/LFGifPlayer/LFGifPlayerManager.h'
end
# LFToGIF模块
s.subspec 'LFToGIF' do |ss|
ss.source_files = 'LFImagePickerController/LFImagePickerController/vendors/LFToGIF/*.{h,m}'
ss.public_header_files = 'LFImagePickerController/LFImagePickerController/vendors/LFToGIF/LFToGIF.h'
end
# LFMediaEdit模块
s.subspec 'LFMediaEdit' do |ss|
ss.xcconfig = {
'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) LF_MEDIAEDIT=1'
}
ss.dependency 'LFImagePickerController/Core'
ss.dependency 'LFMediaEditingController'
end
end
|
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.8' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
# DocumentCloud-specific configuration.
SECRETS = YAML.load_file("#{Rails.root}/config/secrets.yml")[RAILS_ENV]
DC_CONFIG = YAML.load_file("#{Rails.root}/config/document_cloud.yml")[RAILS_ENV]
# Settings in config/initializers take precedence over this.
Rails::Initializer.run do |config|
# Standard Library:
require 'digest/md5'
require 'tmpdir'
require 'fileutils'
# Gems:
config.gem 'json', :version => '>= 1.1.9'
config.gem 'calais', :version => '>= 0.0.8'
config.gem 'rest-client', :version => '>= 1.0.3', :lib => 'rest_client'
config.gem 'bcrypt-ruby', :version => '>= 2.1.2', :lib => 'bcrypt'
config.gem 'rubyzip', :version => '>= 0.9.1', :lib => 'zip/zip'
config.gem 'right_aws', :version => '>= 2.0.0'
config.gem 'pg', :version => '>= 0.9.0'
config.gem 'jammit', :version => '>= 0.5.0'
config.gem 'docsplit', :version => '>= 0.1.1'
config.gem 'sunspot_rails', :version => '>= 1.1.0', :lib => 'sunspot/rails'
config.gem 'rdiscount', :version => '>= 1.6.5'
config.gem 'fastercsv', :version => '>= 1.5.3'
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
config.frameworks -= [:active_resource]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
config.active_record.schema_format = :sql
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# 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}')]
# config.i18n.default_locale = :de
end
RightAws::RightAWSParser.xml_lib = 'libxml'
ActiveRecord::Base.include_root_in_json = false
ActiveSupport::JSON.backend = 'JSONGem'
require 'json'
require 'json/add/rails'
setting: RightAws::AWSErrorHandler.close_on_4xx_probability = 100
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.8' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
# DocumentCloud-specific configuration.
SECRETS = YAML.load_file("#{Rails.root}/config/secrets.yml")[RAILS_ENV]
DC_CONFIG = YAML.load_file("#{Rails.root}/config/document_cloud.yml")[RAILS_ENV]
# Settings in config/initializers take precedence over this.
Rails::Initializer.run do |config|
# Standard Library:
require 'digest/md5'
require 'tmpdir'
require 'fileutils'
# Gems:
config.gem 'json', :version => '>= 1.1.9'
config.gem 'calais', :version => '>= 0.0.8'
config.gem 'rest-client', :version => '>= 1.0.3', :lib => 'rest_client'
config.gem 'bcrypt-ruby', :version => '>= 2.1.2', :lib => 'bcrypt'
config.gem 'rubyzip', :version => '>= 0.9.1', :lib => 'zip/zip'
config.gem 'right_aws', :version => '>= 2.0.0'
config.gem 'pg', :version => '>= 0.9.0'
config.gem 'jammit', :version => '>= 0.5.0'
config.gem 'docsplit', :version => '>= 0.1.1'
config.gem 'sunspot_rails', :version => '>= 1.1.0', :lib => 'sunspot/rails'
config.gem 'rdiscount', :version => '>= 1.6.5'
config.gem 'fastercsv', :version => '>= 1.5.3'
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
config.frameworks -= [:active_resource]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
config.active_record.schema_format = :sql
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# 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}')]
# config.i18n.default_locale = :de
end
# Tell RightAWS to always reset the connection after failure.
RightAws::AWSErrorHandler.close_on_4xx_probability = 100
RightAws::RightAWSParser.xml_lib = 'libxml'
ActiveRecord::Base.include_root_in_json = false
ActiveSupport::JSON.backend = 'JSONGem'
require 'json'
require 'json/add/rails'
|
Pod::Spec.new do |s|
s.name = 'LFImagePickerController'
s.version = '1.6.3'
s.summary = 'A clone of UIImagePickerController, support picking multiple photos、 video and edit photo'
s.homepage = 'https://github.com/lincf0912/LFImagePickerController'
s.license = 'MIT'
s.author = { 'lincf0912' => 'dayflyking@163.com' }
s.platform = :ios
s.ios.deployment_target = '7.0'
s.source = { :git => 'https://github.com/lincf0912/LFImagePickerController.git', :tag => s.version, :submodules => true }
s.requires_arc = true
s.default_subspec = 'Core'
s.subspec 'Core' do |ss|
ss.resources = 'LFImagePickerController/LFImagePickerController/class/*.bundle'
ss.source_files = 'LFImagePickerController/LFImagePickerController/class/*.{h,m}','LFImagePickerController/LFImagePickerController/class/**/*.{h,m}'
ss.public_header_files = 'LFImagePickerController/LFImagePickerController/class/*.h','LFImagePickerController/LFImagePickerController/class/manager/*.h','LFImagePickerController/LFImagePickerController/class/model/*.h','LFImagePickerController/LFImagePickerController/class/model/**/*.h','LFImagePickerController/LFImagePickerController/class/define/LFImagePickerPublicHeader.h'
ss.dependency 'LFImagePickerController/LFGifPlayer'
ss.dependency 'LFImagePickerController/LFToGIF'
end
# LFGifPlayer模块
s.subspec 'LFGifPlayer' do |ss|
ss.source_files = 'LFImagePickerController/LFImagePickerController/vendors/LFGifPlayer/*.{h,m}'
ss.public_header_files = 'LFImagePickerController/LFImagePickerController/vendors/LFGifPlayer/LFGifPlayerManager.h'
end
# LFToGIF模块
s.subspec 'LFToGIF' do |ss|
ss.source_files = 'LFImagePickerController/LFImagePickerController/vendors/LFToGIF/*.{h,m}'
ss.public_header_files = 'LFImagePickerController/LFImagePickerController/vendors/LFToGIF/LFToGIF.h'
end
# LFMediaEdit模块
s.subspec 'LFMediaEdit' do |ss|
ss.xcconfig = {
'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) LF_MEDIAEDIT=1'
}
ss.dependency 'LFImagePickerController/Core'
ss.dependency 'LFMediaEditingController'
end
end
-优化不允许选择GIF时的图片大小与处理效率
-调整预览界面展示编辑后的图片会出现编辑前的图片一闪而过的情况
-修复不允许选择GIF的情况下,选取的图片仍然会变成GIF的问题
-修复部分GIF图片无法获取的问题
Pod::Spec.new do |s|
s.name = 'LFImagePickerController'
s.version = '1.6.4'
s.summary = 'A clone of UIImagePickerController, support picking multiple photos、 video and edit photo'
s.homepage = 'https://github.com/lincf0912/LFImagePickerController'
s.license = 'MIT'
s.author = { 'lincf0912' => 'dayflyking@163.com' }
s.platform = :ios
s.ios.deployment_target = '7.0'
s.source = { :git => 'https://github.com/lincf0912/LFImagePickerController.git', :tag => s.version, :submodules => true }
s.requires_arc = true
s.default_subspec = 'Core'
s.subspec 'Core' do |ss|
ss.resources = 'LFImagePickerController/LFImagePickerController/class/*.bundle'
ss.source_files = 'LFImagePickerController/LFImagePickerController/class/*.{h,m}','LFImagePickerController/LFImagePickerController/class/**/*.{h,m}'
ss.public_header_files = 'LFImagePickerController/LFImagePickerController/class/*.h','LFImagePickerController/LFImagePickerController/class/manager/*.h','LFImagePickerController/LFImagePickerController/class/model/*.h','LFImagePickerController/LFImagePickerController/class/model/**/*.h','LFImagePickerController/LFImagePickerController/class/define/LFImagePickerPublicHeader.h'
ss.dependency 'LFImagePickerController/LFGifPlayer'
ss.dependency 'LFImagePickerController/LFToGIF'
end
# LFGifPlayer模块
s.subspec 'LFGifPlayer' do |ss|
ss.source_files = 'LFImagePickerController/LFImagePickerController/vendors/LFGifPlayer/*.{h,m}'
ss.public_header_files = 'LFImagePickerController/LFImagePickerController/vendors/LFGifPlayer/LFGifPlayerManager.h'
end
# LFToGIF模块
s.subspec 'LFToGIF' do |ss|
ss.source_files = 'LFImagePickerController/LFImagePickerController/vendors/LFToGIF/*.{h,m}'
ss.public_header_files = 'LFImagePickerController/LFImagePickerController/vendors/LFToGIF/LFToGIF.h'
end
# LFMediaEdit模块
s.subspec 'LFMediaEdit' do |ss|
ss.xcconfig = {
'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) LF_MEDIAEDIT=1'
}
ss.dependency 'LFImagePickerController/Core'
ss.dependency 'LFMediaEditingController'
end
end
|
PROJECT_ROOT = File.join(File.dirname(__FILE__), '..', '..')
God.watch do |w|
w.name = "ddclient"
w.pid_file = '/var/run/ddclient.pid'
w.keepalive
w.start = 'ddclient -daemon=1'
w.behavior(:clean_pid_file)
end
God.watch do |w|
# Environment variables
w.env = {
'BURNING_BUSH_ROOT' => PROJECT_ROOT
}
w.env['BURNING_BUSH_LIB'] = w.env['BURNING_BUSH_ROOT'] + "/lib"
w.name = "burning-bush"
w.log = PROJECT_ROOT + "/exec/log.txt"
w.keepalive
w.start = "su -l pi -c #{PROJECT_ROOT}/burning_bush_daemon"
puts "logging to #{w.log}"
end
Remove logging
PROJECT_ROOT = File.join(File.dirname(__FILE__), '..', '..')
God.watch do |w|
w.name = "ddclient"
w.pid_file = '/var/run/ddclient.pid'
w.keepalive
w.start = 'ddclient -daemon=1'
w.behavior(:clean_pid_file)
end
God.watch do |w|
# Environment variables
w.env = {
'BURNING_BUSH_ROOT' => PROJECT_ROOT
}
w.env['BURNING_BUSH_LIB'] = w.env['BURNING_BUSH_ROOT'] + "/lib"
w.name = "burning-bush"
w.keepalive
w.start = "su -l pi -c #{PROJECT_ROOT}/burning_bush_daemon"
end
|
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
#RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
# Load heroku vars from local file
balder_env = File.join(RAILS_ROOT, 'config', 'balder.rb')
load(balder_env) if File.exists?(balder_env)
Rails::Initializer.run do |config|
config.gem "authlogic"
config.gem 'mime-types', :lib => 'mime/types'
config.gem "carrierwave"
#config.gem "mini_exiftool"
#config.gem "aws-s3", :lib => "aws/s3"
config.load_paths += %W( #{RAILS_ROOT}/app/middleware )
config.time_zone = 'Copenhagen'
config.i18n.default_locale = 'no-NB'
end
no need to set my locale for everyone else..
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
#RAILS_GEM_VERSION = '2.3.4' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
# Load heroku vars from local file
balder_env = File.join(RAILS_ROOT, 'config', 'balder.rb')
load(balder_env) if File.exists?(balder_env)
Rails::Initializer.run do |config|
config.gem "authlogic"
config.gem 'mime-types', :lib => 'mime/types'
config.gem "carrierwave"
#config.gem "mini_exiftool"
#config.gem "aws-s3", :lib => "aws/s3"
config.load_paths += %W( #{RAILS_ROOT}/app/middleware )
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.