class Object

Constants

CA_PHOSEUM
MIN_PASS
MIN_USER
VERSION_SIGN

Public Instance Methods

add_user(user,password,role) click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 315
def add_user(user,password,role)
  result = api_caller({"action" => "create-user", "user" => user, "password" => password, "role" => role},true)
  if result['error']
    return false
  end
  if result['success']
    return true
  end
end
api_caller(json_body,auth=false,cli=false) click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 238
def api_caller(json_body,auth=false,cli=false)
  headers = {}
  if !auth
    if $config['TOKEN']
      headers={ "bearer" => "#{$config['TOKEN']}" }
    else
      return false
    end
  end
  base = URI.parse("#{$config['SERVERURL']}")
  request = Net::HTTP::Post.new(base,headers)
  request.body = JSON.generate(json_body)

  if auth
    if cli
      request.basic_auth("cli", "loginNOauth")
    else
      request.basic_auth("auth", $config['DEFAULT_SECRET'])
    end
  else
    if cli
      request.basic_auth("cli", "loginNOauth")
    end
  end

  response = Net::HTTP.start(base.hostname, $config['PORT'],
                             :timeout => $config['CALL_TIMEOUT'],
                             :use_ssl => base.scheme == "https",
                             :verify_mode => OpenSSL::SSL::VERIFY_PEER,
                             :ca_file => $config['CA_TRUST']
                             ) do |http|
    http.request(request)
  end
  begin
    list = JSON.parse(response.body)
    return list
  rescue
    if !auth
      puts "\nThe server sent out an Error:".red
      puts clean_html(response.body)
      exit 1
    else
      return '{"error": "Secret is invalid"}'
    end
  end
end
change_role(user,new_role) click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 326
def change_role(user,new_role)
  result = api_caller({"action" => "change-role", "username" => user, "new-role" => new_role},true)
  if result['error']
    return false
  end
  if result['success']
    return true
  end
end
change_user_password(user,pass,auth=false) click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 295
def change_user_password(user,pass,auth=false)
  result = api_caller({"action" => "change-password", "username" => user, "password" => pass},auth)
  if result['error']
    return false
  end
  if result['success']
    return true
  end
end
change_username(user,new_user) click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 305
def change_username(user,new_user)
  result = api_caller({"action" => "change-username", "username" => user, "new-username" => new_user},true)
  if result['error']
    return false
  end
  if result['success']
    return true
  end
end
check_image_exists(fpath) click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 186
def check_image_exists(fpath)
  flocal = fpath.split('/')
  filename = flocal.last
  album = fpath.clone
  album.gsub!(/#{filename}/,'')

  if ffile = search_image(filename,album)
    return ffile
  else
    return false
  end
  exit 0
end
check_string_sanity(album) click to toggle source
# File lib/phoseum/phoseum-common-lib.rb, line 50
def check_string_sanity(album)
  album.gsub!(/^\//,'')
  album.gsub!(/^#{$config['ALBUM_URL']}/,'')
  album.gsub!(/^\//,'')
  folders=album.split("/")
  r_folders=''
  folders.each do |f|
    r_folders= [r_folders,f.remove_non_ascii].join("/")
  end
  r_folders = r_folders.gsub!(/^\//,'')
  return r_folders
end
clean_html(msg) click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 168
def clean_html(msg)
  msg.gsub!(/<\/?[^>]*>/, ' ')
  msg.gsub!(/\n\n+/, '\n')
  msg.gsub!(/^\n|\n$/, ' ')
  return msg
end
clean_name(nameval) click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 175
def clean_name(nameval)
  name_words = nameval.split(' ')
  name = ''
  name_words.each do |word|
    cword = check_string_sanity(word)
    name = name.nil? ? cword : [name,cword].join(' ')
  end
  name.gsub!(/^\ /,'')
  return name
end
client_checks() click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 150
def client_checks
  if $config['SERVERURL'] == ''
    puts "I could not find a valid SERVERURL configuration. CFG is empty.".red
    exit 1
  elsif $config['SERVERURL'] !~ /\A#{URI::regexp(['https', 'http'])}\z/
    puts "I could not find a valid SERVERURL configuration. Contains: #{$config['SERVERURL']}".red
    exit 1
  end
  if !$config['SERVERURL']
    puts "I could not find the SERVERURL from Phoseum config, this client is then useless.".red
    exit 1
  end
  if !$config['PORT']
    puts "I could not find the PORT from Phoseum config, this client is then useless.".red
    exit 1
  end
end
confirm_action(msg) click to toggle source

Give yes/no prompt!

Example:

>> confirm_action("message")
=> You must write 'YES' to confirm, otherwise NO is assumed
=> message :[YES/NO]:

Arguments:

msg: (String)
# File lib/phoseum/phoseum-cli-lib.rb, line 108
def confirm_action(msg)
  puts "You must write 'YES' to confirm, otherwise NO is assumed".yellow
  print "#{msg} :[YES/NO]: "
  confirm=STDIN.gets.chomp
  if confirm == "YES"
    return true
  else
    return false
  end
end
cross_versions() click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 354
def cross_versions
  return api_caller({"action" => "version-check" },true,true)
end
delete_user(username) click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 358
def delete_user(username)
  result = api_caller({"action" => "delete-user", "username" => username},true)
  if result['error']
    return false
  end
  if result['success']
    return true
  end
end
gen_config(who) click to toggle source
# File lib/phoseum/phoseum-common-lib.rb, line 142
def gen_config(who)

  local_config={}
  file_to_write=''

  case who
  when "cli"
    local_config['SERVERURL']=""
    local_config['DEBUG']=false
    local_config['PORT']=2207
    local_config['CALL_TIMEOUT']=120
    local_config['DEFAULT_SECRET']="copy-secret-from-server"
    local_config['TOKEN']="make-a-successful-login"

    home_cfg=File.expand_path('~/.phoseum/')
    local_config['CA_TRUST']=[home_cfg,"CA-PHOSEUM"].join('/')

    if !Dir.exist?(home_cfg)
      Dir.mkdir(home_cfg)
      File.open("#{home_cfg}/CA-PHOSEUM", 'w') do |ca|
        ca.write(CA_PHOSEUM)
      end
    end
    file_to_write = [home_cfg,"cli-config.yml"].join('/')
    puts "Creating config at #{file_to_write}"

  when "api"
    local_config['THREADED']=false
    local_dir=Dir.pwd
    local_config['BASEALBUM']="#{local_dir}/Albums"
    local_config['ALBUM_URL']="Albums"
    local_config['STORE_DIR']="#{local_dir}"
    local_config['DEBUG']=true
    local_config['PORT']=2207
    local_config['EXT_URL']=""
    local_config['MAX_IMG_SIZE']=50000000
    local_config['RESIZE']="640x640"
    local_config['RESAMPLE']="72x72"
    local_config['CALL_TIMEOUT']=120
    home_cfg="#{local_dir}/cfg"
    if !Dir.exist?(home_cfg)
      Dir.mkdir(home_cfg)
    end
    file_to_write = [home_cfg,"phoseum-api-config.yml"].join('/')
    puts "Creating config at #{file_to_write}"

    new_secret = SecureRandom.base64(32)
    local_config['DEFAULT_SECRET'] = new_secret
    puts "\nGenerating new secret: #{new_secret}"

  end

  File.open(file_to_write, 'w') do |f|
    f.write(Psych.dump(local_config))
  end
  return true

end
load_config(who) click to toggle source
# File lib/phoseum/phoseum-common-lib.rb, line 100
def load_config(who)
  load_gem('yaml')
  if who == "api"
    local_dir=Dir.pwd
    home_cfg=File.expand_path("#{local_dir}/cfg")
    file_to_load = [home_cfg,"phoseum-api-config.yml"].join('/')
    if !Dir.exist?(home_cfg)
      gen_config(who)
      puts "New configuration was generated at #{file_to_load}. Please complete missing information and run again"
      exit 1
    end
    if !File.file?(file_to_load)
      puts "API CFG Not found: #{file_to_load} "
      exit 1
    end
  elsif who == "cli"
    home_cfg=File.expand_path('~/.phoseum/')
    file_to_load = [home_cfg,"cli-config.yml"].join('/')
    if !Dir.exist?(home_cfg)
      gen_config(who)
      puts "New configuration was generated at #{file_to_load}. Please complete missing information and run again"
      exit 1
    end
    if !File.file?(file_to_load)
      puts "CLI CFG Not found: #{file_to_load} "
      exit 1
    end
  else
    puts "Not sure which configuration to load. Abort."
    exit 1
  end

  begin
    config_data = YAML.load_file(file_to_load)
    puts "Opening configuration from #{file_to_load}" if config_data['DEBUG']
  rescue
    puts "Failed loading configuration from #{file_to_load}"
    exit 1
  end
  return config_data
end
load_gem(gem_name) click to toggle source
# File lib/phoseum/phoseum-common-lib.rb, line 63
def load_gem(gem_name)
  found_gem = false
  begin
    found_gem = Gem::Specification.find_by_name(gem_name)
  rescue Gem::LoadError
    puts "Could not find gem '#{gem_name}'. Please run 'gem install #{gem_name}' as user #{ENV["USER"]}"
    exit 1
  else
    require(gem_name)
  end
end
local_version() click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 368
def local_version
  puts "This CLI library is running version: #{VERSION_SIGN}"
  return
end
option_parser(opts) click to toggle source

Provide some help and options!

Example:

>> options = option_parser(ARGV)
=> puts options[:option]

Arguments:

ARGV: (Array or command line parameters)
# File lib/phoseum/phoseum-cli-lib.rb, line 10
def option_parser(opts)
  options = {}
  OptionParser.new do |opts|
    opts.banner = "Usage: phoseum-cli [options]\n\nRead about details on album names and types of images supported on official website:\nphoseum.org\n\n".green

    opts.on("-a", "--album-path STRING", "Choose destination album. Use with: [update, delete, check]") do |a|
      options[:album] = a
    end

    opts.on("-c", "--check", "Check against Phoseum API Server. Use with: [album-path, image, <alone>]") do |c|
      options[:check] = c
    end

    opts.on("-C", "--create-user USERNAME", "Create user on the application") do |cre|
      options[:create_user] = cre
    end

    opts.on("-d", "--delete", "Delete Album or Image. Use with: [album-path, image]") do |d|
      options[:delete] = d
    end

    opts.on("-D", "--description 'SHORTDESC'", "Add album description (up to 255 chars). Use with: [album-path]") do |ds|
      options[:description] = ds
    end

    opts.on("-f", "--file-cfg FILENAME", "Use alternative configuration file") do |f|
      options[:filecfg] = f
    end

    opts.on("-i", "--image FILENAME", "Manipulate one image. Use with: [check, upload, delete]") do |i|
      options[:image] = i
    end

    opts.on("-l", "--login", "Make a login to save a new token") do |l|
      options[:login] = l
    end

    opts.on("-m", "--multiple", "Ignore repeated images, keep multiple") do |m|
      options[:multiple] = m
    end

    opts.on("-N", "--name 'REALNAME'", "Set Album's synthetic name. Use with: [album-path]") do |n|
      options[:name] = n
    end

    opts.on("-v", "--verbose", "Run verbosely (DEBUG mode)") do |v|
      options[:verbose] = v
    end

    opts.on("-V", "--version", "What version we are") do |vs|
      options[:version] = vs
    end

    opts.on("-x", "--cross-versions", "Check version match between Client and API") do |x|
      options[:crossv] = x
    end

    opts.on("-r", "--role ROLE", "Role for user: [User, Super]. Use with 'create-user'") do |r|
      options[:role] = r
    end

    opts.on("-o", "--options", "Update options from User. Use with: [user]") do |o|
      options[:options] = o
    end

    opts.on("-q", "--quiet", "Avoid regular info, useful for JSON output") do |q|
      options[:quiet] = q
    end

    opts.on("-t", "--test", "Test local files. Used to identify on local directory what will be uploaded.") do |t|
      options[:test] = t
    end

    opts.on("-u", "--upload", "Upload files to Phoseum API Server. Use with: [album-path, image]") do |u|
      options[:upload] = u
    end

    opts.on("-U", "--User USERNAME", "Username for delete or change password / role. Use with: [delete, options]") do |usr|
      options[:user] = usr
    end

    opts.on("-h", "-h", "That is this...") do |h|
      options[:help] = h
    end

  end.parse!
  return options
end
password_sanity(password) click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 336
def password_sanity(password)
  if password.length < MIN_PASS
    puts "New password is shorter than #{MIN_PASS} chars, please use a bigger password.".red
    exit 1
  end
  if !password.test_password
    puts "Password must be at least #{MIN_PASS} and contain at least one capital, one symbol, one number, one regular characters.".red
    exit 1
  end
end
search_image(sign,album='') click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 200
def search_image(sign,album='')
  if !validate_token($config['TOKEN'])
    if token = user_login()
      headers = { "bearer" => token }
    else
      puts "Login Failed".red
      exit 1
    end
  else
    headers={ "bearer" => "#{$config['TOKEN']}" }
  end
  some_uri= album == '' ? "?signature=#{sign}" : "?signature=#{sign}&inside_album=#{album}"
  base = URI.parse("#{$config['SERVERURL']}#{some_uri}")
  request = Net::HTTP::Get.new(base,headers)
  response = Net::HTTP.start(base.hostname, $config['PORT'],
                             :timeout => $config['CALL_TIMEOUT'],
                             :use_ssl => base.scheme == "https",
                             :verify_mode => OpenSSL::SSL::VERIFY_PEER,
                             :ca_file => $config['CA_TRUST']
                             ) do |http|
    http.request(request)
  end
  begin
    list = JSON.parse(response.body)
    if list['warning']
      # puts list['warning']
      return list['warning']
    end
    if list['success']
      return false
    end
  rescue
    puts "\nThe server sent out an Error:".red
    puts clean_html(response.body)
    exit 1
  end
end
username_sanity(username) click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 347
def username_sanity(username)
  if username.length < MIN_USER
    puts "New Username is shorter than #{MIN_USER} chars, please use a bigger username.".red
    exit 1
  end
end
validate_token(token) click to toggle source
# File lib/phoseum/phoseum-cli-lib.rb, line 285
def validate_token(token)
  result = api_caller({"action" => "check-token" })
  if result['error']
    return false
  end
  if result['success']
    return true
  end
end