diff --git a/.gitignore b/.gitignore index 4d98e16e9..b5a4be542 100644 --- a/.gitignore +++ b/.gitignore @@ -4,13 +4,9 @@ app/assets/images/custom/* # Configuration files -config/app_config.yml -config/app.yml -config/application.yml +config/diaspora.yml config/heroku.yml -config/script_server*.yml -config/fb_config.yml -config/oauth_keys.yml +config/script_server.yml config/initializers/secret_token.rb config/redis.conf config/deploy_config.yml diff --git a/Changelog.md b/Changelog.md new file mode 100644 index 000000000..3ff77fb8c --- /dev/null +++ b/Changelog.md @@ -0,0 +1,24 @@ +# 0.0.1.0pre + +## New configuration system! + +Copy over config/diaspora.yml.example to config/diaspora.yml and migrate your settings! An updated Heroku guide including basic hints on howto migrate is [here](https://github.com/diaspora/diaspora/wiki/Installing-on-heroku). + +The new configuration system allows all possible settings to be overriden by environment variables. This makes it possible to deploy heroku without checking any credentials into git. Read the top of `config/diaspora.yml.example` for an explanation on how to convert the setting names to environment variables. + +### Environment variable changes: + +#### deprectated + +* REDISTOGO_URL in favour of REDIS_URL or ENVIRONMENT_REDIS + +#### removed + +* application_yml - Obsolete, all settings are settable via environment variables now + +#### renamed + +* SINGLE_PROCESS_MODE -> ENVIRONMENT_SINGLE_PROCESS_MODE +* SINGLE_PROCESS -> ENVIRONMENT_SINGLE_PROCESS_MODE +* NO_SSL -> ENVIRONMENT_REQUIRE_SSL +* ASSET_HOST -> ENVIRONMENT_ASSETS_HOST \ No newline at end of file diff --git a/Gemfile b/Gemfile index 1bb479926..08ca2e8b1 100644 --- a/Gemfile +++ b/Gemfile @@ -53,7 +53,6 @@ group :heroku do gem 'unicorn', '4.3.1', :require => false end -gem 'settingslogic', :git => 'https://github.com/binarylogic/settingslogic.git' # database gem "activerecord-import", "0.2.11" diff --git a/Gemfile.lock b/Gemfile.lock index b70604c63..081e2a5cf 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -7,12 +7,6 @@ GIT activesupport (>= 2.3.0) nokogiri (>= 1.3.3) -GIT - remote: https://github.com/binarylogic/settingslogic.git - revision: 4884d455bf18d92723cb8190cfd2dbf87f3aafd5 - specs: - settingslogic (2.0.8) - GIT remote: https://github.com/plataformatec/markerb.git revision: 93b1e8bea9b8fa89ef930f78ba562f596c022198 @@ -519,7 +513,6 @@ DEPENDENCIES ruby-oembed (= 0.8.7) sass-rails (= 3.2.5) selenium-webdriver (= 2.25.0) - settingslogic! spork (= 1.0.0rc3) thin (= 1.4.1) timecop (= 0.5.1) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 9ec778228..b6aaf97f8 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -8,7 +8,7 @@ class ApplicationController < ActionController::Base before_filter :ensure_http_referer_is_set before_filter :set_locale - before_filter :set_git_header if (AppConfig[:git_update] && AppConfig[:git_revision]) + before_filter :set_diaspora_header before_filter :set_grammatical_gender before_filter :mobile_switch @@ -61,9 +61,13 @@ class ApplicationController < ActionController::Base params[:page] = params[:page] ? params[:page].to_i : 1 end - def set_git_header - headers['X-Git-Update'] = AppConfig[:git_update] if AppConfig[:git_update].present? - headers['X-Git-Revision'] = AppConfig[:git_revision] if AppConfig[:git_revision].present? + def set_diaspora_header + headers['X-Diaspora-Version'] = AppConfig.version_string + + if AppConfig.git_available? + headers['X-Git-Update'] = AppConfig.git_update if AppConfig.git_update.present? + headers['X-Git-Revision'] = AppConfig.git_revision if AppConfig.git_revision.present? + end end def set_locale diff --git a/app/controllers/invitations_controller.rb b/app/controllers/invitations_controller.rb index 2ea2e4c05..a73d7c5b1 100644 --- a/app/controllers/invitations_controller.rb +++ b/app/controllers/invitations_controller.rb @@ -55,7 +55,7 @@ class InvitationsController < ApplicationController end def check_if_invites_open - unless AppConfig[:open_invitations] + unless AppConfig.settings.invitations.open? flash[:error] = I18n.t 'invitations.create.no_more' redirect_to :back diff --git a/app/controllers/publics_controller.rb b/app/controllers/publics_controller.rb index e1d22fd31..4ce1e044f 100644 --- a/app/controllers/publics_controller.rb +++ b/app/controllers/publics_controller.rb @@ -9,12 +9,6 @@ class PublicsController < ApplicationController require Rails.root.join('lib', 'postzord', 'receiver', 'private') include Diaspora::Parser - # We use newrelic_ignore to prevent artifical RPM bloat; however, - # I am commenting this line out for the time being to debug some apparent - # issues on Heroku. - # - # newrelic_ignore if EnvironmentConfiguration.using_new_relic? - skip_before_filter :set_header_data skip_before_filter :set_grammatical_gender before_filter :check_for_xml, :only => [:receive, :receive_public] diff --git a/app/controllers/registrations_controller.rb b/app/controllers/registrations_controller.rb index 76cef3be5..da18aeaa7 100644 --- a/app/controllers/registrations_controller.rb +++ b/app/controllers/registrations_controller.rb @@ -31,7 +31,7 @@ class RegistrationsController < Devise::RegistrationsController private def check_valid_invite! - return true unless AppConfig[:registrations_closed] #this sucks + return true if AppConfig.settings.enable_registrations? #this sucks return true if invite && invite.can_be_used? flash[:error] = t('registrations.invalid_invite') redirect_to new_user_session_path @@ -39,7 +39,7 @@ class RegistrationsController < Devise::RegistrationsController def check_registrations_open_or_vaild_invite! return true if invite.present? - if AppConfig[:registrations_closed] + unless AppConfig.settings.enable_registrations? flash[:error] = t('registrations.closed') redirect_to new_user_session_path end diff --git a/app/helpers/analytics_helper.rb b/app/helpers/analytics_helper.rb index f49d3331f..1a17d3c9c 100644 --- a/app/helpers/analytics_helper.rb +++ b/app/helpers/analytics_helper.rb @@ -9,7 +9,7 @@ module AnalyticsHelper <<-JS.html_safe (function(d,c){var a,b,g,e;a=d.createElement('script');a.type='text/javascript';a.async=!0;a.src=('https:'===d.location.protocol?'https:':'http:')+'//api.mixpanel.com/site_media/js/api/mixpanel.2.js';b=d.getElementsByTagName('script')[0];b.parentNode.insertBefore(a,b);c._i=[];c.init=function(a,d,f){var b=c;'undefined'!==typeof f?b=c[f]=[]:f='mixpanel';g='disable track track_pageview track_links track_forms register register_once unregister identify name_tag set_config'.split(' '); for(e=0;e AppConfig[:pod_uri].scheme, :host => AppConfig[:pod_uri].authority) + opts.merge!(:protocol => AppConfig.pod_uri.scheme, :host => AppConfig.pod_uri.authority) absolute = opts.delete(:absolute) if person.local? diff --git a/app/helpers/posts_helper.rb b/app/helpers/posts_helper.rb index bda797c27..efd741df3 100644 --- a/app/helpers/posts_helper.rb +++ b/app/helpers/posts_helper.rb @@ -20,7 +20,7 @@ module PostsHelper def post_iframe_url(post_id, opts={}) opts[:width] ||= 516 opts[:height] ||= 315 - host = AppConfig[:pod_uri].site + host = AppConfig.pod_uri.site "".html_safe end end diff --git a/app/helpers/sessions_helper.rb b/app/helpers/sessions_helper.rb index ecef50181..2c5056e16 100644 --- a/app/helpers/sessions_helper.rb +++ b/app/helpers/sessions_helper.rb @@ -9,7 +9,7 @@ module SessionsHelper end def display_registration_link? - !AppConfig[:registrations_closed] && devise_mapping.registerable? && controller_name != 'registrations' + !AppConfig.settings.enable_registrations? && devise_mapping.registerable? && controller_name != 'registrations' end def display_password_reset_link? diff --git a/app/mailers/diaspora_devise_mailer.rb b/app/mailers/diaspora_devise_mailer.rb index c74f86ab2..9a18ffb38 100644 --- a/app/mailers/diaspora_devise_mailer.rb +++ b/app/mailers/diaspora_devise_mailer.rb @@ -1,5 +1,5 @@ class DiasporaDeviseMailer < Devise::Mailer - default :from => AppConfig[:smtp_sender_address] + default :from => AppConfig.mail.sender_address def self.mailer_name "devise/mailer" diff --git a/app/mailers/notification_mailers/also_commented.rb b/app/mailers/notification_mailers/also_commented.rb index 73edd6e51..786a16e8a 100644 --- a/app/mailers/notification_mailers/also_commented.rb +++ b/app/mailers/notification_mailers/also_commented.rb @@ -9,7 +9,7 @@ module NotificationMailers @comment = Comment.find_by_id(comment_id) if mail? - @headers[:from] = "\"#{@comment.author_name} (Diaspora*)\" <#{AppConfig[:smtp_sender_address]}>" + @headers[:from] = "\"#{@comment.author_name} (Diaspora*)\" <#{AppConfig.mail.sender_address}>" @headers[:subject] = truncate(@comment.comment_email_subject, :length => TRUNCATION_LEN) @headers[:subject] = "Re: #{@headers[:subject]}" end diff --git a/app/mailers/notification_mailers/base.rb b/app/mailers/notification_mailers/base.rb index 1f72787b8..980f70e51 100644 --- a/app/mailers/notification_mailers/base.rb +++ b/app/mailers/notification_mailers/base.rb @@ -33,12 +33,12 @@ module NotificationMailers private def default_headers headers = { - :from => AppConfig[:smtp_sender_address], - :host => "#{AppConfig[:pod_uri]}", + :from => AppConfig.mail.sender_address.get, + :host => "#{AppConfig.pod_uri.host}", :to => name_and_address(@recipient.name, @recipient.email) } - headers[:from] = "\"#{@sender.name} (Diaspora*)\" <#{AppConfig[:smtp_sender_address]}>" if @sender.present? + headers[:from] = "\"#{@sender.name} (Diaspora*)\" <#{AppConfig.mail.sender_address}>" if @sender.present? headers end diff --git a/app/mailers/notification_mailers/comment_on_post.rb b/app/mailers/notification_mailers/comment_on_post.rb index 0b9ad130f..d7735a887 100644 --- a/app/mailers/notification_mailers/comment_on_post.rb +++ b/app/mailers/notification_mailers/comment_on_post.rb @@ -7,7 +7,7 @@ module NotificationMailers def set_headers(comment_id) @comment = Comment.find(comment_id) - @headers[:from] = "\"#{@comment.author_name} (Diaspora*)\" <#{AppConfig[:smtp_sender_address]}>" + @headers[:from] = "\"#{@comment.author_name} (Diaspora*)\" <#{AppConfig.mail.sender_address}>" @headers[:subject] = truncate(@comment.comment_email_subject, :length => TRUNCATION_LEN) @headers[:subject] = "Re: #{@headers[:subject]}" end diff --git a/app/mailers/notification_mailers/private_message.rb b/app/mailers/notification_mailers/private_message.rb index 74b832b20..e39632b7d 100644 --- a/app/mailers/notification_mailers/private_message.rb +++ b/app/mailers/notification_mailers/private_message.rb @@ -7,7 +7,7 @@ module NotificationMailers @conversation = @message.conversation @participants = @conversation.participants - @headers[:from] = "\"#{@message.author_name} (Diaspora*)\" <#{AppConfig[:smtp_sender_address]}>" + @headers[:from] = "\"#{@message.author_name} (Diaspora*)\" <#{AppConfig.mail.sender_address}>" @headers[:subject] = @conversation.subject.strip @headers[:subject] = "Re: #{@headers[:subject]}" if @conversation.messages.size > 1 end diff --git a/app/mailers/notifier.rb b/app/mailers/notifier.rb index b4c1d8f9b..c922f2744 100644 --- a/app/mailers/notifier.rb +++ b/app/mailers/notifier.rb @@ -24,8 +24,8 @@ class Notifier < ActionMailer::Base end default_opts = {:to => @receiver.email, - :from => AppConfig[:smtp_sender_address], - :subject => I18n.t('notifier.single_admin.subject'), :host => AppConfig[:pod_uri].host} + :from => AppConfig.mail.sender_address, + :subject => I18n.t('notifier.single_admin.subject'), :host => AppConfig.pod_uri.host} default_opts.merge!(opts) @@ -42,9 +42,9 @@ class Notifier < ActionMailer::Base @locale = locale @invitation_code = invitation_code - mail_opts = {:to => email, :from => AppConfig[:smtp_sender_address], - :subject => I18n.t('notifier.invited_you', :name => @inviter.name), - :host => AppConfig[:pod_uri].host} + mail_opts = {:to => email, :from => AppConfig.mail.sender_address, + :subject => I18n.t('notifier.invited_you', :name => @inviter.name), + :host => AppConfig.pod_uri.host} I18n.with_locale(locale) do mail(mail_opts) do |format| diff --git a/app/models/app_config.rb b/app/models/app_config.rb deleted file mode 100644 index 927ec2abe..000000000 --- a/app/models/app_config.rb +++ /dev/null @@ -1,194 +0,0 @@ -# Copyright (c) 2010-2011, Diaspora Inc. This file is -# licensed under the Affero General Public License version 3 or later. See -# the COPYRIGHT file. - -require 'uri' -require Rails.root.join('lib', 'environment_configuration') - -class AppConfig < Settingslogic - def self.source_file_name - if ENV['application_yml'].present? - puts "using remote application.yml" - return ENV['application_yml'] - end - config_file = Rails.root.join("config", "application.yml") - if !File.exists?(config_file) && (Rails.env == 'test' || Rails.env.include?("integration") || EnvironmentConfiguration.heroku?) - config_file = Rails.root.join("config", "application.yml.example") - end - config_file - end - source source_file_name - namespace Rails.env - - def self.load! - unless EnvironmentConfiguration.heroku? - if no_config_file? && !have_old_config_file? - $stderr.puts <<-HELP -******** You haven't set up your Diaspora settings file. ********** -Please do the following: -1. Copy config/application.yml.example to config/application.yml. -2. Have a look at the settings in that file. It has sensible defaults for development, which (we hope) -work without modification. However, it's always good to know what's available to change later. -3. Restart Diaspora! -******** Thanks for being an alpha tester! ********** - HELP - Process.exit(1) - end - - if ((no_config_file? && have_old_config_file?) || config_file_is_old_style?) - $stderr.puts <<-HELP -******** The Diaspora configuration file format has changed. ********** -Please do the following: -1. Copy config/application.yml.example to config/application.yml. -2. Make any changes in config/application.yml that you previously made in config/app.yml or config/app_config.yml. -3. Delete config/app.yml and config/app_config.yml. Don't worry if they don't exist, though. -4. Restart Diaspora! -******** Thanks for being an alpha tester! ********** - HELP - Process.exit(1) - end - end - - begin - super - rescue TypeError - puts "Couldn't find section ''#{self.namespace}' in config/application.yml." - puts "Double check it's there and that you haven't set RAILS_ENV to something weired (check it for typos)" - Process.exit(1) - end - - if !EnvironmentConfiguration.heroku? && no_cert_file_in_prod? - $stderr.puts <<-HELP -******** Diaspora does not know where your SSL-CA-Certificates file is. ********** - Please add the root certificate bundle (this is operating system specific) to application.yml. Defaults: - CentOS: '/etc/pki/tls/certs/ca-bundle.crt' - Debian: '/etc/ssl/certs/ca-certificates.crt' - - Example: - ca_file: '/etc/ssl/certs/ca-certificates.crt' -******** Thanks for being secure! ********** -HELP - Process.exit(1) - end - end - - def self.setup! - normalize_pod_url - normalize_admins - normalize_pod_services - deprecate_hoptoad_api_key - self[:to_ary] = [] - end - - def self.configured_services - self['configured_services'] || [] - end - - def self.config_file_is_old_style? - !(File.read(@source) =~ /^defaults: &defaults/) - end - - def self.no_config_file? - !File.exists?(@source) - end - - def self.no_cert_file_in_prod? - (Rails.env == "production") && (self[:ca_file].blank? || !File.exists?(self[:ca_file])) - end - - def self.have_old_config_file? - File.exists?(Rails.root.join("config", "app.yml")) || (File.exists?(Rails.root.join("config", "app_config.yml"))) - end - - def self.new_relic_app_name - self[:new_relic_app_name] || self[:pod_uri].host - end - - def self.normalize_pod_url - unless self[:pod_url] =~ /^(https?:\/\/)/ # starts with http:// or https:// - self[:pod_url] = "http://#{self[:pod_url]}" - end - unless self[:pod_url] =~ /\/$/ # ends with slash - self[:pod_url] = "#{self[:pod_url]}/" - end - end - - def self.bare_pod_uri - self[:pod_uri].authority.gsub('www.', '') - end - - def self.normalize_admins - self[:admins] ||= [] - self[:admins].collect! { |username| username.downcase } - end - - def self.normalize_pod_services - self['configured_services'] = [] - if defined?(SERVICES) - SERVICES.keys.each do |service| - unless SERVICES[service].keys.any?{|service_key| SERVICES[service][service_key].blank?} - self['configured_services'] << service - end - end - end - end - - def deprecate_hoptoad_api_key - if self[:hoptoad_api_key].present? - $stderr.puts "WARNING: Please change hoptoad_api_key to airbrake_api_key in your application.yml" - self[:airbrake_api_key] = self[:hoptoad_api_key] - end - end - - load! - - def self.[] (key) - return self.pod_uri if key == :pod_uri - super - end - - def self.[]= (key, value) - super - if key.to_sym == :pod_url - @@pod_uri = nil - normalize_pod_url - end - end - - cattr_accessor :pod_uri - - def self.pod_uri - if @@pod_uri.nil? - begin - @@pod_uri = Addressable::URI.parse(self[:pod_url]) - rescue - puts "WARNING: pod url " + self[:pod_url] + " is not a legal URI" - end - end - return @@pod_uri - end - - def self.single_process_mode? - (ENV['SINGLE_PROCESS'] == "true" || ENV['SINGLE_PROCESS_MODE'] == "true" || self[:single_process_mode]) ? true : false - end - - def self.get_redis_instance - if ENV["REDISTOGO_URL"].present? - puts "WARNING: using the REDISTOGO_URL environment variable is deprecated, please use REDIS_URL now." - ENV['REDIS_URL'] = ENV["REDISTOGO_URL"] - end - - redis_options = {} - - if ENV['REDIS_URL'].present? - redis_options = { :url => ENV['REDIS_URL'] } - elsif ENV['RAILS_ENV']== 'integration2' - redis_options = { :host => 'localhost', :port => 6380 } - elsif self[:redis_url].present? - puts "WARNING: You're redis_url doesn't start with redis://" unless self[:redis_url].start_with?("redis://") - redis_options = { :url => self[:redis_url] } - end - - Redis.new(redis_options.merge(:thread_safe => true)) - end -end diff --git a/app/models/invitation_code.rb b/app/models/invitation_code.rb index 3a340c4b3..35fa80d49 100644 --- a/app/models/invitation_code.rb +++ b/app/models/invitation_code.rb @@ -30,14 +30,14 @@ class InvitationCode < ActiveRecord::Base end def self.default_inviter_or(user) - if AppConfig[:admin_account].present? - inviter = User.find_by_username(AppConfig[:admin_account]) + if AppConfig.admins.account.present? + inviter = User.find_by_username(AppConfig.admins.account.get) end inviter ||= user inviter end def set_default_invite_count - self.count = AppConfig[:invite_count] || 25 + self.count = AppConfig['settings.invitations.count'] || 25 end end diff --git a/app/models/jobs/publish_to_hub.rb b/app/models/jobs/publish_to_hub.rb index 1899c6b9d..80858984a 100644 --- a/app/models/jobs/publish_to_hub.rb +++ b/app/models/jobs/publish_to_hub.rb @@ -9,7 +9,7 @@ module Jobs def self.perform(sender_public_url) require Rails.root.join('lib', 'pubsubhubbub') atom_url = sender_public_url + '.atom' - Pubsubhubbub.new(AppConfig[:pubsub_server]).publish(atom_url) + Pubsubhubbub.new(AppConfig.environment.pubsub_server.get).publish(atom_url) end end end diff --git a/app/models/photo.rb b/app/models/photo.rb index 4d49c43af..5e80ea1ba 100644 --- a/app/models/photo.rb +++ b/app/models/photo.rb @@ -99,8 +99,8 @@ class Photo < ActiveRecord::Base def update_remote_path unless self.unprocessed_image.url.match(/^https?:\/\//) - pod_url = AppConfig[:pod_url].dup - pod_url.chop! if AppConfig[:pod_url][-1,1] == '/' + pod_url = AppConfig.environment.url.get.dup + pod_url.chop! if pod_url[-1,1] == '/' remote_path = "#{pod_url}#{self.unprocessed_image.url}" else remote_path = self.unprocessed_image.url diff --git a/app/models/profile.rb b/app/models/profile.rb index bf41aa31b..331dde95b 100644 --- a/app/models/profile.rb +++ b/app/models/profile.rb @@ -185,8 +185,8 @@ class Profile < ActiveRecord::Base end def absolutify_local_url url - pod_url = AppConfig[:pod_url].dup - pod_url.chop! if AppConfig[:pod_url][-1,1] == '/' + pod_url = AppConfig.environment.url.get + pod_url.chop! if pod_url[-1,1] == '/' "#{pod_url}#{url}" end end diff --git a/app/models/role.rb b/app/models/role.rb index 5fc0782f8..965044cf4 100644 --- a/app/models/role.rb +++ b/app/models/role.rb @@ -13,20 +13,4 @@ class Role < ActiveRecord::Base def self.add_spotlight(person) find_or_create_by_person_id_and_name(person.id, 'spotlight') end - - def self.load_admins - admins = AppConfig[:admins] || [] - admins.each do |username| - u = User.find_by_username(username) - find_or_create_by_person_id_and_name(u.person.id, 'admin') - end - end - - def self.load_spotlight - spotlighters = AppConfig[:community_spotlight] || [] - spotlighters.each do |diaspora_handle| - person = Person.find_by_diaspora_handle(diaspora_handle) - find_or_create_by_person_id_and_name(person.id, 'spotlight') - end - end end diff --git a/app/models/service.rb b/app/models/service.rb index 4720b1141..f44d5df13 100644 --- a/app/models/service.rb +++ b/app/models/service.rb @@ -14,7 +14,7 @@ class Service < ActiveRecord::Base def public_message(post, length, url = "") Rails.logger.info("Posting out to #{self.class}") - url = Rails.application.routes.url_helpers.short_post_url(post, :protocol => AppConfig[:pod_uri].scheme, :host => AppConfig[:pod_uri].authority) + url = Rails.application.routes.url_helpers.short_post_url(post, :protocol => AppConfig.pod_uri.scheme, :host => AppConfig.pod_uri.authority) space_for_url = 21 + 1 truncated = truncate(post.text(:plain_text => true), :length => (length - space_for_url)) truncated = "#{truncated} #{url}" diff --git a/app/models/services/facebook.rb b/app/models/services/facebook.rb index 4d8121d32..1e23bf61e 100644 --- a/app/models/services/facebook.rb +++ b/app/models/services/facebook.rb @@ -23,7 +23,7 @@ class Services::Facebook < Service end def create_open_graph_params(post) - {:post => "#{AppConfig[:pod_url]}#{short_post_path(post)}", :access_token => self.access_token} + {:post => "#{AppConfig.environment.url}#{short_post_path(post)}", :access_token => self.access_token} end def create_post_params(post) @@ -38,4 +38,4 @@ class Services::Facebook < Service def profile_photo_url "https://graph.facebook.com/#{self.uid}/picture?type=large&access_token=#{URI.escape(self.access_token)}" end -end \ No newline at end of file +end diff --git a/app/models/services/tumblr.rb b/app/models/services/tumblr.rb index 010ac96f3..ab964b6ea 100644 --- a/app/models/services/tumblr.rb +++ b/app/models/services/tumblr.rb @@ -9,11 +9,11 @@ class Services::Tumblr < Service end def consumer_key - SERVICES['tumblr']['consumer_key'] + AppConfig.services.tumblr.key end def consumer_secret - SERVICES['tumblr']['consumer_secret'] + AppConfig.services.tumblr.secret end def post(post, url='') diff --git a/app/models/services/twitter.rb b/app/models/services/twitter.rb index c3b409697..a4730b6e8 100644 --- a/app/models/services/twitter.rb +++ b/app/models/services/twitter.rb @@ -35,8 +35,8 @@ class Services::Twitter < Service private def configure_twitter - twitter_key = SERVICES['twitter']['consumer_key'] - twitter_consumer_secret = SERVICES['twitter']['consumer_secret'] + twitter_key = AppConfig.services.twitter.key + twitter_consumer_secret = AppConfig.services.twitter.secret if twitter_key.blank? || twitter_consumer_secret.blank? Rails.logger.info "you have a blank twitter key or secret.... you should look into that" diff --git a/app/models/user.rb b/app/models/user.rb index 6226c968a..7677245f6 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -395,7 +395,7 @@ class User < ActiveRecord::Base end def set_person(person) - person.url = AppConfig[:pod_url] + person.url = AppConfig.environment.url person.diaspora_handle = "#{self.username}#{User.diaspora_id_host}" self.person = person end @@ -410,7 +410,7 @@ class User < ActiveRecord::Base self.aspects.create(:name => I18n.t('aspects.seed.work')) aq = self.aspects.create(:name => I18n.t('aspects.seed.acquaintances')) - unless AppConfig[:no_follow_diasporahq] + unless AppConfig.settings.follow_diasporahq default_account = Webfinger.new('diasporahq@joindiaspora.com').fetch self.share_with(default_account, aq) if default_account end diff --git a/app/presenters/o_embed_presenter.rb b/app/presenters/o_embed_presenter.rb index d4c2500b9..73e1cbb35 100644 --- a/app/presenters/o_embed_presenter.rb +++ b/app/presenters/o_embed_presenter.rb @@ -15,7 +15,7 @@ class OEmbedPresenter def as_json(opts={}) { :provider_name => "Diaspora", - :provider_hurl => AppConfig[:pod_url], + :provider_url => AppConfig.environment.url, :type => 'rich', :version => '1.0', :title => post_title, @@ -40,7 +40,7 @@ class OEmbedPresenter end def post_author_url - Rails.application.routes.url_helpers.person_url(@post.author, :host => AppConfig[:pod_uri].host) + Rails.application.routes.url_helpers.person_url(@post.author, :host => AppConfig.pod_uri.host) end def iframe_html diff --git a/app/views/admins/_admin_bar.haml b/app/views/admins/_admin_bar.haml index 70ab909f0..0f2577dc7 100644 --- a/app/views/admins/_admin_bar.haml +++ b/app/views/admins/_admin_bar.haml @@ -6,6 +6,6 @@ %li= link_to t('.weekly_user_stats'), weekly_user_stats_path %li= link_to t('.pod_stats'), pod_stats_path %li= link_to t('.correlations'), correlations_path - - if AppConfig[:mount_resque_web] + - if AppConfig.admins.inline_resque_web? %li= link_to t('.resque_overview'), resque_web_path diff --git a/app/views/contacts/spotlight.haml b/app/views/contacts/spotlight.haml index 3c5eb9d20..da61f96e4 100644 --- a/app/views/contacts/spotlight.haml +++ b/app/views/contacts/spotlight.haml @@ -16,9 +16,9 @@ .span-18.last{:style => "position:relative;"} - - if AppConfig[:spotlight_suggest_email].present? + - if AppConfig.settings.community_spotlight.suggest_email.present? .right - = link_to "Suggest a member", "mailto:#{AppConfig[:spotlight_suggest_email]}", :class => "button" + = link_to "Suggest a member", "mailto:#{AppConfig.settings.community_spotlight.suggest_email}", :class => "button" %h3 = t('contacts.spotlight.community_spotlight') diff --git a/app/views/devise/shared/_links.haml b/app/views/devise/shared/_links.haml index 101d43567..4c37c1ed5 100644 --- a/app/views/devise/shared/_links.haml +++ b/app/views/devise/shared/_links.haml @@ -1,7 +1,7 @@ - if controller_name != 'sessions' = link_to t('.sign_in'), new_session_path(resource_name) %br/ -- if !AppConfig[:registrations_closed] && devise_mapping.registerable? && controller_name != 'registrations' +- if AppConfig.settings.enable_registrations? && devise_mapping.registerable? && controller_name != 'registrations' = link_to t('.sign_up'), new_registration_path(resource_name) %br/ - else diff --git a/app/views/layouts/notifier.html.erb b/app/views/layouts/notifier.html.erb index 816ecb34b..a55c90bd3 100644 --- a/app/views/layouts/notifier.html.erb +++ b/app/views/layouts/notifier.html.erb @@ -28,7 +28,7 @@
- DIASPORA* + DIASPORA*
diff --git a/app/views/publics/host_meta.erb b/app/views/publics/host_meta.erb index a37801b67..0fcde3b96 100644 --- a/app/views/publics/host_meta.erb +++ b/app/views/publics/host_meta.erb @@ -5,6 +5,6 @@ + template='<%= AppConfig.environment.url %>webfinger?q={uri}' /> diff --git a/app/views/sessions/new.html.erb b/app/views/sessions/new.html.erb index 0738df8fb..a31d736b7 100644 --- a/app/views/sessions/new.html.erb +++ b/app/views/sessions/new.html.erb @@ -1,10 +1,10 @@ <% content_for :page_title do %> - <%= "#{AppConfig[:pod_name]} / #{t('devise.sessions.new.sign_in')}" %> + <%= "#{AppConfig.settings.pod_name} / #{t('devise.sessions.new.sign_in')}" %> <% end %>

- <%= AppConfig[:pod_name] %> + <%= AppConfig.settings.pod_name %>

<%= form_for(resource, :as => resource_name, :url => session_path(resource_name), :html => {:class => "form-horizontal block-form"}, :autocomplete => 'off') do |f| %> diff --git a/app/views/shared/_contact_sidebar.html.haml b/app/views/shared/_contact_sidebar.html.haml index 9e024a774..85106b36b 100644 --- a/app/views/shared/_contact_sidebar.html.haml +++ b/app/views/shared/_contact_sidebar.html.haml @@ -8,6 +8,6 @@ %hr %ul.left_nav - - if AppConfig[:community_spotlight] + - if AppConfig.settings.community_spotlight.enable? %li{:class => ("active" if @spotlight)} = link_to t('contacts.spotlight.community_spotlight'), community_spotlight_path, :class => "element_selector" diff --git a/app/views/shared/_donatepod.html.haml b/app/views/shared/_donatepod.html.haml index 38a04b6a6..1281ff602 100644 --- a/app/views/shared/_donatepod.html.haml +++ b/app/views/shared/_donatepod.html.haml @@ -1,6 +1,6 @@ %form{:action => "https://www.paypal.com/cgi-bin/webscr", :method => "post"} %input{:name => "cmd", :type => "hidden", :value => "_s-xclick"} - %input{:name => "hosted_button_id", :type => "hidden", :value => AppConfig[:paypal_hosted_button_id]} + %input{:name => "hosted_button_id", :type => "hidden", :value => AppConfig.settings.paypal_hosted_button_id} %input{:name => "on0", :type => "hidden", :value => "Type"} %input{:name => "modify", :type => "hidden", :value => "2"} %select{:name => "os0"} diff --git a/app/views/shared/_right_sections.html.haml b/app/views/shared/_right_sections.html.haml index d0a0cd5b0..6a0861c48 100644 --- a/app/views/shared/_right_sections.html.haml +++ b/app/views/shared/_right_sections.html.haml @@ -3,7 +3,7 @@ -# the COPYRIGHT file. -- if AppConfig[:open_invitations] +- if AppConfig.settings.invitations.open? .section .title = image_tag('icons/plus.png') @@ -73,8 +73,8 @@ %h5 = t('aspects.index.donate') .content - - if AppConfig[:paypal_hosted_button_id].present? - = t('aspects.index.keep_pod_running', :pod => URI.parse(AppConfig[:pod_url]).host) + - if AppConfig.settings.paypal_hosted_button_id.present? + = t('aspects.index.keep_pod_running', :pod => URI.parse(AppConfig.environment.url).host) %br = render 'shared/donatepod' - else diff --git a/app/views/users/public.atom.builder b/app/views/users/public.atom.builder index b9c773b67..b29ea1140 100644 --- a/app/views/users/public.atom.builder +++ b/app/views/users/public.atom.builder @@ -8,14 +8,14 @@ atom_feed({'xmlns:thr' => 'http://purl.org/syndication/thread/1.0', :id => "#{@user.public_url}.atom", :root_url => "#{@user.public_url}"}) do |feed| - feed.tag! :generator, 'Diaspora', :uri => "#{AppConfig[:pod_url]}" + feed.tag! :generator, 'Diaspora', :uri => "#{AppConfig.environment.url}" feed.title "#{@user.name}'s Public Feed" feed.subtitle "Updates from #{@user.name} on Diaspora" feed.logo "#{@user.image_url(:thumb_small)}" feed.updated @posts[0].created_at if @posts.length > 0 feed.tag! :link, :rel => 'avatar', :type => 'image/jpeg', 'media:width' => '100', 'media:height' => '100', :href => "#{@user.image_url}" - feed.tag! :link, :href => "#{AppConfig[:pubsub_server]}", :rel => 'hub' + feed.tag! :link, :href => "#{AppConfig.environment.pubsub_server}", :rel => 'hub' feed.author do |author| author.name @user.name diff --git a/config/application.yml.example b/config/application.yml.example deleted file mode 100644 index 6c1c8f47b..000000000 --- a/config/application.yml.example +++ /dev/null @@ -1,280 +0,0 @@ -# Copyright (c) 2010-2011, Diaspora Inc. This file is -# licensed under the Affero General Public License version 3 or later. See -# the COPYRIGHT file. - -defaults: &defaults - - ###################################################### - # Environment Configuration - ###################################################### - - ## Set the hostname of the machine you're running Diaspora on, as seen - ## from the internet. This should be the URL you want to use to - ## access the pod. So if you plan to reverse proxy it, it should be - ## the URL the proxy listens on. - ## DO NOT CHNANGE THIS AFTER INITIAL SETUP - ## UNLESS YOU KNOW WHAT YOU'RE DOING! - ## However changing http to https is okay and has no consquences. - ## If you do change it you have to start over as it's hardcoded into - ## the database. - pod_url: "http://localhost:3000/" - - ## Setting the bundle of certificate authorities (CA) certificates. - ## This is operating system specific. - ## Examples, uncomment one or add your own: - ca_file: '/etc/pki/tls/certs/ca-bundle.crt' - - ## Redis URL for a remote redis. - ## Don't forget to restrict IP access! - ## Leave it empty for the default ('redis://localhost:6379/0') - ## You can specify a username and password in it, for example - ## redis://user:password@remote_host:6379/0 - ## You can also specify a unix socket URL like unix://tmp/redis.sock - redis_url: - - ## Serve static assets via the appserver. - ## This is highly not recommended for production use, - ## let your reverse proxy/webserver do it by serving the files - ## under public/ directly. - serve_static_assets: false - - ## Disable SSL requirement - #when set, your pod will not force you to use https in production - #NOTE: not all features of Diaspora work without SSL, and you may have trouble federating - # with other pods - circumvent_ssl_requirement: false - - # If set to true Diaspora will work with just the appserver, thin by default, - # running, however this makes it quite slow as all the time intensive jobs - # must be run inside the request cycle. Also the live updates from the Websocket - # will be disabled. - single_process_mode: true - - ## Use Amazon S3 instead of your local filesystem - ## to handle uploaded pictures. - # s3 config - if set, carrierwave will store your photos on s3. Otherwise they're on the filesystem. - #s3_key: 'key' - #s3_secret: 'secret' - #s3_bucket: 'my_photos' - s3_region: 'us-east-1' - - ## Related to S3 you can set a url to redirect all requests to uploaded - ## images to another host. If you for example set - ## https://images.example.org here, all requests made to - ## pictures under /uploads/images will be redirected to - ## https://images.example.org/uploads/images/... - image_redirect_url: '' - - ## Diaspora is only tested against this default pubsub server. - ## You probably don't want to change this. - pubsub_server: 'https://pubsubhubbub.appspot.com/' - - ## Include jQuery from Google's CDN - ## This potentially saves you some traffic and speeds up - ## load time since most clients already have this one cached - jquery_cdn: false - - ## Provide a key to enable tracking by Google Analytics - google_a_site: false - - ## Piwik Tracking - ## Provide a site ID and the host piwik is running on to enable - ## tracking through Piwik. - # piwik integration - if not set, no javascript included - piwik_id: - # the site url in raw format (e.g. pikwik.examplehost.com) - piwik_url: - - ## Chartbeat tracking - chartbeat_uid: - - ## Mixpanel event tracking - mixpanel_uid: - - - ###################################################### - # General Pod Settings - ###################################################### - - ## Name of your pod - pod_name: "Diaspora*" - - ## Set this to true to prevent people from signing up for your pod - ## without an invitation. Note that this needs to be true even for - ## the first registration (you). - registrations_closed: false - - ## Set this to true if you don't want your users to follow the - ## diasporahq@joindiaspora.com account on account creation. - ## The diasporahq account helps users start with some activity in - ## their stream and get news about Diaspora, but if you want - ## your server to contact joindiaspora.com, set this to false: - no_follow_diasporahq: false - - ## the 'admin' account for your pod... ie for jd.com, this is diasporahq. - ## (This is not about privileges, but e.g. to determine the sender for - ## emails sent from the admin panel. If you want to configure an actual - ## admin accout, use roles instead. See - ## https://github.com/diaspora/diaspora/wiki/FAQ-for-Pod-Maintainers - ## "What are roles and how do I use them?") - admin_account: '' - - ## Settings about invitations - - # Set this to true if you want users to invite as many people as they want - open_invitations: true - - #the default amount of invitiations for an invite link - invite_count: 25 - - ## Paypal donations - ## You can provide the ID of a hosted Paypal button here to kindly ask - ## your users for donations to run their pod. If you leave this out - ## we kindly ask your users to donate to the Diaspora Foundation :) - paypal_hosted_button_id: "" - - - ## Community Spotlight - ## The community spotlight gives new users a starting point on who - ## could be interesting Diasporas community. - ## -------- - ## DEPRECATED - use roles instead, see - ## https://github.com/diaspora/diaspora/wiki/FAQ-for-Pod-Maintainers - ## "What are roles and how do I use them?" - ## -------- - #community_spotlight: - #list: - #- 'diasporahq@joindiaspora.com' - #- 'me@example.org' - - ## E-Mail address users can make suggestions about who should be - ## in the spotlight to. - spotlight_suggest_email: '' - - ###################################################### - # Email Configuration - ###################################################### - - ## First you need to enable it ;) - mailer_on: false - - ## Sender address used in mail send by Diaspora - #sender_address: 'no-reply@example.org' - - ## This selects which mailer should be used. Take 'smtp' for a smtp - ## connection, 'sendmail' to use the sendmail binary or - ## 'messagebus' to use the messagebus service. - mailer_method: 'smtp' - - # Address/port to smtp server handling outgoing mail. - smtp_address: 'smtp.example.com' - smtp_port: '587' - - #API key if you are using message bus - message_bus_api_key: '' - - # The path to the sendmail binary. Ignored if mailer_method is not set to sendmail - sendmail_location: '/usr/sbin/sendmail' - - # Set this to true if you want to use exim and sendmail - sendmail_exim_fix: false - - # Authentication required to send mail. Use one of 'plain', - # 'login' or 'cram_md5'. Use 'none' if server does not support - # authentication - smtp_authentication: 'plain' - - # Automatically enable TLS? Ignored if smtp_authentication is set to none - smtp_starttls_auto: true - - # OpenSSL verify mode used when connecting to a SMTP server with TLS. - # Set this to none if you have a self signed certificate, keep it empty (not '') for the default - # Possible values: none, peer, client_once, fail_if_no_peer_cert - smtp_openssl_verify_mode: - - # Domain of smtp server. - # This should match the common name of the certificate - # the SMTP server sends. If he sends one - smtp_domain: 'example.com' - - # Credentials to log in to the SMTP server - may be necessary if - # smtp_authentication is not 'none' - smtp_username: 'smtp_username' - smtp_password: 'secret' - - # Sender address in Diaspora's outgoing mail. - smtp_sender_address: 'no-reply@joindiaspora.com' - - ###################################################### - # Social Service Configuration - ###################################################### - - ## OAuth credentials for Facebook: - facebook_app_id: '' - facebook_app_secret: '' - - #this will be the namespace for your object, it should be configured in your FB app - open_graph_namespace: '' - - - ## OAuth credentials for Twitter: - twitter_consumer_key: '' - twitter_consumer_secret: '' - - ## OAuth credentials for Tumblr - tumblr_consumer_key: '' - tumblr_consumer_secret: '' - - - ###################################################### - # Debugging Service Tool Integration - ###################################################### - - ## Resque is the background processing sysem used by Diaspora - ## Resque web is an admin tool for it. This settings decides wheter - ## or not to inline it into Diaspora. - mount_resque_web: true - - ## If you use Airbrake provide your API key here: - airbrake_api_key: '' - - ## If you use NewRelic provide your credentials here: - NEW_RELIC_LICENSE_KEY: '' - new_relic_app_name: '' - -###################################################### -# Overrides -###################################################### - -development: - <<: *defaults - serve_static_assets: true - no_follow_diasporahq: true - -production: - <<: *defaults - jquery_cdn: true - -################################################## -# FEDERATION LOGGER ############################## -# Do not touch unless you know what you're doing!# -################################################## - -test: - <<: *defaults - pod_url: "http://localhost:9887/" - socket_port: 8081 - open_invitations: true - no_follow_diasporahq: true - serve_static_assets: true - mailer_on: true - -integration1: - <<: *defaults - pod_url: "http://localhost:3001/" - serve_static_assets: true - -integration2: - <<: *defaults - pod_url: "http://localhost:3002/" - serve_static_assets: true diff --git a/config/defaults.yml b/config/defaults.yml new file mode 100644 index 000000000..6bdaaf74b --- /dev/null +++ b/config/defaults.yml @@ -0,0 +1,121 @@ +####################################################################### +############### DO NOT TOUCH ANYTHING BELOW THIS ###################### +####################################################################### + +defaults: + version: + number: "0.0.1.0" + release: false # Do not touch unless in a merge conflict on doing a release, master should have a commit setting this to true which is not backported to the develop branch. + heroku: false + environment: + url: "http://localhost:3000/" + certificate_authorities: + redis: + serve_static_assets: false + require_ssl: true + single_process_mode: false + s3: + enable: false + key: + secret: + bucket: + region: + image_redirect_url: + pubsub_server: 'https://pubsubhubbub.appspot.com/' + privacy: + jquery_cdn: true + google_analytics_key: + piwik: + enable: false + host: + site_id: + mixpanel_uid: + chartbeat_uid: + settings: + pod_name: "Diaspora*" + enable_registrations: true + follow_diasporahq: true + invitations: + open: true + count: 25 + paypal_hosted_button_id: + community_spotlight: + enable: false + suggest_email: + services: + facebook: + enable: false + app_id: + secret: + open_graph_namespace: 'joindiaspora' + twitter: + enable: false + key: + secret: + tumblr: + enable: false + key: + secret: + mail: + enable: false + sender_address: 'no-reply@example.org' + method: 'smtp' + smtp: + host: 'localhost' + port: 587 + authentication: 'plain' + username: + password: + starttls_auto: true + openssl_verify_mode: + domain: + sendmail: + location: '/usr/sbin/sendmail' + exim_fix: false + message_bus_api_key: + admins: + account: + inline_resque_web: true + monitoring: + airbrake_api_key: + new_relic: + enable: false + app_name: + license_key: + +development: + environment: + serve_static_assets: true + single_process_mode: true + require_ssl: false + settings: + follow_diasporahq: false +production: + i_am_a_dummy: # Remove if you add an actual override +test: + environment: + url: "http://localhost:9887/" + single_process_mode: true + require_ssl: false + serve_static_assets: true + settings: + follow_diasporahq: false + invitations: + open: true + services: + facebook: + enable: true + app_id: 'fake' + secret: 'sdoigjosdfijg' + mail: + enable: true +integration1: + environment: + url: "http://localhost:45789/" + serve_static_assets: true + require_ssl: false +integration2: + environment: + url: "http://localhost:34658/" + serve_static_assets: true + require_ssl: false diff --git a/config/deploy.rb b/config/deploy.rb index 85ca3525c..44521a727 100644 --- a/config/deploy.rb +++ b/config/deploy.rb @@ -32,8 +32,7 @@ end namespace :deploy do task :symlink_config_files do run "ln -s -f #{shared_path}/config/database.yml #{current_path}/config/database.yml" - run "ln -s -f #{shared_path}/config/application.yml #{current_path}/config/application.yml" - run "ln -s -f #{shared_path}/config/oauth_keys.yml #{current_path}/config/oauth_keys.yml" + run "ln -s -f #{shared_path}/config/diaspora.yml #{current_path}/config/diaspora.yml" end task :symlink_cookie_secret do diff --git a/config/diaspora.yml.example b/config/diaspora.yml.example new file mode 100644 index 000000000..83cbf6568 --- /dev/null +++ b/config/diaspora.yml.example @@ -0,0 +1,283 @@ +## Some notes about this file: +## - All comments start with a double # +## - All settings are by default commented out with a single # +## You need to uncomment them in order to work. +## - Take care to keep proper indentation, that is keeping the indentation +## of the original #, with no additional space before the settings +## name. +## - Take care to keep proper quoting. All ' should have a matching ' at +## the end of the same line. Same goes for " +## - Lists need the space after the - +## - true, false and numbers should have no quoting. +## Single words could have none, but doesn't do any harm to them. +## +## You can set and/or override all this settings through environment variables +## with the following conversion rules: +## - Strip the top level namespace (configuration, production, etc.) +## - Build the path to the setting, for example environment.s3.enable +## - Replace the dots with underscores: environment_s3_enable +## - Upcase everything: ENVIRONMENT_S3_ENABLE +## - Specify lists/arrays as comma separated values + +configuration: + + ## Settings you need to change or at least review + ## in order for your pod to basically work + environment: + + ## Set the hostname of the machine you're running Diaspora on, as seen + ## from the internet. This should be the URL you want to use to + ## access the pod. So if you plan to reverse proxy it, it should be + ## the URL the proxy listens on. + ## DO NOT CHNANGE THIS AFTER INITIAL SETUP + ## UNLESS YOU KNOW WHAT YOU'RE DOING! + ## However changing http to https is okay and has no consequences. + ## If you do change it you have to start over as it's hardcoded into + ## the database. + #url: "https://example.org/" + + ## Setting the bundle of certificate authorities (CA) certificates. + ## This is operating system specific. + ## Examples, uncomment one or add your own: + ## Debian, Ubuntu, Archlinux (package ca-certificates) + #certificate_authorities: '/etc/ssl/certs/ca-certificates.crt' + ## CentOS + #certificate_authorities: '/etc/pki/tls/certs/ca-bundle.crt' + ## Gentoo + #certificate_authorities: '/etc/ssl/certs/ca-certificates.crt' + + ## URL for a remote redis. + ## Don't forget to restrict the IP access! + ## Leave it commented out for the default (localhost) + #redis: 'redis://exmaple_host' + #redis: 'redis://username:password@host:6379/0' + #redis: 'unix:///tmp/redis.sock' + + ## Require SSL, default true. + ## When set, your pod will force you to use https in production. + ## Since OAuth2 requires SSL Diasporas future API might not work if you're not + ## on SSL. Also no gurantee that posting to services is given if SSL + ## is disabled. + #require_ssl: true + + ## Single process mode + ## If set to true Diaspora will work with just the appserver, + ## thin by default, running, however this makes it quite slow as + ## all the time intensive jobs must be run inside the request cycle. + ## So this is higly unrecommended for production setups. + #single_process_mode: true + + ## Use Amazon S3 instead of your local filesystem + ## to handle uploaded pictures. + s3: + #enable: true + #key: 'changeme' + #secret: 'changeme' + #bucket: 'my_photos' + #region: 'us-east-1' + + ## Related to S3 you can set a url to redirect all requests to uploaded + ## images to another host. If you for example set + ## https://images.example.org here, all requests made to + ## pictures under /uploads/images will be redirected to + ## https://images.example.org/uploads/images/... + #image_redirect_url: 'https://images.example.org' + + assets: + ## Serve static assets via the appserver. + ## This is highly discouraged for production use, + ## let your reverse proxy/webserver do it by serving the files + ## under public/ directly. + #serve: true + + ## Upload your assets to S3 + #upload: true + + ## Specify an asset host. Ensure it does not have a trailing slash (/). + #host: http://cdn.example.org/diaspora + + ## Diaspora is only tested against this default pubsub server. + ## You likely don't want to change this. + #pubsub_server: 'https://pubsubhubbub.appspot.com/' + + + ## Settings probably affecting the privacy of your users + privacy: + + ## Include jQuery from Google's CDN + ## This potentially saves you some traffic and speeds up + ## load time since most clients already have this one cached + #jquery_cdn: true + + ## Provide a key to enable tracking by Google Analytics + #google_analytics_key: + + ## Piwik Tracking + ## Provide a site ID and the host piwik is running on to enable + ## tracking through Piwik. + piwik: + #enable: true + #host: 'stats.example.org' + #site_id: 1 + + ## Mixpanel event tracking + #mixpanel_uid: + + ## Chartbeat tracking + #chartbeat_uid: + + ## General settings + settings: + + ## The name of your pod displayed in various locations, + ## including the header. + #pod_name: "Diaspora*" + + ## Set this to false to prevent people from signing up for your pod + ## without an invitation. Note that this needs to be true even for + ## the first registration (you). + #enable_registrations: true + + ## Set this to false if you don't want your users to follow the + ## diasporahq@joindiaspora.com account on account creation. + ## The diasporahq account helps users start with some activity in + ## their stream and get news about Diaspora, but if you don't want + ## your server to contact joindiaspora.com, set this to false: + #follow_diasporahq: false + + ## Settings about invitations + invitiations: + + ## Set this to true if you want users to invite as many + ## people as they want. + #open: true + + ## The default amount of invitiations an invite link has. + ## Every user has such a link. Only counts if open is false. + #count: 25 + + ## Paypal donations + ## You can provide the ID of a hosted Paypal button here to kindly ask + ## your users for donations to run their pod. If you leave this out + ## we kindly ask your users to donate to the Diaspora Foundation :) + #paypal_hosted_button_id: "" + + ## Community Spotlight + ## The community spotlight gives new users a starting point on who + ## could be interesting Diasporas community. To add a person + ## to the spotlight add the 'spotlight' role to it. + community_spotlight: + #enable: false + ## E-Mail address users can make suggestions about who should be + ## in the spotlight to. + #suggest_email: 'admin@example.org' + + ## Setup E-Mail + mail: + + ## First you need to enable it ;) + #enable: true + + ## Sender address used in mail send by Diaspora + #sender_address: 'no-reply@example.org' + + ## This selects which mailer should be used. Take 'smtp' for a smtp + ## connection, 'sendmail' to use the sendmail binary or + ## 'messagebus' to use the messagebus service. + #method: 'smtp' + + ## Ignore if method isn't 'smtp' + smtp: + ## Host and port of the smtp server handling outgoing mail. + ## This should match the common name of the certificate + ## the SMTP server sends. If he sends one. + #host: 'smtp.example.org' + #port: 587 + + ## Authentication required to send mail. Use one of 'plain', + ## 'login' or 'cram_md5'. Use 'none' if server does not support + ## authentication + #authentication: 'plain' + + ## Credentials to log in to the SMTP server - may be necessary if + ## authentication is not 'none' + #username: 'changeme' + #password: 'changeme' + + ## Automatically enable TLS? Ignored if authentication is set to none + #starttls_auto: true + + ## The domain for the HELO command if needed + #domain: 'smtp.example.org' + + ## OpenSSL verify mode used when connecting to a + ## SMTP server with TLS. Set this to none if you have + ## a self signed certificate. Possible values: + ## 'none', 'peer', 'client_once', 'fail_if_no_peer_cert' + #openssl_verify_mode: 'none' + + ## Ignore if method isn't 'sendmail' + sendmail: + ## The path to the sendmail binary. + #location: '/usr/sbin/sendmail' + + ## Set this to true if you want to use exim and sendmail + #exim_fix: true + + ## Ignore if method isn't 'messagebus' + #message_bus_api_key: 'abcdef' + + ## Settings around Diasporas capabilities to post to services + services: + ## OAuth credentials for Facebook: + facebook: + #enable: true + #app_id: 'abcdef' + #secret: 'changeme' + ## this will be the namespace for your object, + ## it should be configured in your FB app + #open_graph_namespace: + + ## OAuth credentials for Twitter: + twitter: + #enable: true + #key: 'abcdef' + #secret: 'changeme' + + ## OAuth credentials for Tumblr + tumblr: + #enable: true + #key: 'abcdef' + #secret: 'changeme' + + ## Settings relevant to administrators + admins: + + ## Set the admin account. + ## This doesn't make the user an admin but is used when a generic + ## admin contact is neeeded, much like the postmaster role in mail + ## systems. Set only the username, NOT the full ID. + #account: "podmaster" + + ## Resque is the background processing system used by Diaspora + ## Resque web is an admin tool for it. This settings decides whether + ## or not to inline it into Diaspora. + #inline_resque_web: true + + monitoring: + ## If you use Airbrake provide your API key here: + #airbrake_api_key: 'abcdef' + + ## If you use NewRelic provide your credentials here: + new_relic: + #enable: true + #app_name: 'foo' + #license_key: 'abcdef' + +## Here you can make overides to settings defined above if you need +## to have them different in different environments. +production: + +development: + environment: + #redis_url: 'redis://production.example.org:6379' diff --git a/config/environment.rb b/config/environment.rb index c55253105..690a781dc 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -13,7 +13,10 @@ end # Load the rails application require File.expand_path('../application', __FILE__) -require File.join(Rails.root, "lib", "exceptions") +require Rails.root.join("lib", "exceptions") + +# Load configuration system early +require Rails.root.join("config", "load_config") Haml::Template.options[:format] = :html5 Haml::Template.options[:escape_html] = true diff --git a/config/heroku.yml.example b/config/heroku.yml.example index f069a6668..ba76bc21c 100644 --- a/config/heroku.yml.example +++ b/config/heroku.yml.example @@ -1,6 +1,6 @@ defaults: &defaults HEROKU: true - application_yml: <%= '../' + '../' +'config/' + 'application.yml.example' %> + application_yml: <%= '../' + '../' +'config/' + 'diaspora.yml.example' %> production: app: production stack: cedar diff --git a/config/initializers/1_intialize_app_config.rb b/config/initializers/1_intialize_app_config.rb deleted file mode 100644 index ccda76cc9..000000000 --- a/config/initializers/1_intialize_app_config.rb +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright (c) 2010-2011, Diaspora Inc. This file is -# licensed under the Affero General Public License version 3 or later. See -# the COPYRIGHT file. - -require Rails.root.join('app', 'models', 'app_config') \ No newline at end of file diff --git a/config/initializers/2_before_load_services.rb b/config/initializers/2_before_load_services.rb deleted file mode 100644 index 48f2a23f3..000000000 --- a/config/initializers/2_before_load_services.rb +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright (c) 2010-2011, Diaspora Inc. This file is -# licensed under the Affero General Public License version 3 or later. See -# the COPYRIGHT file. - -def load_config_yaml filename - YAML.load(ERB.new(File.read(filename)).result) -end - -oauth_keys_file = Rails.root.join('config', 'oauth_keys.yml').to_s - - -SERVICES = load_config_yaml("#{oauth_keys_file}.example") - -#this is to be backwards compatible with current production setups -if File.exist? oauth_keys_file - ActiveSupport::Deprecation.warn("01/05/2012 keys in oauth_keys.yml should be moved into application.yml. SEE application.yml.example for updated key names") - SERVICES.deep_merge!(load_config_yaml(oauth_keys_file)) -end diff --git a/config/initializers/3_setup_app_config.rb b/config/initializers/3_setup_app_config.rb deleted file mode 100644 index 7125cb588..000000000 --- a/config/initializers/3_setup_app_config.rb +++ /dev/null @@ -1 +0,0 @@ -AppConfig.setup! diff --git a/config/initializers/airbrake.rb b/config/initializers/airbrake.rb index 5d7a680f8..1f5d46c05 100644 --- a/config/initializers/airbrake.rb +++ b/config/initializers/airbrake.rb @@ -3,8 +3,8 @@ # the COPYRIGHT file. Airbrake.configure do |config| - if AppConfig[:airbrake_api_key].present? - config.api_key = AppConfig[:airbrake_api_key] + if AppConfig.admins.monitoring.airbrake_api_key.present? + config.api_key = AppConfig.admins.monitoring.airbrake_api_key else # creative way to disable Airbrake, should be replaced once the gem provides a proper way config.development_environments << Rails.env diff --git a/config/initializers/carrierwave.rb b/config/initializers/carrierwave.rb index 148e3aab5..9782335ef 100644 --- a/config/initializers/carrierwave.rb +++ b/config/initializers/carrierwave.rb @@ -3,18 +3,18 @@ # the COPYRIGHT file. #Excon needs to see the CA Cert Bundle file -ENV["SSL_CERT_FILE"] = AppConfig[:ca_file] +ENV['SSL_CERT_FILE'] = AppConfig.environment.certificate_authorities.get CarrierWave.configure do |config| - if !Rails.env.test? && AppConfig[:s3_key] && AppConfig[:s3_secret] && AppConfig[:s3_bucket] && AppConfig[:s3_region] + if !Rails.env.test? && AppConfig.environment.s3.enable? config.storage = :fog config.cache_dir = Rails.root.join('tmp', 'uploads').to_s config.fog_credentials = { - :provider => 'AWS', - :aws_access_key_id => AppConfig[:s3_key], - :aws_secret_access_key => AppConfig[:s3_secret], - :region => AppConfig[:s3_region] + :provider => 'AWS', + :aws_access_key_id => AppConfig.environment.s3.key.get, + :aws_secret_access_key => AppConfig.environment.s3.secret.get, + :region => AppConfig.environment.s3.region.get } - config.fog_directory = AppConfig[:s3_bucket] + config.fog_directory = AppConfig.environment.s3.bucket.get else config.storage = :file end diff --git a/config/initializers/check_session_secret.rb b/config/initializers/check_session_secret.rb index 87e385c7e..563143dcf 100644 --- a/config/initializers/check_session_secret.rb +++ b/config/initializers/check_session_secret.rb @@ -1 +1,6 @@ -EnvironmentConfiguration.ensure_secret_token! \ No newline at end of file +if AppConfig.heroku? + Rails.application.config.secret_token = AppConfig.secret_token +elsif !File.exists?( Rails.root.join('config', 'initializers', 'secret_token.rb')) + `bundle exec rake generate:secret_token` + require Rails.root.join('config', 'initializers', 'secret_token.rb') +end diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb index 5e5ec0313..8f6c83204 100644 --- a/config/initializers/devise.rb +++ b/config/initializers/devise.rb @@ -21,9 +21,9 @@ Devise.setup do |config| require 'devise/orm/active_record' #mail setup - if AppConfig[:smtp_sender_address] - config.mailer_sender = AppConfig[:smtp_sender_address] - else + if AppConfig.mail.sender_address.present? + config.mailer_sender = AppConfig.mail.sender_address + elsif AppcConfig.mail.enable? unless Rails.env == 'test' Rails.logger.warn("No smtp sender address set, mail may fail.") puts "WARNING: No smtp sender address set, mail may fail." diff --git a/config/initializers/enforce_ssl.rb b/config/initializers/enforce_ssl.rb index 80f2bc97d..65a9951c1 100644 --- a/config/initializers/enforce_ssl.rb +++ b/config/initializers/enforce_ssl.rb @@ -2,7 +2,7 @@ # licensed under the Affero General Public License version 3 or later. See # the COPYRIGHT file. -if EnvironmentConfiguration.enforce_ssl? +if AppConfig.environment.require_ssl? Rails.application.config.middleware.insert_before 0, Rack::SSL puts "Rack::SSL is enabled" end diff --git a/config/initializers/faraday.rb b/config/initializers/faraday.rb index cd96e1c28..30b827fcb 100644 --- a/config/initializers/faraday.rb +++ b/config/initializers/faraday.rb @@ -3,7 +3,7 @@ # the COPYRIGHT file. options = {:timeout => 25} -options[:ssl] = {:ca_file => EnvironmentConfiguration.ca_cert_file_location} +options[:ssl] = {:ca_file => AppConfig.environment.certificate_authorities} Faraday.default_connection = Faraday::Connection.new(options) do |b| b.use FaradayMiddleware::FollowRedirects b.adapter Faraday.default_adapter diff --git a/config/initializers/fetch_featured_users.rb b/config/initializers/fetch_featured_users.rb deleted file mode 100644 index b09c0b1d0..000000000 --- a/config/initializers/fetch_featured_users.rb +++ /dev/null @@ -1,15 +0,0 @@ -#this breaks seed scripts - -if AppConfig[:featured_users].present? && AppConfig[:community_spotlight].blank? - AppConfig[:community_spotlight] = AppConfig[:featured_users] - puts "DEPRICATION WARNING (10/21/11): Please change `featured_users` in your application.yml to `community_spotlight`. Thanks!" -end - -unless EnvironmentConfiguration.prevent_fetching_community_spotlight? - print "Fetching community spotlight users from remote servers" - AppConfig[:community_spotlight].each do |x| - Webfinger.new(x).fetch - print "." - end - puts " done!" -end diff --git a/config/initializers/ignore_ssl_in_development.rb b/config/initializers/ignore_ssl_in_development.rb index bf962fcb2..9ec8a2d9c 100644 --- a/config/initializers/ignore_ssl_in_development.rb +++ b/config/initializers/ignore_ssl_in_development.rb @@ -2,7 +2,7 @@ # licensed under the Affero General Public License version 3 or later. See # the COPYRIGHT file. -if AppConfig[:ca_file].blank? && (Rails.env == "development") +if AppConfig.environment.certificate_authorities.blank? && (Rails.env == "development") module OpenSSL module SSL remove_const :VERIFY_PEER diff --git a/config/initializers/load_analyitics.rb b/config/initializers/load_analyitics.rb index 338cd3c73..f8731f9d3 100644 --- a/config/initializers/load_analyitics.rb +++ b/config/initializers/load_analyitics.rb @@ -5,15 +5,16 @@ if Rails.env == 'production' Diaspora::Application.configure do - if AppConfig[:google_a_site].present? + if AppConfig.privacy.google_analytics_key.present? config.gem 'rack-google-analytics', :lib => 'rack/google-analytics' - config.middleware.use Rack::GoogleAnalytics, :tracker => AppConfig[:google_a_site] + config.middleware.use Rack::GoogleAnalytics, :tracker => AppConfig.privacy.google_analytics_key.get end - if AppConfig[:piwik_url].present? + if AppConfig.privacy.piwik.enable? require 'rack/piwik' config.gem 'rack-piwik', :lib => 'rack/piwik' - config.middleware.use Rack::Piwik, :piwik_url => AppConfig[:piwik_url], :piwik_id => AppConfig[:piwik_id] + config.middleware.use Rack::Piwik, :piwik_url => AppConfig.privacy.piwik.host.get, + :piwik_id => AppConfig.privacy.piwik.site_id.get end end end diff --git a/config/initializers/mailer_config.rb b/config/initializers/mailer_config.rb index b8b818c5d..6cd89dd87 100644 --- a/config/initializers/mailer_config.rb +++ b/config/initializers/mailer_config.rb @@ -4,51 +4,49 @@ require Rails.root.join('lib', 'messagebus', 'mailer') Diaspora::Application.configure do - config.action_mailer.default_url_options = {:protocol => AppConfig[:pod_uri].scheme, - :host => AppConfig[:pod_uri].authority } - config.action_mailer.asset_host = AppConfig[:pod_uri].to_s - config.action_mailer.perform_deliveries = AppConfig[:mailer_on] + config.action_mailer.default_url_options = {:protocol => AppConfig.pod_uri.scheme, + :host => AppConfig.pod_uri.authority } + config.action_mailer.asset_host = AppConfig.pod_uri.to_s + config.action_mailer.perform_deliveries = AppConfig.mail.enable? - unless Rails.env == 'test' || AppConfig[:mailer_on] != true - if AppConfig[:mailer_method] == 'messagebus' + unless Rails.env == 'test' || !AppConfig.mail.enable? + if AppConfig.mail.method == 'messagebus' - if AppConfig[:message_bus_api_key].present? - - config.action_mailer.delivery_method = Messagebus::Mailer.new(AppConfig[:message_bus_api_key]) + if AppConfig.mail.message_bus_api_key.present? + config.action_mailer.delivery_method = Messagebus::Mailer.new(AppConfig.mail.message_bus_api_key.get) config.action_mailer.raise_delivery_errors = true else puts "You need to set your messagebus api key if you are going to use the message bus service. no mailer is now configured" end - elsif AppConfig[:mailer_method] == "sendmail" + elsif AppConfig.mail.method == "sendmail" config.action_mailer.delivery_method = :sendmail sendmail_settings = { - :location => AppConfig[:sendmail_location] + :location => AppConfig.mail.sendmail.location.get } - sendmail_settings[:arguments] = "-i" if AppConfig[:sendmail_exim_fix] + sendmail_settings[:arguments] = "-i" if AppConfig.mail.sendmail.exim_fix? config.action_mailer.sendmail_settings = sendmail_settings - else + elsif AppConfig.mail.method == "smtp" config.action_mailer.delivery_method = :smtp - if AppConfig[:smtp_authentication] == "none" - config.action_mailer.smtp_settings = { - :address => AppConfig[:smtp_address], - :port => AppConfig[:smtp_port], - :domain => AppConfig[:smtp_domain], - :enable_starttls_auto => false, - :openssl_verify_mode => AppConfig[:smtp_openssl_verify_mode] - } - else - config.action_mailer.smtp_settings = { - :address => AppConfig[:smtp_address], - :port => AppConfig[:smtp_port], - :domain => AppConfig[:smtp_domain], - :authentication => AppConfig[:smtp_authentication].gsub('-', '_').to_sym, - :user_name => AppConfig[:smtp_username], - :password => AppConfig[:smtp_password], - :enable_starttls_auto => AppConfig[:smtp_starttls_auto], - :openssl_verify_mode => AppConfig[:smtp_openssl_verify_mode] - } + smtp_settings = { + :address => AppConfig.mail.smtp.host.get, + :port => AppConfig.mail.smtp.port.to_i, + :domain => AppConfig.mail.smtp.domain.get, + :enable_starttls_auto => false, + :openssl_verify_mode => AppConfig.mail.smtp.openssl_verify_mode.get + } + + if AppConfig.mail.smtp.authentication != "none" + smtp_settings.merge!({ + :authentication => AppConfig.mail.smtp.authentication.gsub('-', '_').to_sym, + :user_name => AppConfig.mail.smtp.username.get, + :password => AppConfig.mail.smtp.password.get, + :enable_starttls_auto => AppConfig.mail.smtp.starttls_auto? + }) end + + config.action_mailer.smtp_settings = smtp_settings + else + $stderr.puts "WARNING: Mailer turned on with unknown method #{AppConfig.mail.method}. Mail won't work." end end - end diff --git a/config/initializers/newrelic.rb b/config/initializers/newrelic.rb index 5a7d107e8..b4e3a0979 100644 --- a/config/initializers/newrelic.rb +++ b/config/initializers/newrelic.rb @@ -2,6 +2,6 @@ # licensed under the Affero General Public License version 3 or later. See # the COPYRIGHT file. -if EnvironmentConfiguration.using_new_relic? +if AppConfig.admins.monitoring.new_relic.enable? require 'newrelic_rpm' end diff --git a/config/initializers/omniauth.rb b/config/initializers/omniauth.rb index 6049dee4d..32e390b5b 100644 --- a/config/initializers/omniauth.rb +++ b/config/initializers/omniauth.rb @@ -3,14 +3,15 @@ # the COPYRIGHT file. Rails.application.config.middleware.use OmniAuth::Builder do - if SERVICES['twitter'] && SERVICES['twitter']['consumer_key'] && SERVICES['twitter']['consumer_secret'] - provider :twitter, SERVICES['twitter']['consumer_key'], SERVICES['twitter']['consumer_secret'] + if AppConfig.services.twitter.enable? + provider :twitter, AppConfig.services.twitter.key, AppConfig.services.twitter.secret end - if SERVICES['tumblr'] && SERVICES['tumblr']['consumer_key'] && SERVICES['tumblr']['consumer_secret'] - provider :tumblr, SERVICES['tumblr']['consumer_key'], SERVICES['tumblr']['consumer_secret'] + if AppConfig.services.tumblr.enable? + provider :tumblr, AppConfig.services.tumblr.key, AppConfig.services.tumblr.secret end - if SERVICES['facebook'] && SERVICES['facebook']['app_id'] && SERVICES['facebook']['app_secret'] - provider :facebook, SERVICES['facebook']['app_id'], SERVICES['facebook']['app_secret'], { :display => "popup", :scope => "publish_actions,publish_stream,offline_access", - :client_options => {:ssl => {:ca_file => EnvironmentConfiguration.ca_cert_file_location}}} + if AppConfig.services.facebook.enable? + provider :facebook, AppConfig.services.facebook.app_id, AppConfig.services.facebook.secret, + { :display => "popup", :scope => "publish_actions,publish_stream,offline_access", + :client_options => {:ssl => {:ca_file => AppConfig.environment.certificate_authorities }}} end end diff --git a/config/initializers/resque.rb b/config/initializers/resque.rb index c89f86723..1ed9eaf0f 100644 --- a/config/initializers/resque.rb +++ b/config/initializers/resque.rb @@ -2,26 +2,26 @@ require 'resque' Resque::Plugins::Timeout.timeout = 300 -if !AppConfig.single_process_mode? +if !AppConfig.environment.single_process_mode? Resque.redis = AppConfig.get_redis_instance end # Single process-mode hooks using Resque.inline -if AppConfig.single_process_mode? +if AppConfig.environment.single_process_mode? if Rails.env == 'production' puts "WARNING: You are running Diaspora in production without Resque" puts " workers turned on. Please set single_process_mode to false in" - puts " config/application.yml." + puts " config/diaspora.yml." end Resque.inline = true end -if AppConfig[:airbrake_api_key].present? +if AppConfig.admins.monitoring.airbrake_api_key.present? require 'resque/failure/multiple' require 'resque/failure/airbrake' require 'resque/failure/redis' Resque::Failure::Airbrake.configure do |config| - config.api_key = AppConfig[:airbrake_api_key] + config.api_key = AppConfig.admins.monitoring.airbrake_api_key config.secure = true end Resque::Failure::Multiple.classes = [Resque::Failure::Redis, Resque::Failure::Airbrake] @@ -29,7 +29,7 @@ if AppConfig[:airbrake_api_key].present? end -if AppConfig[:mount_resque_web] +if AppConfig.admins.inline_resque_web? require 'resque/server' require Rails.root.join('lib', 'admin_rack') Resque::Server.use AdminRack diff --git a/config/initializers/set_up_image_redirects.rb b/config/initializers/set_up_image_redirects.rb index 94d4d90d9..64126a620 100644 --- a/config/initializers/set_up_image_redirects.rb +++ b/config/initializers/set_up_image_redirects.rb @@ -1,8 +1,8 @@ -if AppConfig[:image_redirect_url].present? +if AppConfig.environment.image_redirect_url.present? require 'rack-rewrite' Rails.application.config.middleware.insert(0, Rack::Rewrite) do - r301 %r{/uploads/images/(.*)}, "#{AppConfig[:image_redirect_url]}/uploads/images/$1" - r301 %r{/landing/(.*)}, "#{AppConfig[:image_redirect_url]}/landing/$1" + r301 %r{/uploads/images/(.*)}, "#{AppConfig.environment.image_redirect_url}/uploads/images/$1" + r301 %r{/landing/(.*)}, "#{AppConfig.environment.image_redirect_url}/landing/$1" end -end \ No newline at end of file +end diff --git a/config/initializers/static_assets.rb b/config/initializers/static_assets.rb index 4284e185d..d645ec958 100644 --- a/config/initializers/static_assets.rb +++ b/config/initializers/static_assets.rb @@ -3,6 +3,6 @@ # the COPYRIGHT file. Diaspora::Application.configure do - config.serve_static_assets = AppConfig[:serve_static_assets] unless AppConfig[:serve_static_assets].nil? + config.serve_static_assets = AppConfig.environment.serve_static_assets? # config.static_cache_control = "public, max-age=3600" if AppConfig[:serve_static_assets].to_s == 'true' end diff --git a/config/initializers/version_header.rb b/config/initializers/version_header.rb index d9215a556..9d3eaf294 100644 --- a/config/initializers/version_header.rb +++ b/config/initializers/version_header.rb @@ -2,12 +2,4 @@ # licensed under the Affero General Public License version 3 or later. See # the COPYRIGHT file. - -if EnvironmentConfiguration.cache_git_version? - git_cmd = `git log -1 --pretty="format:%H %ci"` - if git_cmd =~ /^([\d\w]+?)\s(.+)$/ - AppConfig[:git_revision] = $1 - AppConfig[:git_update] = $2.strip - ENV["RAILS_ASSET_ID"] = AppConfig[:git_revision][0..8] if Rails.env.production? - end -end \ No newline at end of file +ENV["RAILS_ASSET_ID"] = AppConfig.rails_asset_id if Rails.env.production? && ! AppConfig.heroku? diff --git a/config/load_config.rb b/config/load_config.rb new file mode 100644 index 000000000..1e7cfd5ba --- /dev/null +++ b/config/load_config.rb @@ -0,0 +1,41 @@ +require Rails.root.join('lib', 'configuration') +require Rails.root.join('lib', 'configuration', 'methods') + +config_dir = Rails.root.join("config") + +if File.exists?(config_dir.join("application.yml")) + $stderr.puts "ATTENTION: There's a new configuration system, please remove your" + $stderr.puts " application.yml and migrate your settings." +end + + +AppConfig ||= Configuration::Settings.create do + add_provider Configuration::Provider::Dynamic + add_provider Configuration::Provider::Env + + unless heroku? || Rails.env == "test" || File.exists?(config_dir.join("diaspora.yml")) + $stderr.puts "FATAL: Configuration not found. Copy over diaspora.yml.example" + $stderr.puts " to diaspora.yml and edit it to your needs." + Process.exit(1) + end + + add_provider Configuration::Provider::YAML, + config_dir.join("diaspora.yml"), + namespace: Rails.env, required: false + add_provider Configuration::Provider::YAML, + config_dir.join("diaspora.yml"), + namespace: "configuration", required: false + add_provider Configuration::Provider::YAML, + config_dir.join("defaults.yml"), + namespace: Rails.env + add_provider Configuration::Provider::YAML, + config_dir.join("defaults.yml"), + namespace: "defaults" + + extend Configuration::Methods + + if Rails.env == "production" && (environment.certificate_authorities.blank? || !File.exists?(environment.certificate_authorities.get)) + $stderr.puts "FATAL: Diaspora doesn't know where your certificate authorities are. Please ensure they are set to a valid path in diaspora.yml" + Process.exit(1) + end +end diff --git a/config/newrelic.yml b/config/newrelic.yml index a254b0457..ecc8e491c 100644 --- a/config/newrelic.yml +++ b/config/newrelic.yml @@ -14,7 +14,7 @@ common: &default_settings # You must specify the license key associated with your New Relic # account. This key binds your Agent's data to your account in the # New Relic service. - license_key: <%= AppConfig['NEW_RELIC_LICENSE_KEY'] %> + license_key: <%= AppConfig.admins.monitoring.new_relic.license_key %> # Agent Enabled (Ruby/Rails Only) # Use this setting to force the agent to run or not run. @@ -33,7 +33,7 @@ common: &default_settings # "All UI" then specify a semicolon-separated list of up to three # distinct names. If you comment this out, it defaults to the # capitalized RAILS_ENV (i.e., Production, Staging, etc) - app_name: <%= AppConfig.new_relic_app_name %> + app_name: <%= AppConfig.admins.monitoring.new_relic.app_name %> # When "true", the agent collects performance data about your # application and reports this data to the New Relic service at diff --git a/config/oauth_keys.yml.example b/config/oauth_keys.yml.example deleted file mode 100644 index 4bbeb2d14..000000000 --- a/config/oauth_keys.yml.example +++ /dev/null @@ -1,9 +0,0 @@ -twitter: - consumer_key: <%= AppConfig['twitter_consumer_key'] %> - consumer_secret: <%= AppConfig['twitter_consumer_secret'] %> -facebook: - app_id: <%=AppConfig['facebook_app_id'] %> - app_secret: <%= AppConfig['facebook_app_secret'] %> -tumblr: - consumer_key: <%= AppConfig['tumblr_consumer_key'] %> - consumer_secret: <%= AppConfig['tumblr_consumer_secret'] %> diff --git a/config/routes.rb b/config/routes.rb index 45e81aaf9..6ae77aca4 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -213,7 +213,7 @@ Diaspora::Application.routes.draw do get 'protocol' => redirect("https://github.com/diaspora/diaspora/wiki/Diaspora%27s-federation-protocol") # Resque web - if AppConfig[:mount_resque_web] + if AppConfig.admins.inline_resque_web? mount Resque::Server.new, :at => '/resque-jobs', :as => "resque_web" end diff --git a/config/unicorn.rb b/config/unicorn.rb index 7c6810b7e..97a8d3889 100644 --- a/config/unicorn.rb +++ b/config/unicorn.rb @@ -46,7 +46,7 @@ after_fork do |server, worker| ActiveRecord::Base.establish_connection # copy pasta from resque.rb because i'm a bad person - if !AppConfig.single_process_mode? + if !AppConfig.environment.single_process_mode? Resque.redis = AppConfig.get_redis_instance end diff --git a/features/step_definitions/uri-step.rb b/features/step_definitions/uri-step.rb index 4928be63e..a37d737fa 100644 --- a/features/step_definitions/uri-step.rb +++ b/features/step_definitions/uri-step.rb @@ -1,10 +1,3 @@ -Given /^configuration parameter (\w+) is ([^ ]+)$/ do |key, value| - require Rails.root.join('config', "initializers", "_load_app_config.rb") - app_value = AppConfig[key.to_sym] - assert_equal value, app_value, - "You must set #{key} to #{value} and kill running server" -end - When /^I visit url ([^ ]+)$/ do |url| visit( url) end diff --git a/features/support/env.rb b/features/support/env.rb index 7d5258e2f..78533829a 100644 --- a/features/support/env.rb +++ b/features/support/env.rb @@ -56,11 +56,6 @@ Spork.prefork do # require 'webmock/cucumber' # WebMock.disable_net_connect!(:allow_localhost => true) - silence_warnings do - SERVICES['facebook'] = {'app_id' => :fake, 'app_secret' => 'sdoigjosdfijg'} - AppConfig[:configured_services] << 'facebook' - end - require Rails.root.join('spec', 'support', 'fake_resque') require File.join(File.dirname(__FILE__), 'run_resque_in_process') @@ -75,14 +70,11 @@ end Spork.each_run do Before do - @no_follow_diaspora_hq_setting = AppConfig[:no_follow_diasporahq] - AppConfig[:no_follow_diasporahq] = true DatabaseCleaner.clean Devise.mailer.deliveries = [] end After do - AppConfig[:no_follow_diasporahq] = @no_follow_diaspora_hq_setting if Capybara.current_session.driver.respond_to?(:browser) Capybara.reset_sessions! # Capybara.current_session.driver.browser.manage.delete_all_cookies diff --git a/lib/configuration.rb b/lib/configuration.rb new file mode 100644 index 000000000..c691b4940 --- /dev/null +++ b/lib/configuration.rb @@ -0,0 +1,69 @@ + +require Rails.root.join('lib', 'configuration', 'lookup_chain') +require Rails.root.join('lib', 'configuration', 'provider') +require Rails.root.join('lib', 'configuration', 'proxy') + + +# A flexible and extendable configuration system. +# The calling logic is isolated from the lookup logic +# through configuration providers, which only requirement +# is to define the +#lookup+ method and show a certain behavior on that. +# The providers are asked in the order they were added until one provides +# a response. This allows to even add multiple providers of the same type, +# you never easier defined your default configuration parameters. +# There are no class methods used, you can have an unlimited amount of +# independent configuration sources at the same time. +# +# See {Settings} for a quick start. +module Configuration + # This is your main entry point. Instead of lengthy explanations + # let an example demonstrate its usage: + # + # require Rails.root.join('lib', 'configuration') + # + # AppSettings = Configuration::Settings.create do + # add_provider Configuration::Provider::Env + # add_provider Configuration::Provider::YAML, '/etc/app_settings.yml', + # namespace: Rails.env, required: false + # add_provider Configuration::Provider::YAML, 'config/default_settings.yml' + # + # extend YourConfigurationMethods + # end + # + # AppSettings.setup_something if AppSettings.something.enable? + # + # Please also read the note at {Proxy}! + class Settings + + attr_reader :lookup_chain + + undef_method :method # Remove possible conflicts with common setting names + + # @!method lookup(setting) + # (see LookupChain#lookup) + # @!method add_provider(provider, *args) + # (see LookupChain#add_provider) + # @!method [](setting) + # (see LookupChain#[]) + def method_missing(method, *args, &block) + return @lookup_chain.send(method, *args, &block) if [:lookup, :add_provider, :[]].include?(method) + + Proxy.new(@lookup_chain).send(method, *args, &block) + end + + def initialize + @lookup_chain = LookupChain.new + $stderr.puts "Warning you called Configuration::Settings.new with a block, you really meant to call #create" if block_given? + end + + # Create a new configuration object + # @yield the given block will be evaluated in the context of the new object + def self.create(&block) + config = self.new + config.instance_eval(&block) if block_given? + config + end + end + + class SettingNotFoundError < RuntimeError; end +end diff --git a/lib/configuration/lookup_chain.rb b/lib/configuration/lookup_chain.rb new file mode 100644 index 000000000..803a86610 --- /dev/null +++ b/lib/configuration/lookup_chain.rb @@ -0,0 +1,65 @@ +module Configuration + # This object builds a chain of configuration providers to try to find + # a setting. + class LookupChain + def initialize + @provider = [] + end + + # Add a provider to the chain. Providers are tried in the order + # they are added, so the order is important. + # + # @param provider [#lookup] + # @param *args the arguments passed to the providers constructor + # @raise [ArgumentError] if an invalid provider is given + # @return [void] + def add_provider(provider, *args) + unless provider.instance_method_names.include?("lookup") + raise ArgumentError, "the given provider does not respond to lookup" + end + + @provider << provider.new(*args) + end + + + # Tries all providers in the order they were added to provide a response + # for setting. + # + # @param setting [#to_s] settings should be underscore_case, + # nested settings should be separated by a dot + # @param *args further args passed to the provider + # @return [Array,String,Boolean,nil] whatever the provider provides + # is casted to a {String}, except for some special values + def lookup(setting, *args) + setting = setting.to_s + + @provider.each do |provider| + begin + return special_value_or_string(provider.lookup(setting, *args)) + rescue SettingNotFoundError; end + end + + nil + end + alias_method :[], :lookup + + private + + def special_value_or_string(value) + if [TrueClass, FalseClass, NilClass, Array, Hash].include?(value.class) + return value + elsif value.is_a?(String) + return case value.strip + when "true" then true + when "false" then false + when "", "nil" then nil + else value + end + elsif value.respond_to?(:to_s) + return value.to_s + else + return value + end + end + end +end diff --git a/lib/configuration/methods.rb b/lib/configuration/methods.rb new file mode 100644 index 000000000..6b58967ca --- /dev/null +++ b/lib/configuration/methods.rb @@ -0,0 +1,115 @@ +module Configuration + module Methods + def pod_uri + return @pod_uri unless @pod_uri.nil? + + url = environment.url.get + url = "http://#{url}" unless url =~ /^(https?:\/\/)/ + url << "/" unless url.end_with?("/") + + begin + @pod_url = Addressable::URI.parse(url) + rescue + puts "WARNING: pod url #{url} is not a legal URI" + end + + @pod_url + end + + def bare_pod_uri + pod_uri.authority.gsub('www.', '') + end + + def configured_services + return @configured_services unless @configured_services.nil? + + @configured_services = [] + [:twitter, :tumblr, :facebook].each do |service| + @configured_services << service if services.send(service).enable? + end + + @configured_services + end + attr_writer :configured_services + + def secret_token + return ENV['SECRET_TOKEN'] if ENV['SECRET_TOKEN'] + $stderr.puts "FATAL: Running on Heroku with SECRET_TOKEN unset" + $stderr.puts " Run heroku config:add SECRET_TOKEN=#{SecureRandom.hex(40)}" + Process.exit(1) + end + + def version_string + return @version_string unless @version_string.nil? + @version_string = version.number.to_s + @version_string << "pre" unless version.release? + @version_string << "-p#{git_revision[0..7]}" if git_available? + @version_string + end + + def git_available? + return @git_available unless @git_available.nil? + + if heroku? + @git_available = false + else + `which git` + @git_available = $?.success? + end + end + + def git_revision + get_git_info if git_available? + @git_revision + end + attr_writer :git_revision + + def git_update + get_git_info if git_available? + @git_update + end + attr_writer :git_update + + def rails_asset_id + (git_revision || version)[0..8] + end + + def get_redis_instance + if redistogo_url.present? + $stderr.puts "WARNING: using the REDISTOGO_URL environment variable is deprecated, please use REDIS_URL now." + ENV['REDIS_URL'] = redistogo_url + end + + redis_options = {} + + redis_url = ENV['REDIS_URL'] || environment.redis.get + + if ENV['RAILS_ENV']== 'integration2' + redis_options = { :host => 'localhost', :port => 6380 } + elsif redis_url.present? + unless redis_url.start_with?("redis://") || redis_url.start_with?("unix:///") + $stderr.puts "WARNING: Your redis url (#{redis_url}) doesn't start with redis:// or unix:///" + end + redis_options = { :url => redis_url } + end + + Redis.new(redis_options.merge(:thread_safe => true)) + end + + private + + def get_git_info + return if git_info_present? || !git_available? + + git_cmd = `git log -1 --pretty="format:%H %ci"` + if git_cmd =~ /^([\d\w]+?)\s(.+)$/ + @git_revision = $1 + @git_update = $2.strip + end + end + + def git_info_present? + @git_revision || @git_update + end + end +end diff --git a/lib/configuration/provider.rb b/lib/configuration/provider.rb new file mode 100644 index 000000000..cb8bc82a1 --- /dev/null +++ b/lib/configuration/provider.rb @@ -0,0 +1,19 @@ +module Configuration::Provider + # This provides a basic {#lookup} method for other providers to build + # upon. Childs are expected to define +lookup_path(path, *args)+ where + # +path+ will be passed an array of settings generated by splitting the + # called setting at the dots. The method should return nil if the setting + # wasn't found and {#lookup} will raise an {SettingNotFoundError} in that + # case. + class Base + def lookup(setting, *args) + result = lookup_path(setting.split("."), *args) + return result unless result.nil? + raise Configuration::SettingNotFoundError, "The setting #{setting} was not found" + end + end +end + +require Rails.root.join("lib", "configuration", "provider", "yaml") +require Rails.root.join("lib", "configuration", "provider", "env") +require Rails.root.join("lib", "configuration", "provider", "dynamic") diff --git a/lib/configuration/provider/dynamic.rb b/lib/configuration/provider/dynamic.rb new file mode 100644 index 000000000..245f76a9a --- /dev/null +++ b/lib/configuration/provider/dynamic.rb @@ -0,0 +1,24 @@ +module Configuration::Provider + # This provider knows nothing upon initialization, however if you access + # a setting ending with +=+ and give one argument to that call it remembers + # that setting, stripping the +=+ and will return it on the next call + # without +=+. + class Dynamic < Base + def initialize + @settings = {} + end + + def lookup_path(settings_path, *args) + key = settings_path.join(".") + + if key.end_with?("=") && args.length > 0 + key = key.chomp("=") + value = args.first + value = value.get if value.respond_to?(:_proxy?) && value._proxy? + @settings[key] = value + end + + @settings[key] + end + end +end diff --git a/lib/configuration/provider/env.rb b/lib/configuration/provider/env.rb new file mode 100644 index 000000000..ea17f694e --- /dev/null +++ b/lib/configuration/provider/env.rb @@ -0,0 +1,14 @@ +module Configuration::Provider + # This provider looks for settings in the environment. + # For the setting +foo.bar_baz+ this provider will look for an + # environment variable +FOO_BAR_BAZ+, replacing all dots in the setting + # and upcasing the result. If an value contains +,+ it's split at them + # and returned as array. + class Env < Base + def lookup_path(settings_path, *args) + value = ENV[settings_path.join("_").upcase] + value = value.split(",") if value && value.include?(",") + value + end + end +end diff --git a/lib/configuration/provider/yaml.rb b/lib/configuration/provider/yaml.rb new file mode 100644 index 000000000..635e179d6 --- /dev/null +++ b/lib/configuration/provider/yaml.rb @@ -0,0 +1,52 @@ +require 'yaml' + +module Configuration::Provider + # This provider tries to open a YAML file and does in nested lookups + # in it. + class YAML < Base + # @param file [String] the path to the file + # @param opts [Hash] + # @option opts [String] :namespace optionally set this as the root + # @option opts [Boolean] :required wheter or not to raise an error if + # the file or the namespace, if given, is not found. Defaults to +true+. + # @raise [ArgumentError] if the namespace isn't found in the file + # @raise [Errno:ENOENT] if the file isn't found + def initialize(file, opts = {}) + @settings = {} + required = opts.has_key?(:required) ? opts.delete(:required) : true + + @settings = ::YAML.load_file(file) + + namespace = opts.delete(:namespace) + unless namespace.nil? + actual_settings = lookup_in_hash(namespace.split("."), @settings) + unless actual_settings.nil? + @settings = actual_settings + else + raise ArgumentError, "Namespace #{namespace} not found in #{file}" if required + end + end + rescue Errno::ENOENT => e + $stderr.puts "WARNING: configuration file #{file} not found, ensure it's present" + raise e if required + end + + + def lookup_path(settings_path, *args) + lookup_in_hash(settings_path, @settings) + end + + private + + def lookup_in_hash(setting_path, hash) + setting = setting_path.shift + if hash.has_key?(setting) + if setting_path.length > 0 && hash[setting].is_a?(Hash) + return lookup_in_hash(setting_path, hash[setting]) if setting.length > 1 + else + return hash[setting] + end + end + end + end +end diff --git a/lib/configuration/proxy.rb b/lib/configuration/proxy.rb new file mode 100644 index 000000000..4acbbcc00 --- /dev/null +++ b/lib/configuration/proxy.rb @@ -0,0 +1,76 @@ +module Configuration + # Proxy object to support nested settings + # Cavehat: Since this is always true, adding a ? at the end + # returns the value, if found, instead of the proxy object. + # So instead of +if settings.foo.bar+ use +if settings.foo.bar?+ + # to check for boolean values, +if settings.foo.bar.nil?+ to + # check for nil values, +if settings.foo.bar.present?+ to check for + # empty values if you're in Rails and call {#get} to actually return the value, + # commonly when doing +settings.foo.bar.get || 'default'+. If a setting + # ends with +=+ is too called directly, just like with +?+. + class Proxy < BasicObject + COMMON_KEY_NAMES = [:key, :method] + + # @param lookup_chain [#lookup] + def initialize(lookup_chain) + @lookup_chain = lookup_chain + @setting = "" + end + + def ! + !self.get + end + + def !=(other) + self.get != other + end + + def ==(other) + self.get == other + end + + def _proxy? + true + end + + def respond_to?(method, include_private=false) + method == :_proxy? || self.get.respond_to?(method, include_private) + end + + def send(*args, &block) + self.__send__(*args, &block) + end + + def method_missing(setting, *args, &block) + unless COMMON_KEY_NAMES.include? setting + target = self.get + if !(target.respond_to?(:_proxy?) && target._proxy?) && target.respond_to?(setting) + return target.send(setting, *args, &block) + end + end + + setting = setting.to_s + + self.append_setting(setting) + + return self.get(*args) if setting.end_with?("?") || setting.end_with?("=") + + self + end + + # Get the setting at the current path, if found. + # (see LookupChain#lookup) + def get(*args) + setting = @setting[1..-1] + return unless setting + val = @lookup_chain.lookup(setting.chomp("?"), *args) + val + end + + protected + def append_setting(setting) + @setting << "." + @setting << setting + end + end +end diff --git a/lib/environment_configuration.rb b/lib/environment_configuration.rb deleted file mode 100644 index c1b254ab5..000000000 --- a/lib/environment_configuration.rb +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright (c) 2010-2011, Diaspora Inc. This file is -# licensed under the Affero General Public License version 3 or later. See -# the COPYRIGHT file. - -module EnvironmentConfiguration - - def self.heroku? - ENV['HEROKU'] - end - - def self.secret_token_initializer_is_not_present? - !File.exists?( Rails.root.join('config', 'initializers', 'secret_token.rb')) - end - - def self.prevent_fetching_community_spotlight? - return true if heroku? - !ActiveRecord::Base.connection.table_exists?('people') || Rails.env == 'test' || AppConfig[:community_spotlight].nil? || AppConfig[:community_spotlight].count - end - - def self.cache_git_version? - !self.heroku? - end - - def self.ensure_secret_token! - if heroku? - puts 'heroku app detected; using session secret from config vars...' - Rails.application.config.secret_token = ENV['SECRET_TOKEN'] - elsif secret_token_initializer_is_not_present? - `rake generate:secret_token` - require Rails.root.join('config', 'initializers', 'secret_token.rb') - else - #do nothing - end - end - - def self.enforce_ssl? - return false unless Rails.env == 'production' - return false if ENV['NO_SSL'] - return false if AppConfig[:circumvent_ssl_requirement].present? - true - end - - def self.ca_cert_file_location - if self.heroku? - "/usr/lib/ssl/certs/ca-certificates.crt" - else - AppConfig[:ca_file] - end - end - - def self.using_new_relic? - defined?(NewRelic) && AppConfig['NEW_RELIC_LICENSE_KEY'].present? - end -end diff --git a/lib/messagebus/mailer.rb b/lib/messagebus/mailer.rb index 5b3d52e34..7593ab705 100644 --- a/lib/messagebus/mailer.rb +++ b/lib/messagebus/mailer.rb @@ -20,7 +20,7 @@ module Messagebus end def deliver!(message) - msg = {:toEmail => message.to.first, :subject => message.subject, :fromEmail => AppConfig[:smtp_sender_address], :fromName => from_header_parse(message[:from].to_s)} + msg = {:toEmail => message.to.first, :subject => message.subject, :fromEmail => AppConfig.mail.sender_address, :fromName => from_header_parse(message[:from].to_s)} if message.multipart? msg[:plaintextBody] = message.text_part.body.to_s if message.text_part diff --git a/lib/rake_helpers.rb b/lib/rake_helpers.rb index f7a075277..47cd7aed6 100644 --- a/lib/rake_helpers.rb +++ b/lib/rake_helpers.rb @@ -26,8 +26,8 @@ module RakeHelpers possible_invite = Invitation.find_by_identifier(backer_email) possible_user ||= possible_invite.recipient if possible_invite.present? - admin_account = User.find_by_username(AppConfig[:admin_account]) - raise "no admin_account in application.yml" unless admin_account.present? + admin_account = User.find_by_username(AppConfig.admins.account.get) + raise "no admin account in diaspora.yml" unless admin_account.present? admin_account.invitation_code.count += num_to_process admin_account.invitation_code.save diff --git a/lib/stream/base.rb b/lib/stream/base.rb index 601cb1298..f8dd3f4ab 100644 --- a/lib/stream/base.rb +++ b/lib/stream/base.rb @@ -124,10 +124,6 @@ class Stream::Base @contacts_in_stream ||= Contact.where(:user_id => user.id, :person_id => people.map{|x| x.id}).all end - def spotlight_diaspora_id - @spotlight_diaspora_id ||= AppConfig[:community_spotlight].try(:sample, 1) - end - # @param post [Post] # @return [Boolean] def post_is_from_contact?(post) diff --git a/lib/stream/multi.rb b/lib/stream/multi.rb index d6264da4c..319f726c9 100644 --- a/lib/stream/multi.rb +++ b/lib/stream/multi.rb @@ -77,6 +77,6 @@ class Stream::Multi < Stream::Base # @return [Boolean] def include_community_spotlight? - AppConfig[:community_spotlight].present? && user.show_community_spotlight_in_stream? + AppConfig.environment.community_spotlight.enable? && user.show_community_spotlight_in_stream? end end diff --git a/lib/tasks/db.rake b/lib/tasks/db.rake index e2d90b969..f87ecfae6 100644 --- a/lib/tasks/db.rake +++ b/lib/tasks/db.rake @@ -70,7 +70,7 @@ namespace :db do require File.join(File.dirname(__FILE__), '..', '..', 'config', 'environment') Person.where(:url => 'example.org').all.each{|person| if person.owner - person.url = AppConfig[:pod_url] + person.url = AppConfig.environment.url person.diaspora_handle = person.owner.diaspora_handle person.save end diff --git a/lib/tasks/heroku.rake b/lib/tasks/heroku.rake index 174654ed2..87ed08c09 100644 --- a/lib/tasks/heroku.rake +++ b/lib/tasks/heroku.rake @@ -2,8 +2,6 @@ #licensed under the Affero General Public License version 3 or later. See #the COPYRIGHT file. -require Rails.root.join('lib', 'environment_configuration') - namespace :heroku do HEROKU_CONFIG_ADD_COMMAND = "heroku config:add" @@ -23,14 +21,14 @@ namespace :heroku do task :set_up_s3_sync => [:environment] do fog_provider = "FOG_PROVIDER=AWS" - aws_access_key_id = "AWS_ACCESS_KEY_ID=#{AppConfig[:s3_key]}" - aws_secret_access_key = "AWS_SECRET_ACCESS_KEY=#{AppConfig[:s3_secret]}" - fog = "FOG_DIRECTORY=#{AppConfig[:s3_bucket]}" - asset_host = "ASSET_HOST=https://#{AppConfig[:s3_bucket]}.s3.amazonaws.com" + aws_access_key_id = "AWS_ACCESS_KEY_ID=#{AppConfig.environment.s3.key}" + aws_secret_access_key = "AWS_SECRET_ACCESS_KEY=#{AppConfig.environment.s3.secret}" + fog = "FOG_DIRECTORY=#{AppConfig.environment.s3.bucket}" + asset_host = "ASSET_HOST=https://#{AppConfig.environment.s3.bucket}.s3.amazonaws.com" each_heroku_app do |stage| system("heroku labs:enable user_env_compile -a #{stage.app}") stage.run('config:add', "#{fog} #{fog_provider} #{aws_secret_access_key} #{aws_access_key_id} ASSET_HOST=#{asset_host}") end end -end \ No newline at end of file +end diff --git a/lib/tasks/migrations.rake b/lib/tasks/migrations.rake index be1acc84f..f0b8498d0 100644 --- a/lib/tasks/migrations.rake +++ b/lib/tasks/migrations.rake @@ -49,10 +49,10 @@ namespace :migrations do task :upload_photos_to_s3 do require File.join(File.dirname(__FILE__), '..', '..', 'config', 'environment') - puts AppConfig[:s3_key] + puts AppConfig.environment.s3.key - connection = Aws::S3.new( AppConfig[:s3_key], AppConfig[:s3_secret]) - bucket = connection.bucket('joindiaspora') + connection = Aws::S3.new( AppConfig.environment.s3.key, AppConfig.environment.s3.secret) + bucket = connection.bucket(AppConfig.environment.s3.bucket) dir_name = File.dirname(__FILE__) + "/../../public/uploads/images/" count = Dir.foreach(dir_name).count diff --git a/script/get_config.rb b/script/get_config.rb index d194ddfa4..51d5021e3 100755 --- a/script/get_config.rb +++ b/script/get_config.rb @@ -19,6 +19,7 @@ class Rails end end + if ARGV.length >= 1 setting_name = ARGV[0] if Rails.env == 'script_server' # load from the special script_server_config.yml file @@ -34,17 +35,13 @@ if ARGV.length >= 1 else # load from the general diaspora settings file require 'active_support/core_ext/class/attribute_accessors' require 'active_support/core_ext/object/blank' - require 'settingslogic' - require Rails.root.join('app', 'models', 'app_config') - setting_name = setting_name.to_sym - if (!AppConfig.respond_to?(setting_name) || AppConfig.send(setting_name).nil?) && AppConfig[setting_name].nil? - $stderr.puts "Could not find setting #{ARGV[0]} for environment #{Rails.env}." - Process.exit(1) - elsif AppConfig.respond_to?(setting_name) - print AppConfig.send(setting_name) - else - print AppConfig[setting_name] - end + require 'active_support/core_ext/module/delegation' + require 'active_support/core_ext/module/method_names' + require Rails.root.join("config/load_config") + + setting = AppConfig.send(setting_name) + setting = setting.get if setting.is_a?(Configuration::Proxy) + print setting end else $stderr.puts "Usage: ./script/get_config.rb option [section]" diff --git a/script/server b/script/server index c2dc1e280..c961d7b69 100755 --- a/script/server +++ b/script/server @@ -27,8 +27,8 @@ fi # Check if application.yml exists -if [ ! -e 'config/application.yml' ]; then - echo 'FATAL: config/application.yml is missing! Copy over config/application.yml.example to config/application.yml and edit it properly!' >&2 +if [ ! -e 'config/diaspora.yml' ]; then + echo 'FATAL: config/diaspora.yml is missing! Copy over config/diaspora.yml.example to config/diaspora.yml and edit it properly!' >&2 exit 70 fi @@ -91,19 +91,19 @@ if [ ! -e public/source.tar.gz ]; then fi -# Jammit notice if [ ! -e 'public/assets/default.css' ]; then if [ "$RAILS_ENV" == 'production' ]; then - echo "INFO: If you want further performance improvements," >&2 - echo "after each git pull before you restart the application, run:" >&2 + echo "FATAL: You're running in production mode without having assets precompiled." >&2 + echo "Now and after each git pull before you restart the application, run:" >&2 echo "bundle exec rake assets:precompile" >&2 + exit 71 fi fi # Start Diaspora -if [ "$(bundle exec ruby ./script/get_config.rb 'single_process_mode?')" != "true" ]; then +if [ "$(bundle exec ruby ./script/get_config.rb 'environment.single_process_mode?')" != "true" ]; then QUEUE=* bundle exec rake resque:work& fi diff --git a/spec/controllers/application_controller_spec.rb b/spec/controllers/application_controller_spec.rb index cad61acf6..39003b0ab 100644 --- a/spec/controllers/application_controller_spec.rb +++ b/spec/controllers/application_controller_spec.rb @@ -19,14 +19,20 @@ describe ApplicationController do end end - describe '#set_git_headers' do + describe '#set_diaspora_headers' do + it 'sets the version header' do + get :index + response.headers['X-Diaspora-Version'].should include AppConfig.version.number.get + end + context 'with git info' do before do - AppConfig[:git_update] = 'yesterday' - AppConfig[:git_revision] = '02395' + AppConfig.stub(:git_available?).and_return(true) + AppConfig.stub(:git_update).and_return('yesterday') + AppConfig.stub(:git_revision).and_return('02395') end - it 'sets the git header if there is git info' do + it 'sets the git header' do get :index response.headers['X-Git-Update'].should == 'yesterday' response.headers['X-Git-Revision'].should == '02395' diff --git a/spec/controllers/invitations_controller_spec.rb b/spec/controllers/invitations_controller_spec.rb index 300ab78af..413bbe822 100644 --- a/spec/controllers/invitations_controller_spec.rb +++ b/spec/controllers/invitations_controller_spec.rb @@ -7,7 +7,7 @@ require 'spec_helper' describe InvitationsController do before do - AppConfig[:open_invitations] = true + AppConfig.settings.invitations.open = true @user = alice @invite = {'email_inviter' => {'message' => "test", 'emails' => "abc@example.com"}} end @@ -27,12 +27,12 @@ describe InvitationsController do end it "redirects if invitations are closed" do - open_bit = AppConfig[:open_invitations] - AppConfig[:open_invitations] = false + open_bit = AppConfig.settings.invitations.open? + AppConfig.settings.invitations.open = false post :create, @invite response.should be_redirect - AppConfig[:open_invitations] = open_bit + AppConfig.settings.invitations.open = open_bit end it 'returns to the previous page on success' do diff --git a/spec/controllers/registrations_controller_spec.rb b/spec/controllers/registrations_controller_spec.rb index d809d3c58..524aef41e 100644 --- a/spec/controllers/registrations_controller_spec.rb +++ b/spec/controllers/registrations_controller_spec.rb @@ -21,11 +21,11 @@ describe RegistrationsController do describe '#check_registrations_open!' do before do - AppConfig[:registrations_closed] = true + AppConfig.settings.enable_registrations = false end after do - AppConfig[:registrations_closed] = false + AppConfig.settings.enable_registrations = true end it 'redirects #new to the login page' do @@ -57,7 +57,7 @@ describe RegistrationsController do describe "#create" do context "with valid parameters" do before do - AppConfig[:registrations_closed] = false + AppConfig.settings.enable_registrations = true end before do diff --git a/spec/controllers/streams_controller_spec.rb b/spec/controllers/streams_controller_spec.rb index 7b1cdef12..e6735f4a5 100644 --- a/spec/controllers/streams_controller_spec.rb +++ b/spec/controllers/streams_controller_spec.rb @@ -17,29 +17,13 @@ describe StreamsController do end it 'will redirect if not' do - AppConfig[:admins] = [] get :public response.should be_redirect end end describe '#multi' do - before do - @old_spotlight_value = AppConfig[:community_spotlight] - end - - after do - AppConfig[:community_spotlight] = @old_spotlight_value - end - it 'succeeds' do - AppConfig[:community_spotlight] = [bob.person.diaspora_handle] - get :multi - response.should be_success - end - - it 'succeeds without AppConfig[:community_spotlight]' do - AppConfig[:community_spotlight] = nil get :multi response.should be_success end diff --git a/spec/factories.rb b/spec/factories.rb index 9130f3259..5062653cb 100644 --- a/spec/factories.rb +++ b/spec/factories.rb @@ -28,7 +28,7 @@ FactoryGirl.define do factory :person do sequence(:diaspora_handle) { |n| "bob-person-#{n}#{r_str}@example.net" } - sequence(:url) { |n| AppConfig[:pod_url] } + sequence(:url) { |n| AppConfig.environment.url.get } serialized_public_key OpenSSL::PKey::RSA.generate(1024).public_key.export after(:build) do |person| person.profile = FactoryGirl.build(:profile, :person => person) unless person.profile.first_name.present? @@ -170,7 +170,7 @@ FactoryGirl.define do factory(:activity_streams_photo, :class => ActivityStreams::Photo) do association(:author, :factory => :person) - image_url "#{AppConfig[:pod_url]}/assets/asterisk.png" + image_url "#{AppConfig.environments.url}/assets/asterisk.png" image_height 154 image_width 154 object_url "http://example.com/awesome_things.gif" diff --git a/spec/fixtures/config/old_style_app.yml b/spec/fixtures/config/old_style_app.yml deleted file mode 100644 index f2ca7c172..000000000 --- a/spec/fixtures/config/old_style_app.yml +++ /dev/null @@ -1,108 +0,0 @@ -# Copyright (c) 2010-2011, Diaspora Inc. This file is -# licensed under the Affero General Public License version 3 or later. See -# the COPYRIGHT file. - -default: - - # Hostname of this host, as seen from the internet. - pod_url: "http://localhost:3000" - - # Set this to true in order to close signups. Users will still be - # able to invite other people to join. - registrations_closed: false - - # Enable extensive logging to log/{development,test,production}.log - debug: false - - # Diaspora is only tested against this default pubsub server. - pubsub_server: 'https://pubsubhubbub.appspot.com/' - - # Setting this to true enables diaspora's "send email" functionality - # requiring meaningful smtp_* settings. These are options for RoR's - # ActionMailer class. - mailer_on: false - - # This chooses which mailer should be used. 'smtp' for a smtp - # connection or 'sendmail' to use the sendmail binary. - mailer_method: 'smtp' - - # Address/port to smtp server handing outgoing mail. - smtp_address: 'smtp.example.com' - smtp_port: '587' - - # Domain administered of smtp server. - smtp_domain: 'example.com' - - # Sender address in diaspora's outgoing mail. - smtp_sender_address: 'no-reply@joindiaspora.com' - - # Authentication required to send mail. Use one of 'none','plain', - # 'login' or 'cram-md5'. Use 'none' if server does not support - # authentication - smtp_authentication: 'plain' - - # Automatically enable TLS? Ignored if smtp_authentication is set to none - smtp_starttls_auto: true - - # Credentails possibly required to log in to SMTP server if - # smtp_authentication != 'none' - smtp_username: 'smtp_username' - smtp_password: 'secret' - - # The path to the sendmail binary. - sendmail_location: '/usr/sbin/sendmail' - - #google analytics key, if false, it won't include the javascript - google_a_site: false - - #piwik integration if not set, no javascript included - piwik_id: - # the site url in raw format (e.g. pikwik.examplehost.com) - piwik_url: - - - #cloudfiles username and api-key, used for backups - cloudfiles_username: 'example' - cloudfiles_api_key: 'abc123' - invites_off: false - - #list of users who have admin privileges - admins: - - 'example_user1dsioaioedfhgoiesajdigtoearogjaidofgjo' - - #s3 config, if set, carrierwave will store your photos on s3 - #s3_key: 'key' - #s3_secret: 'secret' - #s3_bucket: 'my_photos' - s3_region: 'us-east-1' - - # If you want normal Rails logs, set this to false in the appropriate environment. - # It is false by default in development and test. - enable_splunk_logging: true - - # Process jobs in process? - single_process_mode: true - -# Use this sections to overide settings from default in the specific environments -development: - enable_splunk_logging: false - -production: - single_process_mode: false - -# Do not touch unless you know what you're doing -test: - pod_url: "http://example.org/" - enable_splunk_logging: false - - -# This section is special, you cannot overide settings from here in the above sections -script_server: - # Port on which thin should listen - thin_port: 3000 - - # customize thins startup - default_thin_args: "-p $THIN_PORT -e $RAILS_ENV" - - # Possibilties are development, production - rails_env: "development" diff --git a/spec/helpers/application_helper_spec.rb b/spec/helpers/application_helper_spec.rb index 4697feea4..9980a48e6 100644 --- a/spec/helpers/application_helper_spec.rb +++ b/spec/helpers/application_helper_spec.rb @@ -30,13 +30,18 @@ describe ApplicationHelper do describe "#all_services_connected?" do before do - AppConfig[:configured_services] = [1, 2, 3] + @old_configured_services = AppConfig.configured_services + AppConfig.configured_services = [1, 2, 3] def current_user @current_user end @current_user = alice end + + after do + AppConfig.configured_services = @old_configured_services + end it 'returns true if all networks are connected' do 3.times { |t| @current_user.services << FactoryGirl.build(:service) } @@ -52,7 +57,7 @@ describe ApplicationHelper do describe "#jquery_include_tag" do describe "with google cdn" do before do - AppConfig[:jquery_cdn] = true + AppConfig.privacy.jquery_cdn = true end it 'inclues jquery.js from google cdn' do @@ -66,7 +71,7 @@ describe ApplicationHelper do describe "without google cdn" do before do - AppConfig[:jquery_cdn] = false + AppConfig.privacy.jquery_cdn = false end it 'includes jquery.js from asset pipeline' do @@ -89,11 +94,11 @@ describe ApplicationHelper do pod_name.should match /DIASPORA/i end - it 'displays the supplied AppConfig[:pod_name] if it is set' do - old_name = AppConfig[:pod_name] - AppConfig[:pod_name] = "Catspora" + it 'displays the supplied pod_name if it is set' do + old_name = AppConfig.settings.pod_name.get + AppConfig.settings.pod_name = "Catspora" pod_name.should == "Catspora" - AppConfig[:pod_name] = old_name + AppConfig.settings.pod_name = old_name end end end diff --git a/spec/helpers/people_helper_spec.rb b/spec/helpers/people_helper_spec.rb index 59a40f14b..98f461a8c 100644 --- a/spec/helpers/people_helper_spec.rb +++ b/spec/helpers/people_helper_spec.rb @@ -98,7 +98,7 @@ describe PeopleHelper do @user.username = "invalid.username" @user.save(:validate => false).should == true person = @user.person - person.diaspora_handle = "#{@user.username}@#{AppConfig[:pod_uri].authority}" + person.diaspora_handle = "#{@user.username}@#{AppConfig.pod_uri.authority}" person.save! local_or_remote_person_path(@user.person).should == person_path(@user.person) diff --git a/spec/lib/configuration/lookup_chain_spec.rb b/spec/lib/configuration/lookup_chain_spec.rb new file mode 100644 index 000000000..272106dc3 --- /dev/null +++ b/spec/lib/configuration/lookup_chain_spec.rb @@ -0,0 +1,67 @@ +require 'spec_helper' + +class InvalidConfigurationProvider; end +class ValidConfigurationProvider + def lookup(setting, *args); end +end + +describe Configuration::LookupChain do + subject { described_class.new } + + describe "#add_provider" do + it "adds a valid provider" do + expect { + subject.add_provider ValidConfigurationProvider + }.to change { subject.instance_variable_get(:@provider).size }.by 1 + end + + it "doesn't add an invalid provider" do + expect { + subject.add_provider InvalidConfigurationProvider + }.to raise_error ArgumentError + end + + it "passes extra args to the provider" do + ValidConfigurationProvider.should_receive(:new).with(:extra) + subject.add_provider ValidConfigurationProvider, :extra + end + end + + describe "#lookup" do + before(:all) do + subject.add_provider ValidConfigurationProvider + subject.add_provider ValidConfigurationProvider + @provider = subject.instance_variable_get(:@provider) + end + + it "it tries all providers" do + setting = "some.setting" + @provider.each do |provider| + provider.should_receive(:lookup).with(setting).and_raise(Configuration::SettingNotFoundError) + end + + subject.lookup(setting) + end + + it "stops if a value is found" do + @provider[0].should_receive(:lookup).and_return("something") + @provider[1].should_not_receive(:lookup) + subject.lookup("bla") + end + + it "converts numbers to strings" do + @provider[0].stub(:lookup).and_return(5) + subject.lookup("foo").should == "5" + end + + it "does not convert false to a string" do + @provider[0].stub(:lookup).and_return(false) + subject.lookup("enable").should be_false + end + + it "returns nil if no value is found" do + @provider.each { |p| p.stub(:lookup).and_raise(Configuration::SettingNotFoundError) } + subject.lookup("not.me").should be_nil + end + end +end diff --git a/spec/lib/configuration/methods_spec.rb b/spec/lib/configuration/methods_spec.rb new file mode 100644 index 000000000..352664d42 --- /dev/null +++ b/spec/lib/configuration/methods_spec.rb @@ -0,0 +1,141 @@ +require 'spec_helper' + +describe Configuration::Methods do + before(:all) do + @settings = Configuration::Settings.create do + add_provider Configuration::Provider::Dynamic + add_provider Configuration::Provider::Env + extend Configuration::Methods + end + end + + describe "#pod_uri" do + it "properly parses the pod url" do + @settings.environment.url = "http://example.org/" + @settings.pod_uri.scheme.should == "http" + @settings.pod_uri.host.should == "example.org" + end + end + + describe "#bare_pod_uri" do + it 'is #pod_uri.authority stripping www.' do + pod_uri = mock + @settings.stub(:pod_uri).and_return(pod_uri) + pod_uri.should_receive(:authority).and_return("www.example.org") + @settings.bare_pod_uri.should == 'example.org' + end + end + + describe "#configured_services" do + it "includes the enabled services only" do + services = mock + enabled = mock + enabled.stub(:enable?).and_return(true) + disabled = mock + disabled.stub(:enable?).and_return(false) + services.stub(:twitter).and_return(enabled) + services.stub(:tumblr).and_return(enabled) + services.stub(:facebook).and_return(disabled) + @settings.stub(:services).and_return(services) + @settings.configured_services.should include :twitter + @settings.configured_services.should include :tumblr + @settings.configured_services.should_not include :facebook + end + end + + describe "#version_string" do + before do + @version = mock + @version.stub(:number).and_return("0.0.0.0") + @version.stub(:release?).and_return(true) + @settings.stub(:version).and_return(@version) + @settings.stub(:git_available?).and_return(false) + @settings.instance_variable_set(:@version_string, nil) + end + + it "includes the version" do + @settings.version_string.should include @version.number + end + + context "on a non release" do + before do + @version.stub(:release?).and_return(false) + end + + it "includes pre" do + @settings.version_string.should include "pre" + end + end + + context "with git available" do + before do + @settings.stub(:git_available?).and_return(true) + @settings.stub(:git_revision).and_return("1234567890") + end + + it "includes the 'patchlevel'" do + @settings.version_string.should include "-p#{@settings.git_revision[0..7]}" + @settings.version_string.should_not include @settings.git_revision[0..8] + end + end + end + + describe "#get_redis_instance" do + context "with REDISTOGO_URL set" do + before do + ENV["REDISTOGO_URL"] = "redis://myserver" + end + + it "uses that" do + @settings.get_redis_instance.client.host.should == "myserver" + end + end + + context "with REDIS_URL set" do + before do + ENV["REDISTOGO_URL"] = nil + ENV["REDIS_URL"] = "redis://yourserver" + end + + it "uses that" do + @settings.get_redis_instance.client.host.should == "yourserver" + end + end + + context "with redis set" do + before do + ENV["REDISTOGO_URL"] = nil + ENV["REDIS_URL"] = nil + @settings.environment.redis = "redis://ourserver" + end + + it "uses that" do + @settings.get_redis_instance.client.host.should == "ourserver" + end + end + + context "with nothing set" do + before do + @settings.environment.redis = nil + ENV["REDISTOGO_URL"] = nil + ENV["REDIS_URL"] = nil + end + + it "uses localhost" do + @settings.get_redis_instance.client.host.should == "127.0.0.1" + end + end + + context "with a unix socket set" do + before do + ENV["REDISTOGO_URL"] = nil + ENV["REDIS_URL"] = nil + @settings.environment.redis = "unix:///tmp/redis.sock" + end + + it "uses that" do + @settings.get_redis_instance.client.path.should == "/tmp/redis.sock" + end + end + end +end diff --git a/spec/lib/configuration/provider/dynamic_spec.rb b/spec/lib/configuration/provider/dynamic_spec.rb new file mode 100644 index 000000000..937dd00e2 --- /dev/null +++ b/spec/lib/configuration/provider/dynamic_spec.rb @@ -0,0 +1,23 @@ +require 'spec_helper' + +describe Configuration::Provider::Dynamic do + subject { described_class.new } + describe "#lookup_path" do + it "returns nil if the setting was never set" do + subject.lookup_path(["not_me"]).should be_nil + end + + it "remembers the setting if it ends with =" do + subject.lookup_path(["find_me", "later="], "there") + subject.lookup_path(["find_me", "later"]).should == "there" + end + + it "calls .get on the argument if a proxy object is given" do + proxy = mock + proxy.stub(:respond_to?).and_return(true) + proxy.stub(:_proxy?).and_return(true) + proxy.should_receive(:get) + subject.lookup_path(["bla="], proxy) + end + end +end diff --git a/spec/lib/configuration/provider/env_spec.rb b/spec/lib/configuration/provider/env_spec.rb new file mode 100644 index 000000000..0bc5eaa56 --- /dev/null +++ b/spec/lib/configuration/provider/env_spec.rb @@ -0,0 +1,32 @@ +require 'spec_helper' + +describe Configuration::Provider::Env do + subject { described_class.new } + let(:existing_path) { ['existing', 'setting']} + let(:not_existing_path) { ['not', 'existing', 'path']} + let(:array_path) { ['array'] } + before(:all) do + ENV['EXISTING_SETTING'] = "there" + ENV['ARRAY'] = "foo,bar,baz" + end + + after(:all) do + ENV['EXISTING_SETTING'] = nil + ENV['ARRAY'] = nil + end + + describe '#lookup_path' do + it "joins and upcases the path" do + ENV.should_receive(:[]).with("EXISTING_SETTING") + subject.lookup_path(existing_path) + end + + it "returns nil if the setting isn't available" do + subject.lookup_path(not_existing_path).should be_nil + end + + it "makes an array out of comma separated values" do + subject.lookup_path(array_path).should == ["foo", "bar", "baz"] + end + end +end diff --git a/spec/lib/configuration/provider/yaml_spec.rb b/spec/lib/configuration/provider/yaml_spec.rb new file mode 100644 index 000000000..ea4da964d --- /dev/null +++ b/spec/lib/configuration/provider/yaml_spec.rb @@ -0,0 +1,72 @@ +require 'spec_helper' + +describe Configuration::Provider::YAML do + let(:settings) { {"toplevel" => "bar", + "some" => { + "nested" => { "some" => "lala", "setting" => "foo"} + } + } } + + describe "#initialize" do + it "loads the file" do + file = "foobar.yml" + ::YAML.should_receive(:load_file).with(file).and_return({}) + described_class.new file + end + + it "raises if the file is not found" do + ::YAML.stub(:load_file).and_raise(Errno::ENOENT) + expect { + described_class.new "foo" + }.to raise_error Errno::ENOENT + end + + + context "with a namespace" do + it "looks in the file for that namespace" do + namespace = "some" + ::YAML.stub(:load_file).and_return(settings) + provider = described_class.new 'bla', namespace: namespace + provider.instance_variable_get(:@settings).should == settings[namespace] + end + + it "raises if the namespace isn't found" do + ::YAML.stub(:load_file).and_return({}) + expect { + described_class.new 'bla', namespace: "foo" + }.to raise_error ArgumentError + end + end + + context "with required set to false" do + it "doesn't raise if a file isn't found" do + ::YAML.stub(:load_file).and_raise(Errno::ENOENT) + expect { + described_class.new "not_me", required: false + }.not_to raise_error Errno::ENOENT + end + + it "doesn't raise if a namespace isn't found" do + ::YAML.stub(:load_file).and_return({}) + expect { + described_class.new 'bla', namespace: "foo", required: false + }.not_to raise_error ArgumentError + end + end + end + + describe "#lookup_path" do + before do + ::YAML.stub(:load_file).and_return(settings) + @provider = described_class.new 'dummy' + end + + it "looks up the whole nesting" do + @provider.lookup_path(["some", "nested", "some"]).should == settings["some"]["nested"]["some"] + end + + it "returns nil if no setting is found" do + @provider.lookup_path(["not_me"]).should be_nil + end + end +end diff --git a/spec/lib/configuration/provider_spec.rb b/spec/lib/configuration/provider_spec.rb new file mode 100644 index 000000000..12cba2491 --- /dev/null +++ b/spec/lib/configuration/provider_spec.rb @@ -0,0 +1,18 @@ +require 'spec_helper' + +describe Configuration::Provider::Base do + subject { described_class.new } + describe "#lookup" do + it "calls #lookup_path with the setting as array" do + subject.should_receive(:lookup_path).with(["foo", "bar"]).and_return("something") + subject.lookup("foo.bar").should == "something" + end + + it "raises SettingNotFoundError if the #lookup_path returns nil" do + subject.should_receive(:lookup_path).and_return(nil) + expect { + subject.lookup("bla") + }.to raise_error Configuration::SettingNotFoundError + end + end +end diff --git a/spec/lib/configuration/proxy_spec.rb b/spec/lib/configuration/proxy_spec.rb new file mode 100644 index 000000000..950112d2f --- /dev/null +++ b/spec/lib/configuration/proxy_spec.rb @@ -0,0 +1,56 @@ +require 'spec_helper' + +describe Configuration::Proxy do + let(:lookup_chain) { mock } + before do + lookup_chain.stub(:lookup).and_return("something") + end + + describe "#method_missing" do + it "calls #get if the method ends with a ?" do + lookup_chain.should_receive(:lookup).with("enable").and_return(false) + described_class.new(lookup_chain).method_missing(:enable?) + end + + it "calls #get if the method ends with a =" do + lookup_chain.should_receive(:lookup).with("url=").and_return(false) + described_class.new(lookup_chain).method_missing(:url=) + end + end + + describe "#get" do + [:to_str, :to_s, :to_xml, :respond_to?, :present?, :!=, + :each, :try, :size, :length, :count, :==, :=~, :gsub, :blank?, :chop, + :start_with?, :end_with?].each do |method| + it "is called for accessing #{method} on the proxy" do + target = mock + lookup_chain.should_receive(:lookup).and_return(target) + target.should_receive(method).and_return("something") + described_class.new(lookup_chain).something.__send__(method, mock) + end + end + + described_class::COMMON_KEY_NAMES.each do |method| + it "is not called for accessing #{method} on the proxy" do + target = mock + lookup_chain.should_not_receive(:lookup).and_return(target) + target.should_not_receive(method).and_return("something") + described_class.new(lookup_chain).something.__send__(method, mock) + end + end + + it "strips leading dots" do + lookup_chain.should_receive(:lookup).with("foo.bar").and_return("something") + described_class.new(lookup_chain).foo.bar.get + end + + it "returns nil if no setting is given" do + described_class.new(lookup_chain).get.should be_nil + end + + it "strips ? at the end" do + lookup_chain.should_receive(:lookup).with("foo.bar").and_return("something") + described_class.new(lookup_chain).foo.bar? + end + end +end diff --git a/spec/lib/configuration_spec.rb b/spec/lib/configuration_spec.rb new file mode 100644 index 000000000..f75619541 --- /dev/null +++ b/spec/lib/configuration_spec.rb @@ -0,0 +1,25 @@ +require 'spec_helper' + +describe Configuration::Settings do + describe "#method_missing" do + subject { described_class.create } + + it "delegates the call to a new proxy object" do + proxy = mock + Configuration::Proxy.should_receive(:new).and_return(proxy) + proxy.should_receive(:method_missing).with(:some_setting).and_return("foo") + subject.some_setting + end + end + + [:lookup, :add_provider, :[]].each do |method| + describe "#{method}" do + subject { described_class.create } + + it "delegates the call to #lookup_chain" do + subject.lookup_chain.should_receive(method) + subject.send(method) + end + end + end +end diff --git a/spec/lib/rake_helper_spec.rb b/spec/lib/rake_helper_spec.rb index 430fe17ef..77fd6e198 100644 --- a/spec/lib/rake_helper_spec.rb +++ b/spec/lib/rake_helper_spec.rb @@ -12,12 +12,12 @@ describe RakeHelpers do describe '#process_emails' do before do Devise.mailer.deliveries = [] - @old_admin = AppConfig[:admin_account] - AppConfig[:admin_account] = FactoryGirl.create(:user).username + @old_admin = AppConfig.admins.account.get + AppConfig.admins.account = FactoryGirl.create(:user).username end after do - AppConfig[:admin_account] = @old_admin + AppConfig.admins.account = @old_admin end it 'should send emails to each email' do diff --git a/spec/lib/webfinger_spec.rb b/spec/lib/webfinger_spec.rb index b8a7dfe89..34cac08f9 100644 --- a/spec/lib/webfinger_spec.rb +++ b/spec/lib/webfinger_spec.rb @@ -11,7 +11,7 @@ describe Webfinger do let(:account){'foo@bar.com'} let(:account_in_fixtures){"alice@localhost:9887"} let(:finger){Webfinger.new(account)} - let(:host_meta_url){"http://#{AppConfig[:pod_uri].authority}/webfinger?q="} + let(:host_meta_url){"http://#{AppConfig.pod_uri.authority}/webfinger?q="} describe '#intialize' do it 'sets account ' do diff --git a/spec/mailers/notifier_spec.rb b/spec/mailers/notifier_spec.rb index 98da0cc6d..fab09a643 100644 --- a/spec/mailers/notifier_spec.rb +++ b/spec/mailers/notifier_spec.rb @@ -190,7 +190,7 @@ describe Notifier do end it "FROM: contains the sender's name" do - @mail["From"].to_s.should == "\"#{@cnv.author.name} (Diaspora*)\" <#{AppConfig[:smtp_sender_address]}>" + @mail["From"].to_s.should == "\"#{@cnv.author.name} (Diaspora*)\" <#{AppConfig.mail.sender_address}>" end it 'SUBJECT: has a snippet of the post contents' do @@ -225,7 +225,7 @@ describe Notifier do end it "FROM: contains the sender's name" do - comment_mail["From"].to_s.should == "\"#{eve.name} (Diaspora*)\" <#{AppConfig[:smtp_sender_address]}>" + comment_mail["From"].to_s.should == "\"#{eve.name} (Diaspora*)\" <#{AppConfig.mail.sender_address}>" end it 'SUBJECT: has a snippet of the post contents' do @@ -266,7 +266,7 @@ describe Notifier do end it 'FROM: has the name of person commenting as the sender' do - comment_mail["From"].to_s.should == "\"#{eve.name} (Diaspora*)\" <#{AppConfig[:smtp_sender_address]}>" + comment_mail["From"].to_s.should == "\"#{eve.name} (Diaspora*)\" <#{AppConfig.mail.sender_address}>" end it 'SUBJECT: has a snippet of the post contents' do diff --git a/spec/models/app_config_spec.rb b/spec/models/app_config_spec.rb deleted file mode 100644 index bc37389f9..000000000 --- a/spec/models/app_config_spec.rb +++ /dev/null @@ -1,257 +0,0 @@ -# Copyright (c) 2010-2011, Diaspora Inc. This file is -# licensed under the Affero General Public License version 3 or later. See -# the COPYRIGHT file. - -require 'spec_helper' - -describe AppConfig do - - after do - AppConfig.reload! - AppConfig.setup! - end - - describe ".load!" do - context "error conditions" do - before do - @original_stderr = $stderr - $stderr = StringIO.new - end - after do - $stderr = @original_stderr - end - - context "with old-style application.yml" do - before do - @original_source = AppConfig.source - AppConfig.source(Rails.root.join("spec", "fixtures", "config", "old_style_app.yml")) - end - after do - AppConfig.source(@original_source) - end - it "prints an error message and exits" do - expect { - AppConfig.load! - }.to raise_error SystemExit - - $stderr.rewind - $stderr.string.chomp.should_not be_blank - end - end - - context "when source config file (i.e. config/application.yml) does not exist" do - before do - application_yml = AppConfig.source_file_name - @app_yml = Rails.root.join("config", "app.yml") - @app_config_yml = Rails.root.join("config", "app_config.yml") - File.should_receive(:exists?).with(application_yml).at_least(:once).and_return(false) - end - after do - File.instance_eval { alias :exists? :obfuscated_by_rspec_mocks__exists? } # unmock exists? so that the AppConfig.reload! in the top-level after block can run - AppConfig.source(AppConfig.source_file_name) - end - context "and there are no old-style config files around" do - it "prints an error message with instructions for setting up application.yml and exits" do - File.should_receive(:exists?).with(@app_yml).at_least(:once).and_return(false) - File.should_receive(:exists?).with(@app_config_yml).at_least(:once).and_return(false) - - expect { - AppConfig.load! - }.to raise_error SystemExit - - $stderr.rewind - $stderr.string.should include("haven't set up") - end - end - context "and there is an old-style app.yml" do - it "prints an error message with instructions for converting an old-style file and exits" do - File.should_receive(:exists?).with(@app_yml).at_least(:once).and_return(true) - - expect { - AppConfig.load! - }.to raise_error SystemExit - - $stderr.rewind - $stderr.string.should include("file format has changed") - end - end - context "and there is an old-style app_config.yml" do - it "prints an error message with instructions for converting an old-style file and exits" do - File.should_receive(:exists?).with(@app_yml).at_least(:once).and_return(false) - File.should_receive(:exists?).with(@app_config_yml).at_least(:once).and_return(true) - - expect { - AppConfig.load! - }.to raise_error SystemExit - - $stderr.rewind - $stderr.string.should include("file format has changed") - end - end - end - end - end - - describe '.setup!' do - it "calls normalize_pod_url" do - AppConfig.should_receive(:normalize_pod_url).twice - AppConfig.setup! - end - it "calls normalize_admins" do - AppConfig.should_receive(:normalize_admins).twice - AppConfig.setup! - end - end - - describe ".normalize_admins" do - it "downcases the user names that are set as admins" do - AppConfig[:admins] = ["UPPERCASE", "MiXeDCaSe", "lowercase"] - AppConfig.normalize_admins - AppConfig[:admins].should == ["uppercase", "mixedcase", "lowercase"] - end - it "sets admins to an empty array if no admins were specified" do - AppConfig[:admins] = nil - AppConfig.normalize_admins - AppConfig[:admins].should == [] - end - end - - describe ".normalize_pod_url" do - it "adds a trailing slash if there isn't one" do - AppConfig[:pod_url] = "http://example.org" - AppConfig.normalize_pod_url - AppConfig[:pod_url].should == "http://example.org/" - end - it "does not add an extra trailing slash" do - AppConfig[:pod_url] = "http://example.org/" - AppConfig.normalize_pod_url - AppConfig[:pod_url].should == "http://example.org/" - end - it "adds http:// on the front if it's missing" do - AppConfig[:pod_url] = "example.org/" - AppConfig.normalize_pod_url - AppConfig[:pod_url].should == "http://example.org/" - end - it "does not add a prefix if there already is http:// on the front" do - AppConfig[:pod_url] = "http://example.org/" - AppConfig.normalize_pod_url - AppConfig[:pod_url].should == "http://example.org/" - end - it "does not add a prefix if there already is https:// on the front" do - AppConfig[:pod_url] = "https://example.org/" - AppConfig.normalize_pod_url - AppConfig[:pod_url].should == "https://example.org/" - end - - end - - describe '.bare_pod_uri' do - it 'is AppConfig[:pod_uri].authority stripping www.' do - AppConfig[:pod_url] = "https://www.example.org/" - AppConfig.bare_pod_uri.should == 'example.org' - end - end - - describe ".pod_uri" do - it "properly parses the pod_url" do - AppConfig.pod_uri = nil - AppConfig[:pod_url] = "http://example.org" - pod_uri = AppConfig[:pod_uri] - pod_uri.scheme.should == "http" - pod_uri.host.should == "example.org" - end - end - - describe '.normalize_services' do - before do - @services = SERVICES - Object.send(:remove_const, :SERVICES) - end - - after do - SERVICES = @services - end - - it 'sets configured_services to an empty array if SERVICES is not defined' do - AppConfig.normalize_pod_services - AppConfig.configured_services.should == [] - end - end - - describe ".get_redis_instance" do - context "with REDISTOGO_URL set" do - before do - ENV["REDISTOGO_URL"] = "redis://myserver" - end - - it "uses that" do - AppConfig.get_redis_instance.client.host.should == "myserver" - end - end - - context "with REDIS_URL set" do - before do - ENV["REDISTOGO_URL"] = nil - ENV["REDIS_URL"] = "redis://yourserver" - end - - it "uses that" do - AppConfig.get_redis_instance.client.host.should == "yourserver" - end - end - - context "with redis_url set" do - before do - AppConfig[:redis_url] = "redis://ourserver" - ENV["REDISTOGO_URL"] = nil - ENV["REDIS_URL"] = nil - end - - after do - end - - it "uses that" do - AppConfig.get_redis_instance.client.host.should == "ourserver" - end - end - - context "with nothing set" do - before do - AppConfig[:redis_url] = "" - ENV["REDISTOGO_URL"] = nil - ENV["REDIS_URL"] = nil - end - - it "uses localhost" do - AppConfig.get_redis_instance.client.host.should == "127.0.0.1" - end - end - end - - describe ".[]=" do - describe "when setting pod_url" do - context "with a symbol" do - it "clears the cached pod_uri" do - AppConfig[:pod_uri].host.should_not == "joindiaspora.com" - AppConfig[:pod_url] = "http://joindiaspora.com" - AppConfig[:pod_uri].host.should == "joindiaspora.com" - end - it "calls normalize_pod_url" do - AppConfig.should_receive(:normalize_pod_url).twice - AppConfig[:pod_url] = "http://joindiaspora.com" - end - end - context "with a string" do - it "clears the cached pod_uri" do - AppConfig[:pod_uri].host.should_not == "joindiaspora.com" - AppConfig['pod_url'] = "http://joindiaspora.com" - AppConfig[:pod_uri].host.should == "joindiaspora.com" - end - it "calls normalize_pod_url" do - AppConfig.should_receive(:normalize_pod_url).twice - AppConfig['pod_url'] = "http://joindiaspora.com" - end - end - end - end -end diff --git a/spec/models/invitation_code_spec.rb b/spec/models/invitation_code_spec.rb index 1466189b1..9596952dd 100644 --- a/spec/models/invitation_code_spec.rb +++ b/spec/models/invitation_code_spec.rb @@ -22,12 +22,12 @@ describe InvitationCode do describe '.default_inviter_or' do before do - @old_account = AppConfig[:admin_account] - AppConfig[:admin_account] = 'bob' + @old_account = AppConfig.admins.account.get + AppConfig.admins.account = 'bob' end after do - AppConfig[:admin_account] = @old_account + AppConfig.admins.account = @old_account end it 'grabs the set admin account for the pod...' do @@ -35,7 +35,7 @@ describe InvitationCode do end it '..or the given user' do - AppConfig[:admin_account] = '' + AppConfig.admins.account = '' InvitationCode.default_inviter_or(alice).username.should == 'alice' end end diff --git a/spec/models/jobs/publish_to_hub_spec.rb b/spec/models/jobs/publish_to_hub_spec.rb index 3b5b274d0..38e5e622c 100644 --- a/spec/models/jobs/publish_to_hub_spec.rb +++ b/spec/models/jobs/publish_to_hub_spec.rb @@ -12,7 +12,7 @@ describe Jobs::PublishToHub do m = mock() m.should_receive(:publish).with(url+'.atom') - Pubsubhubbub.should_receive(:new).with(AppConfig[:pubsub_server]).and_return(m) + Pubsubhubbub.should_receive(:new).with(AppConfig.environment.pubsub_server).and_return(m) Jobs::PublishToHub.perform(url) end end diff --git a/spec/models/person_spec.rb b/spec/models/person_spec.rb index 835ce945a..7ce861cb3 100644 --- a/spec/models/person_spec.rb +++ b/spec/models/person_spec.rb @@ -132,17 +132,17 @@ describe Person do end it 'does not include www if it is set in app config' do - old_url = AppConfig[:pod_url] - AppConfig[:pod_url] = 'https://www.foobar.com/' + old_url = AppConfig.environment.url.get + AppConfig.environment.url = 'https://www.foobar.com/' new_person = User.build(:username => "foo123", :email => "foo123@example.com", :password => "password", :password_confirmation => "password").person new_person.diaspora_handle.should == "foo123@foobar.com" - AppConfig[:pod_url] = old_url + AppConfig.environment.url = old_url end end context 'remote people' do it 'stores the diaspora_handle in the database' do - @person.diaspora_handle.include?(AppConfig[:pod_uri].host).should be false + @person.diaspora_handle.include?(AppConfig.pod_uri.host).should be false end end diff --git a/spec/models/profile_spec.rb b/spec/models/profile_spec.rb index 8657b8efd..fabc6815f 100644 --- a/spec/models/profile_spec.rb +++ b/spec/models/profile_spec.rb @@ -116,7 +116,7 @@ describe Profile do before do @profile = FactoryGirl.build(:profile) @profile.image_url = "http://tom.joindiaspora.com/images/user/tom.jpg" - @pod_url = (AppConfig[:pod_url][-1,1] == '/' ? AppConfig[:pod_url].chop : AppConfig[:pod_url]) + @pod_url = (AppConfig.environment.url.get[-1,1] == '/' ? AppConfig.environment.url.chop : AppConfig.environment.url) end it 'ignores an empty string' do diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 9d3772fd0..c58952587 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -98,12 +98,6 @@ Spork.prefork do end end -Spork.each_run do - # This code will be run each time you run your specs. - AppConfig.load! - AppConfig.setup! -end - # https://makandracards.com/makandra/950-speed-up-rspec-by-deferring-garbage-collection RSpec.configure do |config| config.before(:all) do diff --git a/spec/support/user_methods.rb b/spec/support/user_methods.rb index d74e8640d..e2a7038cd 100644 --- a/spec/support/user_methods.rb +++ b/spec/support/user_methods.rb @@ -1,7 +1,7 @@ class User include Rails.application.routes.url_helpers def default_url_options - {:host => AppConfig[:pod_url]} + {:host => AppConfig.environment.url} end alias_method :share_with_original, :share_with