code
stringlengths 26
124k
| docstring
stringlengths 23
125k
| func_name
stringlengths 1
98
| language
stringclasses 1
value | repo
stringlengths 5
53
| path
stringlengths 7
151
| url
stringlengths 50
211
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def setup
@datasets = [
[:Jimmy, [25, 36, 86, 39]],
[:Charles, [80, 54, 67, 54]],
[:Julie, [22, 29, 35, 38]]
]
end | TODO: Delete old output files once when starting tests | setup | ruby | topfunky/gruff | test/test_dot.rb | https://github.com/topfunky/gruff/blob/master/test/test_dot.rb | MIT |
def line_graph_with_themes(size = nil)
g = Gruff::Line.new(size)
g.title = "Multi-Line Graph Test #{size}"
g.labels = @labels
g.baseline_value = 90
@datasets.each do |data|
g.data(data[0], data[1])
end
# Default theme
g.write("test/output/line_theme_keynote_#{size}.png")
assert_same_image("test/expected/line_theme_keynote_#{size}.png", "test/output/line_theme_keynote_#{size}.png")
g = Gruff::Line.new(size)
g.title = "Multi-Line Graph Test #{size}"
g.labels = @labels
g.baseline_value = 90
g.theme = Gruff::Themes::THIRTYSEVEN_SIGNALS
@datasets.each do |data|
g.data(data[0], data[1])
end
g.write("test/output/line_theme_37signals_#{size}.png")
assert_same_image("test/expected/line_theme_37signals_#{size}.png", "test/output/line_theme_37signals_#{size}.png")
g = Gruff::Line.new(size)
g.title = "Multi-Line Graph Test #{size}"
g.labels = @labels
g.baseline_value = 90
g.theme = Gruff::Themes::RAILS_KEYNOTE
@datasets.each do |data|
g.data(data[0], data[1])
end
g.write("test/output/line_theme_rails_keynote_#{size}.png")
assert_same_image("test/expected/line_theme_rails_keynote_#{size}.png", "test/output/line_theme_rails_keynote_#{size}.png")
g = Gruff::Line.new(size)
g.title = "Multi-Line Graph Test #{size}"
g.labels = @labels
g.baseline_value = 90
g.theme = Gruff::Themes::ODEO
@datasets.each do |data|
g.data(data[0], data[1])
end
g.write("test/output/line_theme_odeo_#{size}.png")
assert_same_image("test/expected/line_theme_odeo_#{size}.png", "test/output/line_theme_odeo_#{size}.png")
end | TODO: Reset data after each theme | line_graph_with_themes | ruby | topfunky/gruff | test/test_line.rb | https://github.com/topfunky/gruff/blob/master/test/test_line.rb | MIT |
def email_for(to)
case to
# add your own name => email address mappings here
when /^#{capture_model}$/
model($1).email
when /^"(.*)"$/
$1
else
to
end
end | Maps a name to an email address. Used by email_steps | email_for | ruby | ianwhite/pickle | features/support/email.rb | https://github.com/ianwhite/pickle/blob/master/features/support/email.rb | MIT |
def path_to(page_name)
case page_name
when /the home\s?page/
'/'
# the following are examples using path_to_pickle
when /^#{capture_model}(?:'s)? page$/ # eg. the forum's page
path_to_pickle $1
when /^#{capture_model}(?:'s)? #{capture_model}(?:'s)? page$/ # eg. the forum's post's page
path_to_pickle $1, $2
when /^#{capture_model}(?:'s)? #{capture_model}'s (.+?) page$/ # eg. the forum's post's comments page
path_to_pickle $1, $2, :extra => $3 # or the forum's post's edit page
when /^#{capture_model}(?:'s)? (.+?) page$/ # eg. the forum's posts page
path_to_pickle $1, :extra => $2 # or the forum's edit page
# Add more mappings here.
# Here is an example that pulls values out of the Regexp:
#
# when /^(.*)'s profile page$/i
# user_profile_path(User.find_by_login($1))
else
begin
page_name =~ /the (.*) page/
path_components = $1.split(/\s+/)
self.send(path_components.push('path').join('_').to_sym)
rescue Object => e
raise "Can't find mapping from \"#{page_name}\" to a path.\n" +
"Now, go and add a mapping in #{__FILE__}"
end
end
end | Maps a name to a path. Used by the
When /^I go to (.+)$/ do |page_name|
step definition in web_steps.rb | path_to | ruby | ianwhite/pickle | features/support/paths.rb | https://github.com/ianwhite/pickle/blob/master/features/support/paths.rb | MIT |
def map(*args)
options = args.extract_options!
raise ArgumentError, "Usage: map 'search' [, 'search2', ...] :to => 'replace'" unless args.any? && options[:to].is_a?(String)
args.each do |search|
self.mappings << Mapping.new(search, options[:to])
end
end | Usage: map 'me', 'myself', 'I', :to => 'user: "me"' | map | ruby | ianwhite/pickle | lib/pickle/config.rb | https://github.com/ianwhite/pickle/blob/master/lib/pickle/config.rb | MIT |
def emails(fields = nil)
@emails = ActionMailer::Base.deliveries.select {|m| email_has_fields?(m, fields)}
end | return the deliveries array, optionally selected by the passed fields | emails | ruby | ianwhite/pickle | lib/pickle/email.rb | https://github.com/ianwhite/pickle/blob/master/lib/pickle/email.rb | MIT |
def save_and_open_emails
emails_to_open = @emails || emails
filename = "pickle-email-#{Time.now.to_i}.html"
File.open(filename, "w") do |f|
emails_to_open.each_with_index do |e, i|
f.write "<h1>Email #{i+1}</h1><pre>#{e}</pre><hr />"
end
end
open_in_browser(filename)
end | Saves the emails out to RAILS_ROOT/tmp/ and opens it in the default
web browser if on OS X. (depends on webrat) | save_and_open_emails | ruby | ianwhite/pickle | lib/pickle/email.rb | https://github.com/ianwhite/pickle/blob/master/lib/pickle/email.rb | MIT |
def parse_email_for_anchor_text_link(email, link_text)
if email.multipart?
body = email.html_part.body
else
body = email.body
end
if match_data = body.match(%r{<a[^>]*href=['"]?([^'"]*)['"]?[^>]*?>[^<]*?#{link_text}[^<]*?</a>})
match_data[1]
end
end | e.g. Click here in <a href="http://confirm">Click here</a> | parse_email_for_anchor_text_link | ruby | ianwhite/pickle | lib/pickle/email.rb | https://github.com/ianwhite/pickle/blob/master/lib/pickle/email.rb | MIT |
def parse_fields(fields)
if fields.blank?
{}
elsif fields =~ /^#{match_fields}$/
fields.scan(/(#{match_field})(?:,|$)/).inject({}) do |m, match|
m.merge(parse_field(match[0]))
end
else
raise ArgumentError, "The fields string is not in the correct format.\n\n'#{fields}' did not match: #{match_fields}"
end
end | given a string like 'foo: "bar", bar: "baz"' returns {"foo" => "bar", "bar" => "baz"} | parse_fields | ruby | ianwhite/pickle | lib/pickle/parser.rb | https://github.com/ianwhite/pickle/blob/master/lib/pickle/parser.rb | MIT |
def parse_field(field)
if field =~ /^#{capture_key_and_value_in_field}$/
{ $1 => eval($2) }
else
raise ArgumentError, "The field argument is not in the correct format.\n\n'#{field}' did not match: #{match_field}"
end
end | given a string like 'foo: expr' returns {key => value} | parse_field | ruby | ianwhite/pickle | lib/pickle/parser.rb | https://github.com/ianwhite/pickle/blob/master/lib/pickle/parser.rb | MIT |
def path_to_pickle(*pickle_names)
options = pickle_names.extract_options!
resources = pickle_names.map{|n| model(n) || n.to_sym}
if options[:extra]
parts = options[:extra].underscore.gsub(' ','_').split("_")
find_pickle_path_using_action_segment_combinations(resources, parts)
else
pickle_path_for_resources_action_segment(resources, options[:action], options[:segment])
end or raise "Could not figure out a path for #{pickle_names.inspect} #{options.inspect}"
end | given args of pickle model name, and an optional extra action, or segment, will attempt to find
a matching named route
path_to_pickle 'the user', :action => 'edit' # => /users/3/edit
path_to_pickle 'the user', 'the comment' # => /users/3/comments/1
path_to_pickle 'the user', :segment => 'comments' # => /users/3/comments
If you don;t know if the 'extra' part of the path is an action or a segment, then just
pass it as 'extra' and this method will run through the possibilities
path_to_pickle 'the user', :extra => 'new comment' # => /users/3/comments/new | path_to_pickle | ruby | ianwhite/pickle | lib/pickle/path.rb | https://github.com/ianwhite/pickle/blob/master/lib/pickle/path.rb | MIT |
def email_for(to)
case to
# add your own name => email address mappings here
when /^#{capture_model}$/
model($1).email
when /^"(.*)"$/
$1
else
to
end
end | Maps a name to an email address. Used by email_steps | email_for | ruby | ianwhite/pickle | rails_generators/pickle/templates/email.rb | https://github.com/ianwhite/pickle/blob/master/rails_generators/pickle/templates/email.rb | MIT |
def path_to(page_name)
case page_name
when /the home\s?page/
'/'
# the following are examples using path_to_pickle
when /^#{capture_model}(?:'s)? page$/ # eg. the forum's page
path_to_pickle $1
when /^#{capture_model}(?:'s)? #{capture_model}(?:'s)? page$/ # eg. the forum's post's page
path_to_pickle $1, $2
when /^#{capture_model}(?:'s)? #{capture_model}'s (.+?) page$/ # eg. the forum's post's comments page
path_to_pickle $1, $2, :extra => $3 # or the forum's post's edit page
when /^#{capture_model}(?:'s)? (.+?) page$/ # eg. the forum's posts page
path_to_pickle $1, :extra => $2 # or the forum's edit page
# Add more mappings here.
# Here is an example that pulls values out of the Regexp:
#
# when /^(.*)'s profile page$/i
# user_profile_path(User.find_by_login($1))
else
begin
page_name =~ /the (.*) page/
path_components = $1.split(/\s+/)
self.send(path_components.push('path').join('_').to_sym)
rescue Object => e
raise "Can't find mapping from \"#{page_name}\" to a path.\n" +
"Now, go and add a mapping in #{__FILE__}"
end
end
end | Maps a name to a path. Used by the
When /^I go to (.+)$/ do |page_name|
step definition in web_steps.rb | path_to | ruby | ianwhite/pickle | rails_generators/pickle/templates/paths.rb | https://github.com/ianwhite/pickle/blob/master/rails_generators/pickle/templates/paths.rb | MIT |
def initialize(error_code, error_msg)
@code = error_code
super("Facebook error #{error_code}: #{error_msg}")
end | Error that happens during a facebook call. | initialize | ruby | appoxy/mini_fb | lib/mini_fb.rb | https://github.com/appoxy/mini_fb/blob/master/lib/mini_fb.rb | MIT |
def graph_object(id)
MiniFB::GraphObject.new(self, id)
end | Returns a GraphObject for the given id | graph_object | ruby | appoxy/mini_fb | lib/mini_fb.rb | https://github.com/appoxy/mini_fb/blob/master/lib/mini_fb.rb | MIT |
def me
@me ||= graph_object('me')
end | Returns and caches a GraphObject for the user | me | ruby | appoxy/mini_fb | lib/mini_fb.rb | https://github.com/appoxy/mini_fb/blob/master/lib/mini_fb.rb | MIT |
def initialize(session_or_token, id)
@oauth_session = if session_or_token.is_a?(MiniFB::OAuthSession)
session_or_token
else
MiniFB::OAuthSession.new(session_or_token)
end
@id = id
@object = @oauth_session.get(id, :metadata => true)
@connections_cache = {}
end | Creates a GraphObject using an OAuthSession or access_token | initialize | ruby | appoxy/mini_fb | lib/mini_fb.rb | https://github.com/appoxy/mini_fb/blob/master/lib/mini_fb.rb | MIT |
def split
if options['url']
file = File.basename(options['url'])
File.open(file, 'wb') do |f|
url = URI.parse(options['url'])
http = Net::HTTP.new(url.host, url.port)
(http.use_ssl = true) if url.port == 443
req = Net::HTTP::Get.new(url.request_uri)
http.request(req) do |res|
res.read_body do |seg|
f << seg
sleep 0.005 # To allow the buffer to fill (more).
end
end
end
DC::Store::AssetStore.new.save_original(document, file )
else
file = File.basename document.original_file_path
File.open(file, 'wb'){ |f| f << DC::Store::AssetStore.new.read_original(document) }
end
build_pages = (document.page_count == 0 or options['rebuild'])
# Calculate the file hash for the document's original_file so that duplicates can be found
data = File.open(file, 'rb').read
attributes = {
file_size: data.bytesize,
file_hash: Digest::SHA1.hexdigest(data)
}
document.update_attributes(attributes)
if duplicate = document.duplicates.first
Rails.logger.info "Duplicate found, copying pdf"
asset_store.copy_pdf( duplicate, document, access )
document.update_attributes(page_count: duplicate.page_count) if build_pages
else
Rails.logger.info "Building PDF"
File.open(file, 'r') do |f|
DC::Import::PDFWrangler.new.ensure_pdf(f, file) do |path|
document.update_attributes(page_count: Docsplit.extract_length(file)) if build_pages
DC::Store::AssetStore.new.save_pdf(document, path, access)
end
end
end
create_pages! if build_pages
tasks = []
tasks << {'task' => 'text'} unless options['images_only']
tasks << {'task' => 'images'} unless options['text_only']
tasks
end | Split a document import job into two parallel parts ... one for the image
generation and one for the text extraction.
If the Document was not originally uploaded, but was passed as a remote URL
instead, download it first, convert it to a PDF ... then go to town. | split | ruby | documentcloud/documentcloud | app/actions/document_import.rb | https://github.com/documentcloud/documentcloud/blob/master/app/actions/document_import.rb | MIT |
def process
begin
@pdf = document.slug + '.pdf'
pdf_contents = asset_store.read_pdf document
File.open(@pdf, 'wb') {|f| f.write(pdf_contents) }
case input['task']
when 'text' then process_text
when 'images' then process_images
end
rescue Exception => e
LifecycleMailer.exception_notification(e,options).deliver_now
raise e
end
document.id
end | Process runs either the text extraction or image generation, depending on
the input. | process | ruby | documentcloud/documentcloud | app/actions/document_import.rb | https://github.com/documentcloud/documentcloud/blob/master/app/actions/document_import.rb | MIT |
def merge
document.update_attributes :access => access
email_on_complete
super
end | When both sides are done, update the document to mark it as finished. | merge | ruby | documentcloud/documentcloud | app/actions/document_import.rb | https://github.com/documentcloud/documentcloud/blob/master/app/actions/document_import.rb | MIT |
def enough_text_detected?
text_length = @pages.inject(0) {|sum, page| sum + page[:text].length }
text_length > (@pages.length * 100)
end | Our heuristic for this will be ... 100 bytes of text / page. | enough_text_detected? | ruby | documentcloud/documentcloud | app/actions/document_import.rb | https://github.com/documentcloud/documentcloud/blob/master/app/actions/document_import.rb | MIT |
def email_on_complete
count = options['email_me']
return unless count && count > 0
if Document.owned_by(document.account).pending.count == 0
LifecycleMailer.documents_finished_processing(document.account, count).deliver_now
end
end | Check if there are no more pending documents, then email the user based on
the original count. This is a bit optimistic, as the first document could
finish processing before the second document is finished uploading.
In which case, the user would be emailed twice. | email_on_complete | ruby | documentcloud/documentcloud | app/actions/document_import.rb | https://github.com/documentcloud/documentcloud/blob/master/app/actions/document_import.rb | MIT |
def new_page_order
return @new_page_order if @new_page_order
current_page_order = (1..@old_page_count).to_a
new_pages_order = ((@old_page_count + 1)..(@old_page_count + @insert_page_count)).to_a
@new_pages_order = current_page_order.insert(@insert_page_at, *new_pages_order)
end | Calculate the new page order (array of page numbers). | new_page_order | ruby | documentcloud/documentcloud | app/actions/document_insert_pages.rb | https://github.com/documentcloud/documentcloud/blob/master/app/actions/document_insert_pages.rb | MIT |
def process_concat
letters = ('A'..'Z').to_a
pdf_names = {}
@insert_pdfs.each_with_index do |pdf, i|
letter = letters[(i + 1) % 26]
path = File.join(document.path, 'inserts', pdf)
File.open(pdf, 'wb') {|f| f.write(asset_store.read(path)) }
pdf_names[letter] = "#{letter}=#{pdf}"
end
cmd = "pdftk A=#{@pdf} #{pdf_names.values.join(' ')} cat A #{pdf_names.keys.join(' ')} output #{document.slug}.pdf_temp"
`#{cmd} 2>&1`
asset_store.save_pdf(document, "#{document.slug}.pdf_temp", access)
asset_store.delete_insert_pdfs(document)
end | Rebuilds the PDF from the burst apart pages in the correct order. Saves
images and text from the to-be-inserted PDFs to the local disk. | process_concat | ruby | documentcloud/documentcloud | app/actions/document_insert_pages.rb | https://github.com/documentcloud/documentcloud/blob/master/app/actions/document_insert_pages.rb | MIT |
def rebuild_pdf
page_paths = (1..document.page_count).map {|i| "#{document.slug}_#{i}.pdf" }
#`pdftk #{page_paths.join(' ')} cat output #{@pdf}`
`pdftailor stitch --output #{@pdf} #{page_paths.join(' ')} 2>&1`
if File.exists? @pdf
asset_store.save_pdf(document, @pdf, access)
File.open( @pdf,'r') do | fh |
document.update_file_metadata( fh.read )
end
end
end | Create the new PDF for the full document, and save it to the asset store.
When complete, calculate the new file_hash for the document | rebuild_pdf | ruby | documentcloud/documentcloud | app/actions/redact_pages.rb | https://github.com/documentcloud/documentcloud/blob/master/app/actions/redact_pages.rb | MIT |
def prepare_pdf
@pdf = document.slug + '.pdf'
File.open(@pdf, 'wb') {|f| f.write(asset_store.read_pdf(document)) }
end | Generate the file name we're going to use for the PDF, and save it locally. | prepare_pdf | ruby | documentcloud/documentcloud | app/actions/support/document_action.rb | https://github.com/documentcloud/documentcloud/blob/master/app/actions/support/document_action.rb | MIT |
def enable
key = SecurityKey.find_by_key(params[:key])
if key
if request.post?
if params[:acceptance] == 'yes'
account = key.securable
account.update(password: params[:password])
account.authenticate(session, cookies)
key.destroy
redirect_to homepage_url and return
else
flash.now[:error] = 'Please accept the Terms of Service.'
end
end
else
redirect_to login_url, flash: {error: 'That account is invalid or has already been activated.'} and return
end
end | Enabling an account continues the second half of the signup process,
allowing the journalist to set their password, and logging them in. | enable | ruby | documentcloud/documentcloud | app/controllers/accounts_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/accounts_controller.rb | MIT |
def reset
if request.post? && params[:email].present?
if account = Account.lookup(params[:email].strip)
account.send_reset_request
end
# Show this flash whether or not the email address exists in our system.
flash.now[:notice] = "Please check the email address you provided for further instructions."
end
end | Show the "Reset Password" screen for an account holder. | reset | ruby | documentcloud/documentcloud | app/controllers/accounts_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/accounts_controller.rb | MIT |
def index
respond_to do |format|
format.html do
if logged_in? and current_account.real?
@projects = Project.load_for(current_account)
@current_organization = current_account.organization
@organizations = Organization.all_slugs
@has_documents = Document.owned_by(current_account).exists?
return render template: 'workspace/index', layout: 'workspace'
end
redirect_to public_search_url(query: params[:query])
end
format.json do
json current_organization.accounts.active
end
end
end | Requesting /accounts returns the list of accounts in your logged-in organization.
consider extracting the HTML info into a single method in common w/ workspace | index | ruby | documentcloud/documentcloud | app/controllers/accounts_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/accounts_controller.rb | MIT |
def logged_in
return bad_request unless request.format.json? or request.format.js?
@response = { logged_in: logged_in? }
render_cross_origin_json
end | Does the current request come from a logged-in account? | logged_in | ruby | documentcloud/documentcloud | app/controllers/accounts_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/accounts_controller.rb | MIT |
def create
# Check the requester's permissions
return forbidden unless current_account.admin?(current_organization) or
(current_account.real?(current_organization) and params[:role] == Account::REVIEWER)
# Find or create the appropriate account
account_attributes = pick(params, :first_name, :last_name, :email, :language, :document_language).merge({
language: current_organization.language,
document_language: current_organization.document_language
})
account = Account.lookup(account_attributes[:email]) || Account.create(account_attributes)
return json(account) unless account.valid?
# Find role for account in organization if it exists.
membership_attributes = pick(params, :role, :concealed)
return bad_request(error: 'Role is required') unless Account::ROLES.include? membership_attributes[:role]
membership = current_organization.role_of(account)
# Create a membership if account has no existing role
if membership.nil?
membership_attributes[:default] = true unless account.memberships.exists?
membership = current_organization.memberships.create(membership_attributes.merge(account_id: account.id))
elsif membership.role == Account::REVIEWER # or if account is a reviewer in this organization
account.upgrade_reviewer_to_real(current_organization, membership_attributes[:role])
elsif membership.role == Account::DISABLED
return bad_request(error: 'That email address belongs to an inactive account.')
else
return conflict(error: 'That email address is already part of this organization.')
end
if account.pending?
account.send_login_instructions(current_organization, current_account)
else
LifecycleMailer.membership_notification(account, current_organization, current_account).deliver_now
end
json account.canonical(membership: membership)
end | Fetches or creates a user account and creates a membership for that
account in an organization.
New accounts are created as pending, with a security key instead of
a password. | create | ruby | documentcloud/documentcloud | app/controllers/accounts_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/accounts_controller.rb | MIT |
def update
account = current_organization.accounts.find(params[:id])
return forbidden unless account && current_account.allowed_to_edit_account?(account, current_organization)
return json(account) unless account.update_attributes pick(params, :first_name, :last_name, :email,:language, :document_language)
role = pick(params, :role)
#account.update_attributes(role) if !role.empty? && current_account.admin?
membership = current_organization.role_of(account)
membership.update_attributes(role) if !role.empty? && current_account.admin?
password = pick(params, :password)[:password]
if (current_account.id == account.id) && password
account.update(password: password)
end
json account.canonical(membership: membership)
end | Journalists are authorized to update any account in the organization.
Think about what the desired level of access control is. | update | ruby | documentcloud/documentcloud | app/controllers/accounts_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/accounts_controller.rb | MIT |
def resend_welcome
return forbidden unless current_account.admin?
account = current_organization.accounts.find(params[:id])
LifecycleMailer.login_instructions(account, current_organization, current_account).deliver_now
json nil
end | Resend a welcome email for a pending account. | resend_welcome | ruby | documentcloud/documentcloud | app/controllers/accounts_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/accounts_controller.rb | MIT |
def save_analytics
return forbidden unless params[:secret] == DC::SECRETS['pixel_ping']
RestClient.post(DC::CONFIG['cloud_crowd_server'] + '/jobs', {job: {
action: 'save_analytics', inputs: [params[:json]]
}.to_json})
json nil
end | Endpoint for our pixel-ping application, to save our analytic data every
so often -- delegate to a cloudcrowd job. | save_analytics | ruby | documentcloud/documentcloud | app/controllers/admin_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/admin_controller.rb | MIT |
def queue_length
ok = Document.pending.count <= Document::WARN_QUEUE_LENGTH
render plain: ok ? 'OK' : 'OVERLOADED'
end | Ensure that the length of the pending document queue is ok. | queue_length | ruby | documentcloud/documentcloud | app/controllers/admin_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/admin_controller.rb | MIT |
def launch_worker
return bad_request unless request.post?
Thread.new do
DC::AWS.new.boot_instance({
type: 'c1.medium',
scripts: [DC::AWS::SCRIPTS[:update], DC::AWS::SCRIPTS[:node]]
})
end
json nil
end | Spin up a new CloudCrowd medium worker, for processing. It takes a while
to start the worker, so we let it run in a separate thread and return. | launch_worker | ruby | documentcloud/documentcloud | app/controllers/admin_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/admin_controller.rb | MIT |
def login_as
acc = Account.lookup(params[:email])
return not_found unless acc
acc.authenticate(session, cookies)
# notify when an Admin logs in as a user.
hook_url = DC::SECRETS['slack_webhook']
text = "#{@current_account.full_name} (#{@current_account.email}) has logged in as #{acc.full_name} (#{acc.email} on #{Rails.env})."
data = {:payload => {:text => text, :username => "docbot", :icon_emoji => ":doccloud:"}.to_json}
RestClient.post(hook_url, data)
redirect_to '/'
end | Login as a given account, without needing a password. | login_as | ruby | documentcloud/documentcloud | app/controllers/admin_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/admin_controller.rb | MIT |
def keys_to_timestamps(hash)
result = {}
strings = hash.keys.first.is_a? String
hash.each do |key, value|
time = (strings ? Date.parse(key) : key ).to_time
utc = (time + time.utc_offset).utc
result[utc.to_f.to_i] = value
end
result
end | Pass in the seconds since the epoch, for JavaScript. | keys_to_timestamps | ruby | documentcloud/documentcloud | app/controllers/admin_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/admin_controller.rb | MIT |
def deliver_csv(filename)
response.headers["Content-Type"] ||= 'text/csv'
response.headers["Content-Disposition"] = "attachment; filename=#{filename}.csv"
response.headers['Last-Modified'] = Time.now.ctime.to_s
self.response_body = Enumerator.new do |stream|
csv = CSV.new(stream)
yield csv
end
end | Streams a CSV download to the browser | deliver_csv | ruby | documentcloud/documentcloud | app/controllers/admin_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/admin_controller.rb | MIT |
def index
annotations = current_document.annotations_with_authors(current_account)
json annotations
end | In the workspace, request a listing of annotations. | index | ruby | documentcloud/documentcloud | app/controllers/annotations_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/annotations_controller.rb | MIT |
def print
return bad_request unless params[:docs].is_a?(Array)
docs = Document.accessible(current_account, current_organization).where( :id => params[:docs] )
Document.populate_annotation_counts(current_account, docs)
@documents_json = docs.map {|doc| doc.to_json(:annotations => true, :account => current_account) }
render :layout => nil
end | Print out all the annotations for a document (or documents.) | print | ruby | documentcloud/documentcloud | app/controllers/annotations_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/annotations_controller.rb | MIT |
def create
maybe_set_cors_headers
note_attrs = pick(params, :page_number, :title, :content, :location, :access)
note_attrs[:access] = ACCESS_MAP[note_attrs[:access].to_sym]
doc = current_document
return forbidden unless note_attrs[:access] == PRIVATE || current_account.allowed_to_comment?(doc)
note_attrs[:organization_id] = current_account.organization_id
anno = doc.annotations.create(note_attrs.merge(
:account_id => current_account.id
))
json current_document.annotations_with_authors(current_account, [anno]).first
end | Any account can create a private note on any document.
Only the owner of the document is allowed to create a public annotation. | create | ruby | documentcloud/documentcloud | app/controllers/annotations_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/annotations_controller.rb | MIT |
def update
maybe_set_cors_headers
return not_found unless anno = current_annotation
return forbidden(:error => "You don't have permission to update the note.") unless current_account.allowed_to_edit?(anno)
attrs = pick(params, :title, :content, :access)
attrs[:access] = DC::Access::ACCESS_MAP[attrs[:access].to_sym]
anno.update_attributes(attrs)
anno.reset_public_note_count
json anno
end | You can only alter annotations that you've made yourself. | update | ruby | documentcloud/documentcloud | app/controllers/annotations_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/annotations_controller.rb | MIT |
def upload
secure_silence_logs do
return bad_request unless params[:file] && params[:title] && current_account
is_file = params[:file].respond_to?(:path)
if !is_file && !(URI.parse(params[:file]) rescue nil)
return bad_request(:error => "The 'file' parameter must be the contents of a file or a URL.")
end
if params[:file_hash] && Document.accessible(current_account, current_organization).exists?(:file_hash=>params[:file_hash])
return conflict(:error => "This file is a duplicate of an existing one you have access to.")
end
params[:url] = params[:file] unless is_file
@response = Document.upload(params, current_account, current_organization).canonical
render_cross_origin_json
end
end | Upload API, similar to our internal upload API for starters. Parameters:
file, title, access, source, description.
The `file` must either be a multipart file upload, or a URL to a remote doc. | upload | ruby | documentcloud/documentcloud | app/controllers/api_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/api_controller.rb | MIT |
def projects
return forbidden unless current_account # already returns a 401 if credentials aren't supplied
opts = { :include_document_ids => params[:include_document_ids] != 'false' }
@response = {'projects' => Project.accessible(current_account).map {|p| p.canonical(opts) } }
render_cross_origin_json
end | Retrieve a listing of your projects, including document id. | projects | ruby | documentcloud/documentcloud | app/controllers/api_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/api_controller.rb | MIT |
def logger
params[:secure] ? nil : super
end | Allow logging of all actions, apart from secure uploads. | logger | ruby | documentcloud/documentcloud | app/controllers/api_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/api_controller.rb | MIT |
def json(obj, options={})
# Compatibility: second param used to be `status` and take a numeric status
# code. Until we've purged all these, do a check.
options = { :status => options } if options.is_a?(Numeric)
options = {
:status => 200,
:cors => false
}.merge(options)
obj = {} if obj.nil?
if obj.respond_to?(:errors) && obj.errors.any?
response = {
:json => { :errors => obj.errors.full_messages },
:status => 400
}
else
response = {
:json => obj,
:status => options[:status]
}
end
# If the request has already set the CORS headers, don't overwrite them
# Sending the wildcard origin that will dissallow sending cookies for
# authentication.
headers['Access-Control-Allow-Origin'] = '*' if options[:cors] && !headers.has_key?('Access-Control-Allow-Origin')
render response
end | Convenience method for responding with JSON. Supports empty responses,
specifying status codes, and adding CORS headers. If JSONing an
ActiveRecord object with errors, a 400 Bad Request will be returned with a
list of error messages. | json | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def render_as_jsonp(obj, options={})
options = { :status => 200 }.merge(options)
response = {
:partial => 'common/jsonp.js',
:locals => { obj: obj, callback: params[:callback] },
:content_type => 'application/javascript',
:status => options[:status]
}
render response
end | If the request is asking for JSONP (i.e., has a `callback` parameter), then
wrap the JSON and render as JSONP. | render_as_jsonp | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def render_cross_origin_json(obj=nil, options={})
# Compatibility: Previous version expected the `@response` instance var, so
# until we modify all instances to pass in `obj`, set it to `@response`.
obj ||= @response
return render_as_jsonp(obj, options) if has_callback?
options = {
:cors => true
}.merge(options)
json obj, options
end | Return the contents of `obj` as cross-origin-allowed JSON or, if it has a
`callback` parameter, as JSONP. | render_cross_origin_json | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def set_p3p_header
# explanation of what these mean: http://www.p3pwriter.com/LRN_111.asp
headers['P3P'] = 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'
end | for use by actions that may be embedded in an iframe
without this header IE will not send cookies | set_p3p_header | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def pick(hash, *keys)
filtered = {}
hash.each {|key, value| filtered[key.to_sym] = value if keys.include?(key.to_sym) }
filtered
end | Select only a sub-set of passed parameters. Useful for whitelisting
attributes from the params hash before performing a mass-assignment. | pick | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def forbidden(options = {})
options = {
error: "Forbidden",
locals: {
post_login_url: CGI.escape(request.original_url),
is_document: false
}
}.deep_merge(options)
error_response 403, options
end | Return forbidden when the access is unauthorized. | forbidden | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def not_found(options={})
options = { :error => "Not Found" }.merge(options)
error_response 404, options
end | Return not_found when a resource can't be located. | not_found | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def conflict(options={})
options = { :error => "Conflict" }.merge(options)
error_response 409, options
end | Return conflict when e.g. there's an edit conflict. | conflict | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def server_error(e, options={})
options = { :error => "Internal Server Error" }.merge(options)
error_response 500, options
end | Return server_error when an uncaught exception bubbles up. | server_error | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def not_implemented(options={})
options = { :error => "Not Implemented" }.merge(options)
error_response 501, options
end | A resource was requested in a way we can't fulfill (e.g. an oEmbed
request for XML when we only provide JSON) | not_implemented | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def service_unavailable(options={})
options = { :error => "Service Unavailable" }.merge(options)
error_response 503, options
end | We're offline in an expected way | service_unavailable | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def bouncer
authenticate_or_request_with_http_basic("DocumentCloud") do |login, password|
login == DC::SECRETS['guest_username'] && password == DC::SECRETS['guest_password']
end
end | Simple HTTP Basic Auth to make sure folks don't snoop where the shouldn't. | bouncer | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def notify_exceptions
begin
yield
rescue Exception => e
ignore = ERRORS_TO_IGNORE.any?{ |kind| e.is_a? kind }
LifecycleMailer.exception_notification(e, params).deliver_now unless ignore
raise e
end
end | Email production exceptions to us. Once every 2 minutes at most, per process. | notify_exceptions | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def perform_profile
return yield unless params[:perform_profile]
require 'ruby-prof'
RubyProf.start
yield
result = RubyProf.stop
printer = RubyProf::FlatPrinter.new(result)
File.open("#{Rails.root}/tmp/profile.txt", 'w+') do |f|
printer.print(f)
end
end | In development mode, optionally perform a RubyProf profile of any request.
Simply pass perform_profile=true in your params. | perform_profile | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def debug_api
response.content_type = 'text/plain' if params[:debug]
end | Return all requests as text/plain, if a 'debug' param is passed, to make
the JSON visible in the browser. | debug_api | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def error_response(status=200, options={})
options = {
:locals => {}
}.merge(options)
obj = {}
obj[:error] = options[:error] if options[:error]
obj[:errors] = options[:errors] if options[:errors]
respond_to do |format|
format.js { render_cross_origin_json(obj, {:status => status}) }
format.json { render_cross_origin_json(obj, {:status => status}) }
format.any { render :file => "#{Rails.root}/public/#{status}.html", :locals => options[:locals], :status => status, :layout => nil }
end
false
end | Generic error response helper. Defaults to 200 because never called directly | error_response | ruby | documentcloud/documentcloud | app/controllers/application_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/application_controller.rb | MIT |
def login
return redirect_to '/' if current_account && current_account.refresh_credentials(cookies) && !current_account.reviewer? && current_account.active?
return render layout: 'new' unless request.post?
next_url = (params[:next] && CGI.unescape(params[:next])) || '/'
account = Account.log_in(params[:email], params[:password], session, cookies)
return redirect_to(next_url) if account && account.active?
if account && !account.active?
flash[:error] = "Your account has been disabled. Contact [email protected]."
else
flash[:error] = "Invalid email or password."
end
begin
if referrer = request.env["HTTP_REFERER"]
redirect_to referrer.sub(/^http:/, 'https:')
end
rescue RedirectBackError => e
return render layout: 'new'
end
end | /login handles both the login form and the login request. | login | ruby | documentcloud/documentcloud | app/controllers/authentication_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/authentication_controller.rb | MIT |
def logout
clear_login_state
redirect_to '/'
end | Logging out clears your entire session. | logout | ruby | documentcloud/documentcloud | app/controllers/authentication_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/authentication_controller.rb | MIT |
def remote_data
render :json => build_remote_data( params[:document_id] )
end | this is the endpoint for an embedded document to obtain addition information
about the document as well as the current user | remote_data | ruby | documentcloud/documentcloud | app/controllers/authentication_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/authentication_controller.rb | MIT |
def inner_iframe
if logged_in?
@account = current_account
flash[:notice] = 'You have successfully logged in'
@remote_data = build_remote_data( params[:document_id] )
@status = true
render :action=>'iframe_login_status'
else
@next_url = '/auth/iframe_success'
session[:dv_document_id]=params[:document_id]
render :template=>'authentication/social_login'
end
end | Displays the login page inside an iframe.
if they are already logged in, display a success message,
otherwise renders the standard login page template inside our
own minimalistic layout using custom css to compact it. | inner_iframe | ruby | documentcloud/documentcloud | app/controllers/authentication_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/authentication_controller.rb | MIT |
def omniauth_start_popup
session[:omniauth_popup_next]='/auth/popup_completion'
redirect_to params[:service]
end | Set the iframe session flag before loading the service from omniauth
This way we can know where the request originated and can close the popup
after the authentication completes | omniauth_start_popup | ruby | documentcloud/documentcloud | app/controllers/authentication_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/authentication_controller.rb | MIT |
def iframe_success
@remote_data = session.has_key?(:dv_document_id) ? build_remote_data( session.delete(:dv_document_id) ) : {}
flash[:notice] = 'Successfully logged in'
@status = true
render :action=>'iframe_login_status'
end | renders the message and communicates the success back to the outer
iframe and across the xdm socket to the viewer | iframe_success | ruby | documentcloud/documentcloud | app/controllers/authentication_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/authentication_controller.rb | MIT |
def failure
flash[:error] = params[:message]
redirect_to :action=>'login'
end | The destination for third party logins that have failed.
In almost all cases this is due to the cancel option
being selected while on the external site | failure | ruby | documentcloud/documentcloud | app/controllers/authentication_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/authentication_controller.rb | MIT |
def status
docs = Document.accessible(current_account, current_organization).where({:id => params[:ids]})
Document.populate_annotation_counts(current_account, docs)
render :json => { 'documents' => docs.map{|doc| doc.as_json(:cache_busting=>true) } }
end | Allows us to poll for status updates in the in-progress document uploads. | status | ruby | documentcloud/documentcloud | app/controllers/documents_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/documents_controller.rb | MIT |
def per_page_note_counts
json current_document(true).per_page_annotation_counts
end | TODO: Fix the note/annotation terminology. | per_page_note_counts | ruby | documentcloud/documentcloud | app/controllers/documents_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/documents_controller.rb | MIT |
def send_pdfs
package("#{package_name('original_documents')}.zip") do |zip|
@documents.each do |doc|
zip.get_output_stream("#{doc.slug}.pdf") {|f| f.write(asset_store.read_pdf(doc)) }
end
end
end | TODO: Figure out a more efficient way to package PDFs. | send_pdfs | ruby | documentcloud/documentcloud | app/controllers/download_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/download_controller.rb | MIT |
def enhance
return not_implemented unless request.format.js?
render :enhance, content_type: js_mime_type
end | The enhancer is designed in `documentcloud-pages`, installed via bower,
built by `rake build:embed:page`, and deployed to S3, but but we provide a
route to it here for development and testing. | enhance | ruby | documentcloud/documentcloud | app/controllers/embed_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/embed_controller.rb | MIT |
def loader
return not_implemented unless request.format.js?
object_controller_map = {
viewer: 'documents',
notes: 'annotations',
embed: 'search'
}
return not_found unless matching_controller = object_controller_map[params[:object].to_sym]
render "#{matching_controller}/embed_loader", content_type: js_mime_type
end | The loaders live in their respective view folders and are deployed to S3,
but we provide routes to them here for development and testing. | loader | ruby | documentcloud/documentcloud | app/controllers/embed_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/embed_controller.rb | MIT |
def upload_document
return bad_request unless params[:file]
@document = Document.upload(params, current_account, current_organization)
@project_id = params[:project]
if params[:multi_file_upload]
json @document
else
# Render the HTML/script...
end
end | Internal document upload, called from the workspace. | upload_document | ruby | documentcloud/documentcloud | app/controllers/import_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/import_controller.rb | MIT |
def cloud_crowd
return forbidden unless correct_cloud_crowd_secret?(params[:secret])
cloud_crowd_job = JSON.parse(params[:job])
if processing_job = ProcessingJob.lookup_by_remote(cloud_crowd_job)
processing_job.resolve(cloud_crowd_job)
end
#render plain: '201 Created', status: 201
render plain: "Created but don't clean up the job right now."
end | Returning a "201 Created" ack tells CloudCrowd to clean up the job. | cloud_crowd | ruby | documentcloud/documentcloud | app/controllers/import_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/import_controller.rb | MIT |
def update_access
return forbidden unless correct_cloud_crowd_secret?(params[:secret])
cloud_crowd_job = JSON.parse(params[:job])
if processing_job = ProcessingJob.lookup_by_remote(cloud_crowd_job)
processing_job.resolve(cloud_crowd_job)
end
render plain: '201 Created', status: 201
end | CloudCrowd is done changing the document's asset access levels.
201 created cleans up the job. | update_access | ruby | documentcloud/documentcloud | app/controllers/import_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/import_controller.rb | MIT |
def update
membership = current_account.memberships.where({
:role => DC::Roles::ADMINISTRATOR,
:organization_id => params[:id] }).first
return forbidden unless membership
membership.organization.update_attributes pick(params, :language, :document_language)
json membership.organization.canonical
end | Administrators of an organization can set
the default language for members | update | ruby | documentcloud/documentcloud | app/controllers/organizations_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/organizations_controller.rb | MIT |
def preview
@query = params[:query]
@slug = params[:slug]
@options = params[:options]
end | def facets
perform_search :exclude_documents => true,
:include_facets => true
results = {:query => @query, :facets => @query.facets}
json results
end | preview | ruby | documentcloud/documentcloud | app/controllers/search_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/search_controller.rb | MIT |
def index
if logged_in? and current_account.real?
@projects = Project.load_for(current_account)
@current_organization = current_account.organization
@organizations = Organization.all_slugs
@has_documents = Document.owned_by(current_account).exists?
return render :template => 'workspace/index'
end
redirect_to public_search_url(query: params[:query])
end | Main documentcloud.org page. Renders the workspace if logged in or
searching, the home page otherwise. | index | ruby | documentcloud/documentcloud | app/controllers/workspace_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/workspace_controller.rb | MIT |
def help
@page = HELP_PAGES.include?(params[:page]) ? params[:page] : 'index'
contents = File.read("#{Rails.root}/app/views/help/eng/#{@page}.markdown")
links_filename = "#{Rails.root}/app/views/help/eng/#{@page}_links.markdown"
links = File.exists?(links_filename) ? File.read(links_filename) : ""
@help_content = RDiscount.new(contents+links).to_html.gsub MARKDOWN_LINK_REPLACER, '<tt>\1</tt>'
@help_pages = HELP_PAGES - ['tour']
@help_titles = HELP_TITLES
if !logged_in? || current_account.reviewer?
render :template => 'home/help', :layout => 'home'
else
return self.index
end
end | Render a help page as regular HTML, including correctly re-directed links. | help | ruby | documentcloud/documentcloud | app/controllers/workspace_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/workspace_controller.rb | MIT |
def upgrade
render :layout => nil
end | Page for unsupported browsers, to request an upgrade. | upgrade | ruby | documentcloud/documentcloud | app/controllers/workspace_controller.rb | https://github.com/documentcloud/documentcloud/blob/master/app/controllers/workspace_controller.rb | MIT |
def login_instructions(account, organization, admin=nil)
@admin = admin
@account = account
@organization = organization
options = {
:subject => DC.t(account, 'welcome_to_document_cloud'),
:to => @account.email,
:content_type => "text/plain",
:template_path => translation_path_for( account.language )
}
account.ensure_security_key!
options[ :cc ] = @admin.email if @admin
mail( options )
end | Mail instructions for a new account, with a secure link to activate,
set their password, and log in. | login_instructions | ruby | documentcloud/documentcloud | app/mailers/lifecycle_mailer.rb | https://github.com/documentcloud/documentcloud/blob/master/app/mailers/lifecycle_mailer.rb | MIT |
def reviewer_instructions(documents, inviter_account, reviewer_account=nil, message=nil, key='')
@documents = documents
@key = key
@organization_name = documents[0].account.organization_name
@account_exists = reviewer_account && !reviewer_account.reviewer?
@inviter_account = inviter_account
@reviewer_account = reviewer_account
@message = message
options = {
:cc => inviter_account.email,
:subject => DC.t(inviter_account,'review_x_documents', documents.count, documents.first.title ),
:content_type => "text/plain",
:template_path => translation_path_for( inviter_account.language )
}
options[:to] = reviewer_account.email if reviewer_account
mail( options )
end | Mail instructions for a document review, with a secure link to the
document viewer, where the user can annotate the document. | reviewer_instructions | ruby | documentcloud/documentcloud | app/mailers/lifecycle_mailer.rb | https://github.com/documentcloud/documentcloud/blob/master/app/mailers/lifecycle_mailer.rb | MIT |
def reset_request(account)
@account = account
account.ensure_security_key!
@key = account.security_key.key
mail({
:to => account.email, :subject => DC.t(account,'password_reset'),
:content_type => "text/plain",
:template_path => translation_path_for( account.language )
})
end | Mail instructions for resetting an active account's password. | reset_request | ruby | documentcloud/documentcloud | app/mailers/lifecycle_mailer.rb | https://github.com/documentcloud/documentcloud/blob/master/app/mailers/lifecycle_mailer.rb | MIT |
def contact_us(account, params)
name = account ? account.full_name : params[:email]
@account = account
@message = params[:message]
@email = params[:email]
mail({
:subject => "DocumentCloud message from #{name}",
:from => NO_REPLY,
:reply_to => account ? account.email : params[:email],
:to => SUPPORT
})
end | When someone sends a message through the "Contact Us" form, deliver it to
us via email. | contact_us | ruby | documentcloud/documentcloud | app/mailers/lifecycle_mailer.rb | https://github.com/documentcloud/documentcloud/blob/master/app/mailers/lifecycle_mailer.rb | MIT |
def exception_notification(error, params=nil)
params.delete(:password) if params
@params = params
@error = error
mail({
:subject => "DocumentCloud exception (#{Rails.env}:#{`hostname`.chomp}): #{error.class.name}",
:from => NO_REPLY,
:to => EXCEPTIONS
})
end | Mail a notification of an exception that occurred in production. | exception_notification | ruby | documentcloud/documentcloud | app/mailers/lifecycle_mailer.rb | https://github.com/documentcloud/documentcloud/blob/master/app/mailers/lifecycle_mailer.rb | MIT |
def documents_finished_processing(account, document_count)
@account = account
@count = document_count
mail({
:to => account.email, :subject => DC.t(account,'documents_are_ready'),
:content_type => "text/plain",
:template_path => translation_path_for( account.language )
})
end | When a batch of uploaded documents has finished processing, email
the account to let them know. | documents_finished_processing | ruby | documentcloud/documentcloud | app/mailers/lifecycle_mailer.rb | https://github.com/documentcloud/documentcloud/blob/master/app/mailers/lifecycle_mailer.rb | MIT |
def account_and_document_csvs
date = Date.today.strftime "%Y-%m-%d"
accounts = ""
DC::Statistics.accounts_csv( CSV.new(accounts) )
attachments["accounts-#{date}.csv"] = {
mime_type: 'text/csv',
content: accounts
}
attachments["top-documents-#{date}.csv"] = {
mime_type: 'text/csv',
content: DC::Statistics.top_documents_csv
}
mail({
:subject => "Accounts (CSVs)",
:from => NO_REPLY,
:to => INFO
})
end | Accounts and Document CSVs mailed out every 1st and 15th of the month | account_and_document_csvs | ruby | documentcloud/documentcloud | app/mailers/lifecycle_mailer.rb | https://github.com/documentcloud/documentcloud/blob/master/app/mailers/lifecycle_mailer.rb | MIT |
def permission_to_review(document)
@document = document
mail(
:subject => "We were unable to successfully process a document",
:cc => SUPPORT,
:to => document.account.email,
:content_type => "text/plain"
)
end | Email the owner of a document which is having difficulty processing | permission_to_review | ruby | documentcloud/documentcloud | app/mailers/lifecycle_mailer.rb | https://github.com/documentcloud/documentcloud/blob/master/app/mailers/lifecycle_mailer.rb | MIT |
def translation_path_for( language )
view = action_name
path = Rails.root.join('app','views', 'lifecycle_mailer', language, "#{view}.text.erb" )
"lifecycle_mailer/" + ( path.exist? ? language : DC::Language::DEFAULT )
end | this will break if HTML format emails are ever used.
If we do, this will have to check text.html.erb extension as well | translation_path_for | ruby | documentcloud/documentcloud | app/mailers/lifecycle_mailer.rb | https://github.com/documentcloud/documentcloud/blob/master/app/mailers/lifecycle_mailer.rb | MIT |
def organizations_with_accounts
Organization.populate_members_info( self.organizations, self )
end | Populates the organization#members accessor with all the organizaton's accounts | organizations_with_accounts | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def authenticate(session, cookies)
session['account_id'] = id
session['organization_id'] = organization_id
refresh_credentials(cookies)
self
end | Save this account as the current account in the session. Logs a visitor in. | authenticate | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def organization
@organization ||= Organization.default_for(self)
end | Shims to preserve API backwards compatability. | organization | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def owns?(resource)
resource.account_id == id
end | An account owns a resource if it's tagged with the account_id. | owns? | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def shared?(resource)
# organization_id will no long be returned on account queries
collaborators = Account.find_by_sql(<<-EOS
select distinct on (a.id)
a.id as id, m.organization_id as organization_id, m.role as role
from accounts as a
inner join collaborations as c1
on c1.account_id = a.id
inner join collaborations as c2
on c2.account_id = #{id} and c2.project_id = c1.project_id
inner join projects as p
on p.id = c1.project_id and p.hidden = false
inner join project_memberships as pm
on pm.project_id = c1.project_id and pm.document_id = #{resource.document_id}
left outer join memberships as m on m.account_id = #{id}
where a.id != #{id}
EOS
)
# check for knockon effects in identifying whether an account owns/collabs on a resource.
collaborators.any? {|account| account.owns_or_collaborates?(resource) }
end | Heavy-duty SQL.
A document is shared with you if it's in any project of yours, and that
project is in collaboration with an owner or and administrator of the document.
Note that shared? is not the same as reviews?, as it ignores hidden projects. | shared? | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def reviews?(resource)
project = resource.projects.hidden.first
project && project.collaborators.exists?(id)
end | Effectively the same as Account#shares?, but for hidden projects used for reviewers. | reviews? | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def accessible_project_ids
@accessible_project_ids ||=
Collaboration.owned_by(self).pluck(:project_id)
end | The list of all of the projects that have been shared with this account
through collaboration. | accessible_project_ids | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def dcloud_admin?
organization.id == 1 && ! reviewer?
end | is the account considered an DocumentCloud Administrator? | dcloud_admin? | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
def send_login_instructions(organization=self.organization, admin=nil)
ensure_security_key!
LifecycleMailer.login_instructions(self, organization, admin).deliver_now
end | When an account is created by a third party, send an email with a secure
key to set the password. | send_login_instructions | ruby | documentcloud/documentcloud | app/models/account.rb | https://github.com/documentcloud/documentcloud/blob/master/app/models/account.rb | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.