repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
megorei/motionkit-example
|
app/views/example_motion_kit_layout.rb
|
class ExampleMotionKitLayout < MotionKit::Layout
def layout
root :root do
add UIImageView, :love
add UILabel, :we
add UILabel, :rubymotion
end
end
def root_style
backgroundColor UIColor.blackColor
end
def love_style
image UIImage.imageWithContentsOfFile("#{App.resources_path}/love.png")
frame from_center w: 100, h: 90
end
def we_style
text "We"
font UIFont.systemFontOfSize(24)
textColor UIColor.whiteColor
frame above :love, up: 10, w: 100, h: 30
textAlignment NSTextAlignmentCenter
end
def rubymotion_style
text "RubyMotion"
font UIFont.systemFontOfSize(24)
textColor UIColor.whiteColor
frame below :love, down: 10, left: 25, w: 150, h: 30 # the left offset is necessary because the below helper sets the x-origin of this element to the same value as the x-origin of :love
textAlignment NSTextAlignmentCenter
end
end
|
Seanyo89/Game_Hub
|
lib/biggest_video_game_companies_cli.rb
|
require 'open-uri'
require 'nokogiri'
require 'pry'
require_relative "./biggest_video_game_companies_cli/version"
require_relative './biggest_video_game_companies_cli/company'
require_relative './biggest_video_game_companies_cli/cli'
|
Seanyo89/Game_Hub
|
lib/biggest_video_game_companies_cli/company.rb
|
class BiggestVideoGameCompaniesCli::Company
attr_accessor :name, :position, :url
def self.today
self.scrape_companies
end
def self.scrape_companies
companies = []
companies << self.scrape_alltopeverything
companies
end
def self.alltopeverything
doc = Nokogiri::HTML(open("https://alltopeverything.com/top-10-biggest-video-game-companies/"))
company= self.new
company.name = doc.search("h3.company-title").text.strip
company.position = doc.search("div.kt-info-box").text.strip
company.url = doc.search("a.kt-blocks-info-box-learnmore info-box-link").first.attr("href").strip
company
end
end
|
Seanyo89/Game_Hub
|
lib/biggest_video_game_companies_cli/cli.rb
|
<filename>lib/biggest_video_game_companies_cli/cli.rb
class BiggestVideoGameCompaniesCli::Cli
def call
list_companies
menu
goodbye
end
def list_companies
put"10 Biggest Video Game Companies:"
@companies = BiggestVideoGameCompaniesCli::Company.today
@companies.each.with.index(1) do |company, i|
puts "#{i}. #{company.name} - #{company.position} - #{company.founded}"
end
end
def menu
input = nil
while input != "exit"
puts "Enter the number for the company you'd like more info or type exit:"
input = gets.strip.downcase
if input.to_i > 0
the_company = @companies[input.to_i-1]
puts "#{the_company.name} - #{the_company.position} - #{the_company.founded}"
elsif input == "list"
list_companies
else
puts "Not sure what you want to look for, type list or exit."
end
end
end
def goodbye
puts "Thanks For Coming!!"
end
end
|
shaunmckinnon/scmcms
|
db/seeds.rb
|
<gh_stars>0
if Rails.env.development?
User.create! do |u|
u.email = '<EMAIL>'
u.password = '<PASSWORD>'
end
end
|
shaunmckinnon/scmcms
|
config/routes.rb
|
<filename>config/routes.rb
Rails.application.routes.draw do
devise_for :users
root to: "home#index"
end
|
norcams/sensu-plugins-himlar
|
bin/check-file-missing.rb
|
<gh_stars>0
#! /usr/bin/env ruby
#
# check-file-exists
#
# DESCRIPTION:
# Simple file check
require 'sensu-plugin/check/cli'
class CheckFileExists < Sensu::Plugin::Check::CLI
option :file,
short: '-f /path/to/file',
long: '--file /path/to/file',
default: '/'
option :severity,
short: '-s severity',
long: '--severity severity',
description: 'Severity of missing file. Either W (warning) or C (critical)',
default: 'C'
def run
unless File.exist?(config[:file])
if config[:severity] == 'C'
critical "#{config[:file]} missing!"
elsif config[:severity] == 'W'
warning "#{config[:file]} missing!"
else
unknown "#{config[:file]} missing!"
end
else
ok 'Test file exist'
end
end
end
|
norcams/sensu-plugins-himlar
|
bin/check-imagebuild.rb
|
<reponame>norcams/sensu-plugins-himlar<gh_stars>0
#! /usr/bin/env ruby
#
# check-imagebuild
#
# DESCRIPTION:
# check if imagebuild failed
#
require 'sensu-plugin/check/cli'
require 'jsonl'
class CheckImagebuild < Sensu::Plugin::Check::CLI
option :distro,
short: '-d distro'
def run
file = "/var/log/imagebuilder/#{config[:distro]}-report.jsonl"
if File.exist?(file)
distro = File.basename(file).sub(/\-.*$/, "")
begin
parsed_jsonl = JSONL.parse(File.read(file))
rescue
parsed_jsonl = nil
end
if parsed_jsonl
merged_hash = parsed_jsonl.reduce({}, :merge)
result = merged_hash['result']
else
result = 'invalid'
end
else
result = 'invalid'
end
if result.include? "failed"
critical "#{distro} failed!"
elsif result.include? "success"
ok "#{distro} success!"
elsif result.include? "invalid"
warning "#{distro} warning!"
end
end
end
|
norcams/sensu-plugins-himlar
|
lib/sensu-plugins-himlar.rb
|
require 'sensu-plugins-himlar/version'
|
norcams/sensu-plugins-himlar
|
sensu-plugins-himlar.gemspec
|
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'date'
require_relative 'lib/sensu-plugins-himlar'
Gem::Specification.new do |s|
s.name = 'sensu-plugins-himlar'
s.version = SensuPluginsHimlar::Version::VER_STRING
s.author = 'Norcams'
s.platform = Gem::Platform::RUBY
s.homepage = 'https://github.com/norcams/sensu-plugins-himlar'
s.summary = 'Sensu Plugins Himlar'
s.description = 'Sensu plugins used in himlar'
s.email = '<EMAIL>'
s.license = 'MIT'
s.has_rdoc = false
s.require_paths = ['lib']
s.files = Dir.glob('{bin,lib}/**/*') + %w(LICENSE README.md)
s.executables = Dir.glob('bin/**/*.rb').map { |file| File.basename(file) }
s.test_files = Dir['test/*.rb']
#s.add_dependency('json', '< 2.0.0')
#s.add_dependency('mixlib-cli', '>= 1.5.0')
s.add_runtime_dependency 'english', '0.6.3'
s.add_runtime_dependency 'sensu-plugin', '~> 1.2'
s.add_development_dependency('rake')
s.add_development_dependency('minitest')
end
|
norcams/sensu-plugins-himlar
|
bin/metrics-ceph.rb
|
#! /usr/bin/env ruby
#
# metrics-ceph
#
# DESCRIPTION:
# Overall ceph throughput
#
# OUTPUT:
# metric data
#
# PLATFORMS:
# Linux
#
# DEPENDENCIES:
# gem: sensu-plugin
# gem: english
# ceph client
#
# USAGE:
# #YELLOW
#
# NOTES:
# Runs 'ceph status' command to output cluster status and metrics,
# May need read access to ceph keyring and/or root access for
# authentication.
#
# LICENSE:
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
#
require 'sensu-plugin/metric/cli'
require 'json'
require 'timeout'
require 'English'
require 'socket'
class CephMetrics < Sensu::Plugin::Metric::CLI::Graphite
option :keyring,
description: 'Path to cephx authentication keyring file',
short: '-k KEY',
long: '--keyring',
proc: proc { |k| " -k #{k}" }
option :monitor,
description: 'Optional monitor IP',
short: '-m MON',
long: '--monitor',
proc: proc { |m| " -m #{m}" }
option :cluster,
description: 'Optional cluster name',
short: '-c NAME',
long: '--cluster',
proc: proc { |c| " --cluster=#{c}" }
option :name,
description: 'Optional client name',
short: '-n NAME',
long: '--name',
proc: proc { |n| " --name=#{n}" }
option :timeout,
description: 'Timeout (default 10)',
short: '-t SEC',
long: '--timeout',
proc: proc(&:to_i),
default: 10
option :prefix,
description: 'Metric prefix',
short: '-p PREFIX',
long: '--prefix',
default: "#{Socket.gethostname}.ceph"
def run_cmd(cmd)
pipe, status = nil
begin
cmd += config[:cluster] if config[:cluster]
cmd += config[:keyring] if config[:keyring]
cmd += config[:monitor] if config[:monitor]
cmd += config[:name] if config[:name]
Timeout.timeout(config[:timeout]) do
pipe = IO.popen(cmd)
Process.wait(pipe.pid)
status = $CHILD_STATUS.exitstatus
end
rescue Timeout::Error
begin
Process.kill(9, pipe.pid)
Process.wait(pipe.pid)
rescue Errno::ESRCH, Errno::EPERM
# Catch errors from trying to kill the timed-out process
# We must do something here to stop travis complaining
critical 'Execution timed out'
ensure
critical 'Execution timed out'
end
end
output = pipe.read
critical "Command '#{cmd}' returned no output" if output.to_s == ''
critical output unless status == 0
output
end
def run
result = run_cmd('ceph status --format=json')
data = JSON.parse(result)
ignore_keys = %w(pgs_by_state version)
timestamp = Time.now.to_i
data['pgmap'].each do |key, val|
output "#{config[:prefix]}.#{key}", val, timestamp unless ignore_keys.include? key
end
ok
end
end
|
jrduncans/highcard
|
ruby/lib/cards.rb
|
# Copyright 2006 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This module provides basic playing cards. It provides a Card and Deck class.
# Can be used to implement a card game.
#
# Author:: <NAME> (mailto:<EMAIL>)
# Copyright:: Copyright 2006 <NAME>
# License:: Apache License, Version 2.0
module Cards
# This class represents a playing card, and also provides class methods
# to get the lists of ranks and suits. Cards can be compared using their
# rank, but equality is based on rand and suit both being equal.
class Card
include Comparable
attr_reader :rank, :suit
@@ranks = ['Ace'] + (2..10).to_a + ['Jack', 'Queen', 'King']
@@suits = %w(Clubs Spades Hearts Diamonds)
# The available ranks for playing cards, in order from lowest
# to highest ('Ace' through 'King'). Numerical ranks are
# integers, while non-numerical ranks are strings.
def Card.ranks
@@ranks
end
# The available suits for playing cards, in no particular order.
def Card.suits
@@suits
end
# Creates a card with the given rank and suit.
def initialize(rank, suit)
@rank = rank
@suit = suit
end
def to_s
"#{@rank} of #{@suit}"
end
def hash
@rank.hash + @suit.hash
end
def eql? (other)
self == other
end
def == (other)
@rank == other.rank and @suit == other.suit
end
def <=> (other)
@@ranks.index(@rank) <=> @@ranks.index(other.rank)
end
end
# This class represents a standard 52-card deck of cards. It keeps track
# of the cards that have been drawn.
class Deck
# Creates a new deck with no cards drawn.
def initialize
@cards = []
@drawnCards = []
Card.ranks.each {|rank| Card.suits.each {|suit| @cards << Card.new(rank, suit) } }
end
# Draws a random card.
def draw
index = rand(@cards.size)
card = @cards[index]
if @drawnCards.include? card
draw
else
@drawnCards.push(card)
return card
end
end
# Puts all drawn cards back into the deck.
def reset
@drawnCards = []
end
end
end
|
jrduncans/highcard
|
ruby/lib/highcard.rb
|
#!/usr/bin/env ruby
# Copyright 2006 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
$LOAD_PATH.unshift File.dirname(__FILE__)
require 'cards'
Result = Struct.new('Result', :playerCard, :dealerCard, :message)
class HighCard
def HighCard.play
deck = Cards::Deck.new
player_card = deck.draw
dealer_card = deck.draw
result = Result.new
result.playerCard = player_card
result.dealerCard = dealer_card
if player_card < dealer_card
result.message = "Sorry, you lose."
elsif player_card > dealer_card
result.message = "You win!"
else
result.message = "It's a tie."
end
return result
end
end
def print_instructions
puts '1: Play'
puts '2: Quit'
puts 'Enter the number of the option:'
end
if $PROGRAM_NAME == __FILE__
$stdout.sync = true
loop do
print_instructions
line = gets.strip
case line
when "1"
result = HighCard.play
puts ""
puts "You drew the #{result.playerCard}."
puts "Dealer drew the #{result.dealerCard}."
puts result.message
when "2"
break
else
puts 'Unknown option. Please select again.'
end
puts
end
end
|
jrduncans/highcard
|
ruby/test/test_cards.rb
|
#!/usr/bin/ruby
# Copyright 2006 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
$LOAD_PATH.unshift File.dirname(__FILE__) + '/../lib'
require 'test/unit'
require 'cards'
require 'set'
class CardTest < Test::Unit::TestCase
def setup
@ace_of_clubs = Cards::Card.new('Ace', 'Clubs')
@ace_of_spades = Cards::Card.new('Ace', 'Spades')
@two_of_clubs = Cards::Card.new(2, 'Clubs')
@three_of_diamonds = Cards::Card.new(3, 'Diamonds')
end
def test_equality
ace_of_clubs = Cards::Card.new('Ace', 'Clubs')
assert_equal(@ace_of_clubs, ace_of_clubs)
assert_not_equal(@ace_of_clubs, @ace_of_spades)
assert_not_equal(@ace_of_clubs, @two_of_clubs)
end
def test_comparison
assert(@ace_of_clubs < @two_of_clubs, 'Ace not greater than or equal to two' )
assert(@three_of_diamonds > @two_of_clubs, 'Two not less than or equal to three')
assert_equal(@ace_of_clubs <=> @ace_of_spades, 0, 'Ace of Clubs not greater than or less than Ace of Spades')
end
def test_tostring
assert_match(/\bace\b.+\bclubs\b/i, @ace_of_clubs.to_s)
end
end
class DeckTest < Test::Unit::TestCase
def setup
@deck = Cards::Deck.new
@set = Set.new
end
def test_draw
52.times do
@set << @deck.draw
end
assert(@set.size == 52, '52 different cards not drawn.')
end
def test_reset
52.times { @deck.draw }
@deck.reset
cards = []
52.times { cards << @deck.draw }
assert(cards.size == 52, 'Deck not reset correctly.')
end
end
|
jrduncans/highcard
|
ruby/spec/cards_spec.rb
|
$LOAD_PATH.unshift File.dirname(__FILE__) + '/../lib'
require 'cards'
include Cards
describe Card, '(Ace of Clubs)' do
before(:each) do
@card = Card.new('Ace', 'Clubs')
end
it "should include 'ace' and 'clubs' in display" do
@card.to_s.should match(/\bace\b.+\bclubs\b/i)
end
it 'should equal another Ace of Clubs' do
@card.should eql(Card.new('Ace', 'Clubs'))
end
it 'should not equal an Ace of Spades' do
@card.should_not eql(Card.new('Ace', 'Spades'))
end
it 'should not equal a Two of Clubs' do
@card.should_not eql(Card.new(2, 'Clubs'))
end
it 'should be less than a Two of Clubs' do
@card.should satisfy {|card| card < Card.new(2, 'Clubs')}
end
it 'should compare equally to an Ace of Spades' do
(@card <=> Card.new('Ace', 'Spades')).should equal(0)
end
end
describe Card, '(3 of Diamonds)' do
before(:each) do
@card = Card.new(3, 'Diamonds')
end
it 'should be greater than the Two of Clubs' do
@card.should satisfy {|card| card > Card.new(2, 'Clubs')}
end
end
require 'set'
describe Deck, '(new)' do
before(:each) do
@deck = Deck.new
end
it 'should have 52 unique cards' do
set = Set.new
52.times do
set << @deck.draw
end
set.size.should equal(52)
end
end
describe Deck, '(empty)' do
before(:each) do
@deck = Deck.new
52.times { @deck.draw }
end
it 'should have 52 cards after resetting' do
@deck.reset
cards = []
52.times { cards << @deck.draw }
cards.length.should equal(52)
end
end
|
maromaro0013/hakoirisolver-rails
|
ext/hakoirisolver/test.rb
|
<reponame>maromaro0013/hakoirisolver-rails<gh_stars>0
require "json"
require "./hakoirisolver.o"
stage0 = JSON.parse '{"framesize":{"w":4,"h":5},"endpoint":{"x":3,"y":5},"panels":[{"x":0,"y":0,"w":1,"h":2,"type":"common"},{"x":1,"y":0,"w":2,"h":2,"type":"target"},{"x":3,"y":0,"w":1,"h":2,"type":"common"},{"x":0,"y":2,"w":1,"h":2,"type":"common"},{"x":1,"y":2,"w":1,"h":1,"type":"common"},{"x":2,"y":2,"w":1,"h":1,"type":"common"},{"x":3,"y":2,"w":1,"h":2,"type":"common"},{"x":1,"y":3,"w":1,"h":1,"type":"common"},{"x":2,"y":3,"w":1,"h":1,"type":"common"},{"x":0,"y":4,"w":1,"h":1,"type":"common"},{"x":3,"y":4,"w":1,"h":1,"type":"common"}]}'
stage1 = JSON.parse '{"framesize":{"w":4,"h":5},"endpoint":{"x":3,"y":5},"panels":[{"x":0,"y":0,"w":1,"h":1,"type":"common"},{"x":1,"y":0,"w":2,"h":2,"type":"target"},{"x":3,"y":0,"w":1,"h":1,"type":"common"},{"x":0,"y":1,"w":1,"h":1,"type":"common"},{"x":3,"y":1,"w":1,"h":1,"type":"common"},{"x":0,"y":2,"w":2,"h":1,"type":"common"},{"x":2,"y":2,"w":2,"h":1,"type":"common"},{"x":0,"y":3,"w":2,"h":1,"type":"common"},{"x":2,"y":3,"w":2,"h":1,"type":"common"},{"x":0,"y":4,"w":1,"h":1,"type":"common"},{"x":3,"y":4,"w":1,"h":1,"type":"common"}]}'
stage2 = JSON.parse '{"framesize":{"w":4,"h":5},"endpoint":{"x":3,"y":5},"panels":[{"x":0,"y":0,"w":1,"h":2,"type":"common"},{"x":1,"y":0,"w":2,"h":2,"type":"target"},{"x":3,"y":0,"w":1,"h":2,"type":"common"},{"x":0,"y":2,"w":1,"h":1,"type":"common"},{"x":1,"y":2,"w":1,"h":1,"type":"common"},{"x":2,"y":2,"w":1,"h":1,"type":"common"},{"x":3,"y":2,"w":1,"h":1,"type":"common"},{"x":0,"y":3,"w":2,"h":1,"type":"common"},{"x":2,"y":3,"w":2,"h":1,"type":"common"},{"x":0,"y":4,"w":1,"h":1,"type":"common"},{"x":3,"y":4,"w":1,"h":1,"type":"common"}]}';
stage = stage2
solver = HakoiriSolver.new
solver.set_field_info stage["framesize"]["w"].to_i, stage["framesize"]["h"].to_i, stage["endpoint"]["x"].to_i, stage["endpoint"]["y"].to_i
for panel in stage["panels"] do
type = "0"
case panel["type"]
when "common"
type = "0"
when "target"
type = "1"
end
solver.add_panel_to_field panel["x"].to_i, panel["y"].to_i, panel["w"].to_i, panel["h"].to_i, type.to_i
end
solver.init_solver
ret = solver.data_validate
solver.solve_field
message = ""
move_cnt = 0
move_actions = []
while (message = solver.pop_message) != "" do
m = message.to_s.split ","
move_actions[move_cnt] = {}
move_actions[move_cnt]["index"] = m[0]
move_actions[move_cnt]["action"] = m[1]
move_cnt += 1
end
puts move_actions.to_s
solver.delete_solver
|
maromaro0013/hakoirisolver-rails
|
hakoirisolver-rails.gemspec
|
<reponame>maromaro0013/hakoirisolver-rails
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'hakoirisolver/rails/version'
Gem::Specification.new do |spec|
spec.name = "hakoirisolver-rails"
spec.version = Hakoirisolver::Rails::VERSION
spec.authors = ["maromaro0013"]
spec.email = ["<EMAIL>"]
spec.summary = %q{Immutable Linked List implemented in C-Extensions}
spec.description = %q{Immutable Linked List implemented in C-Extensions}
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
spec.extensions = %w[ext/hakoirisolver/extconf.rb]
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.0"
end
|
maromaro0013/hakoirisolver-rails
|
ext/hakoirisolver/extconf.rb
|
<gh_stars>0
require "mkmf"
create_makefile("hakoirisolver/hakoirisolver")
|
maromaro0013/hakoirisolver-rails
|
lib/hakoirisolver/rails.rb
|
<filename>lib/hakoirisolver/rails.rb<gh_stars>0
require "hakoirisolver/rails/version"
require "hakoirisolver/hakoirisolver"
module Hakoirisolver
module Rails
# Your code goes here...
end
end
|
crushton/acmetools
|
udplog4jr/udplog4jr.rb
|
<gh_stars>1-10
#!/usr/bin/env ruby
###
## Copyright (c) 2012, <NAME>
##
## Permission to use, copy, modify, and distribute this software for any
## purpose with or without fee is hereby granted, provided that the above
## copyright notice and this permission notice appear in all copies.
##
## THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
## WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
## MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
## ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
## WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
## ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
## OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
###
require 'eventmachine'
require 'optparse'
require 'pp'
addr = '0.0.0.0'
port = 2600
optparse = OptionParser.new do|opts|
opts.banner = "Usage: udplog4r.rb [options]"
opts.on_tail( '-h', '--help', 'Show this message' ) do
puts optparse
exit
end
$sipmsg = false
opts.on( '-s', '--sipmsg', 'Filter sipmsg.log only' ) do
$sipmsg = true
end
$disable_options = false
opts.on( '-o', '--disable-options', 'Remove OPTIONS from being displayed' ) do
$disable_options = true
end
end
optparse.parse(ARGV)
if ( ($disable_options == true) and ($sipmsg == false) )
puts "ERROR: -o can only be used with -s"
exit
end
if $sipmsg == true
puts "Filtering sipmsg.log files only..."
end
if $disable_options == true
puts "Filtering out all SIP OPTIONS methods..."
end
class PacketHandler < EM::Connection
def receive_data(data)
if $sipmsg
if /sipmsg/.match(data)
if ( $disable_options && /CSeq:.*OPTIONS/i.match(data) )
return
end
puts data
end
else
puts data
end
end
end
EM.run {
EM.open_datagram_socket addr, port, PacketHandler
printf "Running on %s:%s...\n", addr, port
#EM.add_periodic_timer(1) { puts }
}
|
zeroc0d3/deploy-laravel
|
config/deploy.rb
|
# config valid for current version and patch releases of Capistrano
lock "~> 3.11.2"
set :application, "myapp-deploy"
set :repo_url, "<EMAIL>:zeroc0d3/deploy-laravel.git"
# Default branch is :master
set :branch, "dev-master"
set :source, "src"
# Default deploy_to directory is /var/www/my_app_name
set :root_path, "/var/www"
set :deploy_to, "#{fetch(:root_path)}/#{fetch(:branch)}"
set :shared_folder, "#{fetch(:deploy_to)}/shared"
set :tmp_dir, "#{fetch(:deploy_to)}/tmp"
set :src_current, "#{current_path}/#{fetch(:source)}"
set :src_release, "#{release_path}/#{fetch(:source)}"
set :current_storage, "#{fetch(:src_current)}/storage"
set :release_storage, "#{fetch(:src_release)}/storage"
set :pty, true
# Default value for :linked_files is []
append :linked_files, "#{fetch(:source)}/.env", "#{fetch(:source)}/composer.json", "#{fetch(:source)}/composer.lock", "#{fetch(:source)}/package.json", "#{fetch(:source)}/yarn.lock"
# Default value for :linked_dirs []
append :linked_dirs, "#{fetch(:source)}/vendor", "#{fetch(:source)}/node_modules", "#{fetch(:source)}/storage"
# Default value for keep_releases is 5
set :keep_releases, 5
set :rbenv_type, :user
set :rbenv_ruby, '2.4.1'
set :rbenv_prefix, "RBENV_ROOT=#{fetch(:rbenv_path)} RBENV_VERSION=#{fetch(:rbenv_ruby)} #{fetch(:rbenv_path)}/bin/rbenv exec"
namespace :cleanup do
desc 'Cleanup Current'
task :prev_current do
on roles(:web) do
if test("[ -d #{fetch(:deploy_to)}/current ]")
execute "rm -rf #{fetch(:deploy_to)}/current"
else
info "Can't find: #{fetch(:deploy_to)}/current folder!"
end
end
end
desc 'Cleanup Release'
task :prev_release do
on roles(:web) do
if test("[ -d #{fetch(:deploy_to)}/releases ]")
execute "rm -rf #{fetch(:deploy_to)}/releases"
else
info "Can't find: #{fetch(:deploy_to)}/releases folder!"
end
end
end
task :all do
on roles(:all) do
invoke 'cleanup:prev_current'
invoke 'cleanup:prev_release'
end
end
end
namespace :deploy do
desc 'Restart Deploy'
task :restart do
on roles(:web) do
if test("[ -d #{fetch(:current_storage)} ]")
execute "chmod 777 -R #{fetch(:current_storage)}"
else
info "Can't find: #{fetch(:current_storage)} folder!"
end
end
end
end
namespace :chown do
desc 'Restore Ownership Folder'
task :restore do
on roles(:all) do
if test("[ -d #{release_storage}]")
execute! :sudo, "chown www-data:www-data -R #{release_storage}"
else
info "Can't find: #{release_storage} folder!"
end
end
end
task :change do
on roles(:all) do
if test("[ -d #{fetch(:current_storage)} ]")
execute! :sudo, "chown www-data:www-data -R #{fetch(:current_storage)}"
else
info "Can't find: #{fetch(:current_storage)} folder!"
end
end
end
end
namespace :artisan do
desc 'Artisan Key Generate'
task :key_generate do
on roles(:all) do
execute "cd #{fetch(:src_current)}; php artisan key:generate"
end
end
desc 'Storage Link'
task :storage_link do
on roles(:all) do
execute "cd #{fetch(:src_current)}; php artisan storage:link"
end
end
desc 'Schedule Run'
task :storage_link do
on roles(:all) do
execute "cd #{fetch(:src_current)}; php artisan schedule:run"
end
end
desc 'Create Cached Event'
task :cache_event do
on roles(:all) do
execute "cd #{fetch(:src_current)}; php artisan event:cache"
end
end
desc 'Rebuild Cached Package'
task :cache_package do
on roles(:all) do
execute "cd #{fetch(:src_current)}; php artisan package:discover"
end
end
desc 'Create Cached Route'
task :cache_route do
on roles(:all) do
execute "cd #{fetch(:src_current)}; php artisan route:cache"
end
end
desc 'Create Cached View'
task :cache_view do
on roles(:all) do
execute "cd #{fetch(:src_current)}; php artisan view:cache"
end
end
task :build_cache do
on roles(:all) do
invoke 'artisan:cache_event'
invoke 'artisan:cache_package'
invoke 'artisan:cache_route'
invoke 'artisan:cache_view'
end
end
end
namespace :nginx do
desc 'Reload NGINX'
task :manual_reload do
on roles(:all) do
sudo :service, :nginx, :reload
end
end
desc 'Restart NGINX'
task :manual_start do
on roles(:all), in: :sequence do
execute! :sudo, :service, :nginx, :restart
end
end
task :manual_restart do
on roles(:all) do
invoke 'nginx:manual_reload'
invoke 'nginx:manual_start'
end
end
end
namespace :phpfpm do
desc 'Reload PHP-FPM'
task :manual_reload do
on roles(:all) do
sudo :service, :'php7.4-fpm', :reload
end
end
desc 'Restart PHP-FPM'
task :manual_start do
on roles(:all), in: :sequence do
execute! :sudo, :service, :'php7.4-fpm', :restart
end
end
task :manual_restart do
on roles(:all) do
invoke 'phpfpm:manual_reload'
invoke 'phpfpm:manual_start'
end
end
end
namespace :composer do
desc 'Install Composer'
task :install do
on roles(:all) do
execute "cd #{fetch(:src_current)}; composer install"
end
end
desc 'Self Update Composer'
task :self_update do
on roles(:all) do
execute "cd #{fetch(:src_current)}; composer self-update"
end
end
desc 'Update Composer'
task :update do
on roles(:all) do
execute "cd #{fetch(:src_current)}; composer update"
end
end
desc 'Dump Autoload Composer'
task :dumpautoload do
on roles(:all) do
execute "cd #{fetch(:src_current)}; composer dump-autoload -o"
end
end
task :initialize do
on roles(:all) do
invoke 'composer:install'
invoke 'composer:dumpautoload'
end
end
end
namespace :artisan do
desc 'Clear View'
task :clear_view do
on roles(:all) do
execute "cd #{fetch(:src_current)}; php artisan view:clear"
end
end
desc 'Clear Cache'
task :clear_cache do
on roles(:all) do
execute "cd #{fetch(:src_current)}; php artisan cache:clear"
end
end
desc 'Clear Config'
task :clear_config do
on roles(:all) do
execute "cd #{fetch(:src_current)}; php artisan config:clear"
end
end
desc 'Clear Debugbar'
task :clear_debug do
on roles(:all) do
execute "cd #{fetch(:src_current)}; php artisan debugbar:clear"
end
end
desc 'Clear Event'
task :clear_event do
on roles(:all) do
execute "cd #{fetch(:src_current)}; php artisan event:clear"
end
end
task :clear_all do
on roles(:all) do
invoke 'artisan:clear_view'
invoke 'artisan:clear_cache'
invoke 'artisan:clear_config'
invoke 'artisan:clear_debug'
# invoke 'artisan:clear_event'
end
end
end
namespace :npm do
desc 'Install NPM'
task :install do
on roles(:all) do
execute "cd #{fetch(:src_current)}; npm install"
end
end
desc 'Update NPM'
task :update do
on roles(:all) do
execute "cd #{fetch(:src_current)}; npm update"
end
end
desc 'Remove Old NPM'
task :cleanup do
on roles(:all) do
# execute "cd #{fetch(:src_current)}; rm -rf node_modules"
execute "cd #{fetch(:src_current)}; rm -f package-lock.json"
end
end
task :reinstall do
on roles(:all) do
invoke 'npm:cleanup'
invoke 'npm:install'
end
end
end
namespace :yarn do
desc 'Install Yarn'
task :install do
on roles(:all) do
execute "cd #{fetch(:src_current)}; yarn install"
end
end
desc 'Update Yarn'
task :update do
on roles(:all) do
execute "cd #{fetch(:src_current)}; yarn update"
end
end
desc 'Remove Old Yarn'
task :cleanup do
on roles(:all) do
# execute "cd #{fetch(:src_current)}; rm -rf node_modules"
execute "cd #{fetch(:src_current)}; rm -f yarn.lock"
end
end
task :reinstall do
on roles(:all) do
invoke 'yarn:cleanup'
invoke 'yarn:install'
end
end
end
### CLEANUP ###
after 'git:check', 'cleanup:all'
after 'deploy:publishing', 'deploy:restart'
# after 'deploy:restart', 'composer:initialize'
after 'deploy:restart', 'composer:dumpautoload'
after 'deploy:restart', 'artisan:clear_all'
### NPM ###
# after 'deploy:restart', 'npm:reinstall'
### YARN ###
# after 'deploy:restart', 'yarn:reinstall'
#after 'deploy:restart', 'nginx:manual_reload'
#after 'chown:restore', 'nginx:manual_reload'
#after 'chown:change', 'nginx:manual_reload'
#after 'nginx:manual_reload', 'phpfpm:manual_reload'
|
zeroc0d3/deploy-laravel
|
config/deploy/myapp-staging.rb
|
ask(:password, nil, echo: false)
# Unsecure Deploy
# server '192.168.127.12', user: 'u5780022', roles: %w{app web db}
# Secure Deploy
server '192.168.127.12', user: 'root', port: 22, roles: %w{app web db}
set :application, "myapp-deploy"
set :repo_url, "<EMAIL>:zeroc0d3/deploy-laravel.git"
# Default branch is :master
set :branch, "dev-staging"
# Default deploy_to directory is /var/www/my_app_name
# set :root_path, "/var/www/laravel-project"
# set :deploy_to, "#{fetch(:root_path)}/#{fetch(:branch)}"
set :root_path, "/data/myapp/staging"
set :deploy_to, "#{fetch(:root_path)}"
set :shared_folder, "#{fetch(:deploy_to)}/shared"
set :tmp_dir, "#{fetch(:deploy_to)}/tmp"
set :src_current, "#{current_path}/#{fetch(:source)}"
set :src_release, "#{release_path}/#{fetch(:source)}"
set :current_storage, "#{fetch(:src_current)}/storage"
set :release_storage, "#{fetch(:src_release)}/storage"
set :pty, true
set :ssh_options, {
forward_agent: true,
auth_methods: ["publickey"],
keys: ["keys/myapp.pem"]
}
set :default_environment, {
#-- rbenv --#
# 'PATH' => "$HOME/.rbenv/shims:$HOME/.rbenv/bin:$PATH"
#-- rvm --#
'PATH' => "$HOME/.rvm/bin:$PATH"
}
# namespace :composer do
# desc 'Install Composer'
# task :install do
# on roles(:all) do
# execute "cd #{fetch(:src_current)}; php -d extension=phar.so composer install"
# end
# end
# desc 'Update Composer'
# task :update do
# on roles(:all) do
# execute "cd #{fetch(:src_current)}; php -d extension=phar.so composer self-update"
# end
# end
# desc 'Dump Autoload Composer'
# task :dumpautoload do
# on roles(:all) do
# execute "cd #{fetch(:src_current)}; php -d extension=phar.so composer dump-autoload -o"
# end
# end
# task :initialize do
# on roles(:all) do
# invoke 'composer:install'
# invoke 'composer:dumpautoload'
# end
# end
# end
|
Dreamle/WBZImportInvoice
|
WBZImportInvoice.podspec
|
Pod::Spec.new do |s|
s.name = "WBZImportInvoice"
s.version = "0.0.16"
s.summary = "微报账项目集合微信和支付宝的卡包导入发票"
s.description = <<-DESC
微报账项目集合微信和支付宝的卡包导入发票,供别人方便使用
DESC
s.homepage = "https://github.com/Dreamle/WBZImportInvoice"
s.license = 'MIT'
s.author = { "dreamLee" => "<EMAIL>" }
s.platform = :ios, "9.0"
s.source = { :git => "https://github.com/Dreamle/WBZImportInvoice.git", :tag => "0.0.16" }
s.vendored_frameworks = "**/WBZLib.framework"
s.source_files = "WBZImportInvoice", "*.*"
s.dependency "WechatOpenSDK", '~> 1.8.4'
#s.pod_target_xcconfig = {
#'FRAMEWORK_SEARCH_PATHS' => '$(inherited) $(PODS_ROOT)/WechatOpenSDK',
#'OTHER_LDFLAGS' => '$(inherited) -undefined dynamic_lookup'
#}
s.requires_arc = true
end
|
YUUKIToriyama/miopon-api
|
main.rb
|
<filename>main.rb
#!/usr/bin/ruby
require 'net/http'
require 'json'
uri = URI.parse("https://api.iijmio.jp/mobile/d/v2/log/packet/")
req = Net::HTTP::Get.new(uri)
req["X-IIJmio-Developer"] = open("./.developer_id").read
req["X-IIJmio-Authorization"] = open("./.access_token").read
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
response = https.request(req)
json = JSON.parse(response.body)
puts JSON.pretty_generate(json)
|
greensnark/re2
|
spec/re2_spec.rb
|
<gh_stars>0
require "spec_helper"
describe RE2 do
describe "#Replace" do
it "only replaces the first occurrence of the pattern" do
RE2.Replace("woo", "o", "a").must_equal("wao")
end
it "performs replacement based on regular expressions" do
RE2.Replace("woo", "o+", "e").must_equal("we")
end
it "supports flags in patterns" do
RE2.Replace("Good morning", "(?i)gOOD MORNING", "hi").must_equal("hi")
end
it "performs replacements in-place" do
name = "Robert"
replacement = RE2.Replace(name, "R", "Cr")
replacement.must_equal("Crobert")
name.must_be_same_as(replacement)
end
it "supports passing an RE2::Regexp as the pattern" do
re = RE2::Regexp.new('wo{2}')
RE2.Replace("woo", re, "miaow").must_equal("miaow")
end
it "respects any passed RE2::Regexp's flags" do
re = RE2::Regexp.new('gOOD MORNING', :case_sensitive => false)
RE2.Replace("Good morning", re, "hi").must_equal("hi")
end
it "raises an error if the string is frozen" do
frozen_name = "Arnold".freeze
proc { RE2.Replace(frozen_name, "o", "a") }.must_raise(FrozenError)
end
if String.method_defined?(:encoding)
it "preserves the original string's encoding" do
original = "Foo"
replacement = RE2.Replace(original, "oo", "ah")
original.encoding.must_equal(replacement.encoding)
end
end
end
describe "#GlobalReplace" do
it "replaces every occurrence of a pattern" do
RE2.GlobalReplace("woo", "o", "a").must_equal("waa")
end
it "performs replacement based on regular expressions" do
RE2.GlobalReplace("woohoo", "o+", "e").must_equal("wehe")
end
it "supports flags in patterns" do
RE2.GlobalReplace("Robert", "(?i)r", "w").must_equal("wobewt")
end
it "performs replacement in-place" do
name = "Robert"
replacement = RE2.GlobalReplace(name, "(?i)R", "w")
replacement.must_equal("wobewt")
name.must_be_same_as(replacement)
end
it "supports passing an RE2::Regexp as the pattern" do
re = RE2::Regexp.new('wo{2,}')
RE2.GlobalReplace("woowooo", re, "miaow").must_equal("miaowmiaow")
end
it "respects any passed RE2::Regexp's flags" do
re = RE2::Regexp.new('gOOD MORNING', :case_sensitive => false)
RE2.GlobalReplace("Good morning Good morning", re, "hi").must_equal("hi hi")
end
it "raises an error if the string is frozen" do
frozen_name = "Arnold".freeze
proc { RE2.GlobalReplace(frozen_name, "o", "a") }.must_raise(FrozenError)
end
end
describe "#QuoteMeta" do
it "escapes a string so it can be used as a regular expression" do
RE2.QuoteMeta("1.5-2.0?").must_equal('1\.5\-2\.0\?')
end
end
end
|
greensnark/re2
|
spec/re2/match_data_spec.rb
|
<gh_stars>0
# -*- coding: utf-8 -*-
require "spec_helper"
describe RE2::MatchData do
describe "#to_a" do
it "is populated with the match and capturing groups" do
a = RE2::Regexp.new('w(o)(o)').match('woo').to_a
a.must_equal(["woo", "o", "o"])
end
it "populates optional capturing groups with nil if they are missing" do
a = RE2::Regexp.new('(\d?)(a)(b)').match('ab').to_a
a.must_equal(["ab", nil, "a", "b"])
end
end
describe "#[]" do
it "accesses capturing groups by numerical index" do
md = RE2::Regexp.new('(\d)(\d{2})').match("123")
md[1].must_equal("1")
md[2].must_equal("23")
end
it "has the whole match as the 0th item" do
md = RE2::Regexp.new('(\d)(\d{2})').match("123")
md[0].must_equal("123")
end
it "supports access by numerical ranges" do
md = RE2::Regexp.new('(\d+) (\d+) (\d+)').match("123 456 789")
md[1..3].must_equal(["123", "456", "789"])
md[1...3].must_equal(["123", "456"])
end
it "supports slicing" do
md = RE2::Regexp.new('(\d+) (\d+) (\d+)').match("123 456 789")
md[1, 3].must_equal(["123", "456", "789"])
md[1, 2].must_equal(["123", "456"])
end
it "returns nil if attempting to access non-existent capturing groups by index" do
md = RE2::Regexp.new('(\d+)').match('bob 123')
md[2].must_be_nil
md[3].must_be_nil
end
it "allows access by string names when there are named groups" do
md = RE2::Regexp.new('(?P<numbers>\d+)').match('bob 123')
md["numbers"].must_equal("123")
end
it "allows access by symbol names when there are named groups" do
md = RE2::Regexp.new('(?P<numbers>\d+)').match('bob 123')
md[:numbers].must_equal("123")
end
it "allows access by names and indices with mixed groups" do
md = RE2::Regexp.new('(?P<name>\w+)(\s*)(?P<numbers>\d+)').match("bob 123")
md["name"].must_equal("bob")
md[:name].must_equal("bob")
md[2].must_equal(" ")
md["numbers"].must_equal("123")
md[:numbers].must_equal("123")
end
it "returns nil if no such named group exists" do
md = RE2::Regexp.new('(\d+)').match("bob 123")
md["missing"].must_be_nil
md[:missing].must_be_nil
end
if String.method_defined?(:encoding)
it "returns UTF-8 encoded strings by default" do
md = RE2::Regexp.new('(?P<name>\S+)').match("bob")
md[0].encoding.name.must_equal("UTF-8")
md["name"].encoding.name.must_equal("UTF-8")
md[:name].encoding.name.must_equal("UTF-8")
end
it "returns Latin 1 strings encoding when utf-8 is false" do
md = RE2::Regexp.new('(?P<name>\S+)', :utf8 => false).match('bob')
md[0].encoding.name.must_equal("ISO-8859-1")
md["name"].encoding.name.must_equal("ISO-8859-1")
md[:name].encoding.name.must_equal("ISO-8859-1")
end
end
end
describe "#begin" do
it "returns the index in the search text where the match occurred" do
match = RE2::Regexp.new("(ti)").match("aegypti")
match.begin(1).must_equal(5)
end
it "returns the index of the zeroth match if unspecified" do
match = RE2::Regexp.new("..(ti)").match("aegypti")
match.begin().must_equal(3)
end
it "reports indexes in UTF-8 text as unicode character offsets" do
match = RE2::Regexp.new(".(ら)").match("世界中のあらゆ")
match.begin(0).must_equal(4)
end
it "reports indexes for named captures" do
match = RE2::Regexp.new(".(?P<capture>ら)").match("世界中のあらゆ")
match.begin(:capture).must_equal(5)
end
end
describe "#end" do
it "returns the index in the search text where the match occurred" do
match = RE2::Regexp.new("(ti)").match("aegypti")
match.end(1).must_equal(7)
end
it "returns the index of the zeroth match if unspecified" do
match = RE2::Regexp.new("..(ti)").match("aegypti")
match.end().must_equal(7)
end
it "reports indexes in UTF-8 text as unicode character offsets" do
match = RE2::Regexp.new(".(ら)").match("世界中のあらゆ")
match.end(0).must_equal(6)
end
it "reports indexes for named captures" do
match = RE2::Regexp.new(".(?P<capture>ら).").match("世界中のあらゆ")
match.end(:capture).must_equal(6)
end
end
describe "#string" do
it "returns the original string to match against" do
re = RE2::Regexp.new('(\D+)').match("bob")
re.string.must_equal("bob")
end
it "returns a copy, not the actual original" do
string = "bob"
re = RE2::Regexp.new('(\D+)').match(string)
re.string.wont_be_same_as(string)
end
it "returns a frozen string" do
re = RE2::Regexp.new('(\D+)').match("bob")
re.string.must_be(:frozen?)
end
end
describe "#size" do
it "returns the number of capturing groups plus the matching string" do
md = RE2::Regexp.new('(\d+) (\d+)').match("1234 56")
md.size.must_equal(3)
end
end
describe "#length" do
it "returns the number of capturing groups plus the matching string" do
md = RE2::Regexp.new('(\d+) (\d+)').match("1234 56")
md.length.must_equal(3)
end
end
describe "#regexp" do
it "returns the original RE2::Regexp used" do
re = RE2::Regexp.new('(\d+)')
md = re.match("123")
md.regexp.must_be_same_as(re)
end
end
describe "#inspect" do
it "returns a text representation of the object and indices" do
md = RE2::Regexp.new('(\d+) (\d+)').match("1234 56")
md.inspect.must_equal('#<RE2::MatchData "1234 56" 1:"1234" 2:"56">')
end
it "represents missing matches as nil" do
md = RE2::Regexp.new('(\d+) (\d+)?').match("1234 ")
md.inspect.must_equal('#<RE2::MatchData "1234 " 1:"1234" 2:nil>')
end
end
describe "#to_s" do
it "returns the matching part of the original string" do
md = RE2::Regexp.new('(\d{2,5})').match("one two 23456")
md.to_s.must_equal("23456")
end
end
describe "#to_ary" do
it "allows the object to be expanded with an asterisk" do
md = RE2::Regexp.new('(\d+) (\d+)').match("1234 56")
m1, m2, m3 = *md
m1.must_equal("1234 56")
m2.must_equal("1234")
m3.must_equal("56")
end
end
end
|
greensnark/re2
|
spec/kernel_spec.rb
|
<gh_stars>0
require "spec_helper"
describe Kernel do
describe "#RE2" do
it "returns an RE2::Regexp instance given a pattern" do
RE2('w(o)(o)').must_be_instance_of(RE2::Regexp)
end
it "returns an RE2::Regexp instance given a pattern and options" do
re = RE2('w(o)(o)', :case_sensitive => false)
re.must_be_instance_of(RE2::Regexp)
re.wont_be(:case_sensitive?)
end
end
end
|
greensnark/re2
|
ext/re2/extconf.rb
|
# re2 (http://github.com/mudge/re2)
# Ruby bindings to re2, an "efficient, principled regular expression library"
#
# Copyright (c) 2010-2012, <NAME> (http://mudge.name)
# Released under the BSD Licence, please see LICENSE.txt
require 'mkmf'
incl, lib = dir_config("re2", "/usr/local/include", "/usr/local/lib")
$CFLAGS << " -Wall -Wextra -funroll-loops"
have_library("stdc++")
if have_library("re2")
# Determine which version of re2 the user has installed.
# Revision d9f8806c004d added an `endpos` argument to the
# generic Match() function.
#
# To test for this, try to compile a simple program that uses
# the newer form of Match() and set a flag if it is successful.
checking_for("RE2::Match() with endpos argument") do
test_re2_match_signature = <<SRC
#include <re2/re2.h>
int main() {
RE2 pattern("test");
re2::StringPiece *match;
pattern.Match("test", 0, 0, RE2::UNANCHORED, match, 0);
return 0;
}
SRC
# Pass -x c++ to force gcc to compile the test program
# as C++ (as it will end in .c by default).
if try_compile(test_re2_match_signature, "-x c++")
$defs.push("-DHAVE_ENDPOS_ARGUMENT")
end
end
create_makefile("re2")
else
abort "You must have re2 installed and specified with --with-re2-dir, please see http://code.google.com/p/re2/wiki/Install"
end
|
greensnark/re2
|
spec/re2/consumer_spec.rb
|
<reponame>greensnark/re2
require "spec_helper"
describe RE2::Consumer do
describe "#regexp" do
it "returns the original pattern for the consumer" do
re = RE2::Regexp.new('(\w+)')
consumer = re.consume("It is a truth")
consumer.regexp.must_be_same_as(re)
end
end
describe "#string" do
it "returns the original text for the consumer" do
re = RE2::Regexp.new('(\w+)')
text = "It is a truth"
consumer = re.consume(text)
consumer.string.must_be_same_as(text)
end
end
describe "#consume" do
it "returns the next array of matches" do
r = RE2::Regexp.new('(\w+)')
consumer = r.consume("It is a truth universally acknowledged")
consumer.consume.must_equal(["It"])
consumer.consume.must_equal(["is"])
consumer.consume.must_equal(["a"])
consumer.consume.must_equal(["truth"])
consumer.consume.must_equal(["universally"])
consumer.consume.must_equal(["acknowledged"])
consumer.consume.must_be_nil
end
it "returns an empty array if there are no capturing groups" do
r = RE2::Regexp.new('\w+')
consumer = r.consume("Foo bar")
consumer.consume.must_equal([])
end
it "returns nil if there is no match" do
r = RE2::Regexp.new('\d+')
consumer = r.consume("Foo bar")
consumer.consume.must_be_nil
end
end
it "is enumerable" do
r = RE2::Regexp.new('(\d)')
consumer = r.consume("There are 1 some 2 numbers 3")
consumer.must_be_kind_of(Enumerable)
end
describe "#each" do
it "yields each match" do
r = RE2::Regexp.new('(\d)')
consumer = r.consume("There are 1 some 2 numbers 3")
matches = []
consumer.each do |match|
matches << match
end
matches.must_equal([["1"], ["2"], ["3"]])
end
it "returns an enumerator when not given a block" do
r = RE2::Regexp.new('(\d)')
consumer = r.consume("There are 1 some 2 numbers 3")
# Prior to Ruby 1.9, Enumerator was within Enumerable.
if defined?(Enumerator)
consumer.each.must_be_kind_of(Enumerator)
elsif defined?(Enumerable::Enumerator)
consumer.each.must_be_kind_of(Enumerable::Enumerator)
end
end
end
describe "#rewind" do
it "resets any consumption" do
r = RE2::Regexp.new('(\d)')
consumer = r.consume("There are 1 some 2 numbers 3")
consumer.to_enum.first.must_equal(["1"])
consumer.to_enum.first.must_equal(["2"])
consumer.rewind
consumer.to_enum.first.must_equal(["1"])
end
end
end
|
greensnark/re2
|
spec/re2/regexp_spec.rb
|
<reponame>greensnark/re2
# -*- coding: utf-8 -*-
require "spec_helper"
describe RE2::Regexp do
describe "#initialize" do
it "returns an instance given only a pattern" do
re = RE2::Regexp.new('woo')
re.must_be_instance_of(RE2::Regexp)
end
it "returns an instance given a pattern and options" do
re = RE2::Regexp.new('woo', :case_sensitive => false)
re.must_be_instance_of(RE2::Regexp)
end
end
describe "#compile" do
it "returns an instance given only a pattern" do
re = RE2::Regexp.compile('woo')
re.must_be_instance_of(RE2::Regexp)
end
it "returns an instance given a pattern and options" do
re = RE2::Regexp.compile('woo', :case_sensitive => false)
re.must_be_instance_of(RE2::Regexp)
end
end
describe "#options" do
it "returns a hash of options" do
options = RE2::Regexp.new('woo').options
options.must_be_instance_of(Hash)
end
it "is populated with default options when nothing has been set" do
options = RE2::Regexp.new('woo').options
assert options[:utf8]
refute options[:posix_syntax]
refute options[:longest_match]
assert [:log_errors]
refute options[:literal]
refute options[:never_nl]
assert options[:case_sensitive]
refute options[:perl_classes]
refute options[:word_boundary]
refute options[:one_line]
end
it "is populated with overridden options when specified" do
options = RE2::Regexp.new('woo', :case_sensitive => false).options
refute options[:case_sensitive]
end
end
describe "#error" do
it "returns nil if there is no error" do
error = RE2::Regexp.new('woo').error
error.must_be_nil
end
# Use log_errors => false to suppress RE2's logging to STDERR.
it "contains the error string if there is an error" do
error = RE2::Regexp.new('wo(o', :log_errors => false).error
error.must_equal("missing ): wo(o")
end
end
describe "#error_arg" do
it "returns nil if there is no error" do
error_arg = RE2::Regexp.new('woo').error_arg
error_arg.must_be_nil
end
it "returns the offending portin of the regexp if there is an error" do
error_arg = RE2::Regexp.new('wo(o', :log_errors => false).error_arg
error_arg.must_equal("wo(o")
end
end
describe "#program_size" do
it "returns a numeric value" do
program_size = RE2::Regexp.new('w(o)(o)').program_size
program_size.must_be_instance_of(Fixnum)
end
end
describe "#to_str" do
it "returns the original pattern" do
string = RE2::Regexp.new('w(o)(o)').to_str
string.must_equal("w(o)(o)")
end
end
describe "#pattern" do
it "returns the original pattern" do
pattern = RE2::Regexp.new('w(o)(o)').pattern
pattern.must_equal("w(o)(o)")
end
end
describe "#inspect" do
it "shows the class name and original pattern" do
string = RE2::Regexp.new('w(o)(o)').inspect
string.must_equal("#<RE2::Regexp /w(o)(o)/>")
end
end
describe "#utf8?" do
it "returns true by default" do
RE2::Regexp.new('woo').must_be(:utf8?)
end
it "can be overridden on initialization" do
re = RE2::Regexp.new('woo', :utf8 => false)
re.wont_be(:utf8?)
end
end
describe "#posix_syntax?" do
it "returns false by default" do
RE2::Regexp.new('woo').wont_be(:posix_syntax?)
end
it "can be overridden on initialization" do
re = RE2::Regexp.new('woo', :posix_syntax => true)
re.must_be(:posix_syntax?)
end
end
describe "#literal?" do
it "returns false by default" do
RE2::Regexp.new('woo').wont_be(:literal?)
end
it "can be overridden on initialization" do
re = RE2::Regexp.new('woo', :literal => true)
re.must_be(:literal?)
end
end
describe "#never_nl?" do
it "returns false by default" do
RE2::Regexp.new('woo').wont_be(:never_nl?)
end
it "can be overridden on initialization" do
re = RE2::Regexp.new('woo', :never_nl => true)
re.must_be(:never_nl?)
end
end
describe "#case_sensitive?" do
it "returns true by default" do
RE2::Regexp.new('woo').must_be(:case_sensitive?)
end
it "can be overridden on initialization" do
re = RE2::Regexp.new('woo', :case_sensitive => false)
re.wont_be(:case_sensitive?)
end
end
describe "#case_insensitive?" do
it "returns false by default" do
RE2::Regexp.new('woo').wont_be(:case_insensitive?)
end
it "can be overridden on initialization" do
re = RE2::Regexp.new('woo', :case_sensitive => false)
re.must_be(:case_insensitive?)
end
end
describe "#casefold?" do
it "returns true by default" do
RE2::Regexp.new('woo').wont_be(:casefold?)
end
it "can be overridden on initialization" do
re = RE2::Regexp.new('woo', :case_sensitive => false)
re.must_be(:casefold?)
end
end
describe "#longest_match?" do
it "returns false by default" do
RE2::Regexp.new('woo').wont_be(:casefold?)
end
it "can be overridden on initialization" do
re = RE2::Regexp.new('woo', :longest_match => true)
re.must_be(:longest_match?)
end
end
describe "#log_errors?" do
it "returns true by default" do
RE2::Regexp.new('woo').must_be(:log_errors?)
end
it "can be overridden on initialization" do
re = RE2::Regexp.new('woo', :log_errors => false)
re.wont_be(:log_errors?)
end
end
describe "#perl_classes?" do
it "returns false by default" do
RE2::Regexp.new('woo').wont_be(:perl_classes?)
end
it "can be overridden on initialization" do
re = RE2::Regexp.new('woo', :perl_classes => true)
re.must_be(:perl_classes?)
end
end
describe "#word_boundary?" do
it "returns false by default" do
RE2::Regexp.new('woo').wont_be(:word_boundary?)
end
it "can be overridden on initialization" do
re = RE2::Regexp.new('woo', :word_boundary => true)
re.must_be(:word_boundary?)
end
end
describe "#one_line?" do
it "returns false by default" do
RE2::Regexp.new('woo').wont_be(:one_line?)
end
it "can be overridden on initialization" do
re = RE2::Regexp.new('woo', :one_line => true)
re.must_be(:one_line?)
end
end
describe "#max_mem" do
it "returns the default max memory" do
RE2::Regexp.new('woo').max_mem.must_equal(8388608)
end
it "can be overridden on initialization" do
re = RE2::Regexp.new('woo', :max_mem => 1024)
re.max_mem.must_equal(1024)
end
end
describe "#match" do
let(:re) { RE2::Regexp.new('My name is (\S+) (\S+)') }
it "returns match data given only text" do
md = re.match("My name is <NAME>")
md.must_be_instance_of(RE2::MatchData)
end
it "returns nil if there is no match for the given text" do
re.match("My age is 99").must_be_nil
end
it "returns only true or false if no matches are requested" do
re.match("My name is <NAME>", 0).must_equal(true)
re.match("My age is 99", 0).must_equal(false)
end
describe "with a specific number of matches under the total in the pattern" do
subject { re.match("My name is <NAME>", 1) }
it "returns a match data object" do
subject.must_be_instance_of(RE2::MatchData)
end
it "has the whole match and only the specified number of matches" do
subject.size.must_equal(2)
end
it "populates any specified matches" do
subject[1].must_equal("Robert")
end
it "does not populate any matches that weren't included" do
subject[2].must_be_nil
end
end
describe "with a number of matches over the total in the pattern" do
subject { re.match("My name is <NAME>", 5) }
it "returns a match data object" do
subject.must_be_instance_of(RE2::MatchData)
end
it "has the whole match the specified number of matches" do
subject.size.must_equal(6)
end
it "populates any specified matches" do
subject[1].must_equal("Robert")
subject[2].must_equal("Paulson")
end
it "pads the remaining matches with nil" do
subject[3].must_be_nil
subject[4].must_be_nil
subject[5].must_be_nil
subject[6].must_be_nil
end
end
describe "with negative number of matches" do
describe "with no capturing groups" do
let (:re) { RE2::Regexp.new('Hello, \S+') }
subject { re.match("Hello, sailor", -1) }
it "returns a match object" do
subject.must_be_instance_of(RE2::MatchData)
subject[0].must_equal('Hello, sailor')
end
end
describe "with capturing groups" do
let (:re) { RE2::Regexp.new('Hello, (\S+)') }
subject { re.match("Hello, sailor", -1) }
it "returns a match object" do
subject.must_be_instance_of(RE2::MatchData)
subject[0].must_equal('Hello, sailor')
end
it "returns captures" do
subject.must_be_instance_of(RE2::MatchData)
subject[0].must_equal('Hello, sailor')
subject[1].must_equal('sailor')
end
end
end
describe "with start offset" do
describe "general behavior" do
let (:re) { RE2::Regexp.new(".(.)") }
let (:text) { "世界中のあらゆ" }
it "will begin the match at the specified offset" do
re.match(text, -1, 2).begin.must_equal(2)
re.match(text, -1, 2)[1].must_equal("の")
end
end
describe "word boundaries" do
let (:re) { RE2::Regexp.new('\b([a-z])') }
let (:text) { "How now" }
it "will match word boundaries" do
re.match(text, 2)[1].must_equal('n')
re.match(text, 2).begin(1).must_equal(4)
end
end
end
end
describe "#match?" do
it "returns only true or false if no matches are requested" do
re = RE2::Regexp.new('My name is (\S+) (\S+)')
re.match?("My name is <NAME>").must_equal(true)
re.match?("My age is 99").must_equal(false)
end
end
describe "#=~" do
it "returns only true or false if no matches are requested" do
re = RE2::Regexp.new('My name is (\S+) (\S+)')
(re =~ "My name is <NAME>").must_equal(true)
(re =~ "My age is 99").must_equal(false)
end
end
describe "#!~" do
it "returns only true or false if no matches are requested" do
re = RE2::Regexp.new('My name is (\S+) (\S+)')
(re !~ "My name is <NAME>").must_equal(false)
(re !~ "My age is 99").must_equal(true)
end
end
describe "#===" do
it "returns only true or false if no matches are requested" do
re = RE2::Regexp.new('My name is (\S+) (\S+)')
(re === "My name is <NAME>").must_equal(true)
(re === "My age is 99").must_equal(false)
end
end
describe "#ok?" do
it "returns true for valid regexps" do
RE2::Regexp.new('woo').must_be(:ok?)
RE2::Regexp.new('wo(o)').must_be(:ok?)
RE2::Regexp.new('((\d)\w+){3,}').must_be(:ok?)
end
it "returns false for invalid regexps" do
RE2::Regexp.new('wo(o', :log_errors => false).wont_be(:ok?)
RE2::Regexp.new('wo[o', :log_errors => false).wont_be(:ok?)
RE2::Regexp.new('*', :log_errors => false).wont_be(:ok?)
end
end
describe "#escape" do
it "transforms a string into a regexp" do
RE2::Regexp.escape("1.5-2.0?").must_equal('1\.5\-2\.0\?')
end
end
describe "#quote" do
it "transforms a string into a regexp" do
RE2::Regexp.quote("1.5-2.0?").must_equal('1\.5\-2\.0\?')
end
end
describe "#number_of_capturing_groups" do
it "returns the number of groups in a regexp" do
RE2::Regexp.new('(a)(b)(c)').number_of_capturing_groups.must_equal(3)
RE2::Regexp.new('abc').number_of_capturing_groups.must_equal(0)
RE2::Regexp.new('a((b)c)').number_of_capturing_groups.must_equal(2)
end
end
describe "#named_capturing_groups" do
it "returns a hash of names to indices" do
RE2::Regexp.new('(?P<bob>a)').named_capturing_groups.must_be_instance_of(Hash)
end
it "maps names to indices with only one group" do
groups = RE2::Regexp.new('(?P<bob>a)').named_capturing_groups
groups["bob"].must_equal(1)
end
it "maps names to indices with several groups" do
groups = RE2::Regexp.new('(?P<bob>a)(o)(?P<rob>e)').named_capturing_groups
groups["bob"].must_equal(1)
groups["rob"].must_equal(3)
end
end
describe "#consume" do
it "returns a consumer" do
r = RE2::Regexp.new('(\w+)')
consumer = r.consume("It is a truth universally acknowledged")
consumer.must_be_instance_of(RE2::Consumer)
end
end
end
|
greensnark/re2
|
re2.gemspec
|
Gem::Specification.new do |s|
s.name = "re2"
s.summary = "Ruby bindings to re2."
s.description = 'Ruby bindings to re2, "an efficient, principled regular expression library".'
s.version = "0.6.0.pre"
s.authors = ["<NAME>"]
s.homepage = "http://github.com/mudge/re2"
s.email = "<EMAIL>"
s.extensions = ["ext/re2/extconf.rb"]
s.license = "BSD"
s.files = [
"ext/re2/extconf.rb",
"ext/re2/re2.cc",
"lib/re2.rb",
"lib/re2/consumer.rb",
"lib/re2/string.rb",
"LICENSE.txt",
"README.md",
"Rakefile"
]
s.test_files = [
"spec/spec_helper.rb",
"spec/re2_spec.rb",
"spec/kernel_spec.rb",
"spec/re2/regexp_spec.rb",
"spec/re2/match_data_spec.rb",
"spec/re2/string_spec.rb",
"spec/re2/consumer_spec.rb"
]
s.add_development_dependency("rake-compiler")
s.add_development_dependency("minitest")
end
|
greensnark/re2
|
spec/re2/string_spec.rb
|
<gh_stars>0
require "spec_helper"
require "re2/string"
class String
include RE2::String
end
describe RE2::String do
describe "#re2_sub!" do
it "delegates to RE2.Replace to perform replacement" do
"My name is <NAME>".re2_sub!('Robert', 'Crobert').must_equal("My name is <NAME>")
end
it "does perform an in-place replacement" do
string = "My name is <NAME>"
string.re2_sub!('Robert', 'Crobert').must_be_same_as(string)
end
end
describe "#re2_gsub!" do
it "delegates to RE2.GlobalReplace to perform replacement" do
"My name is <NAME>".re2_gsub!('a', 'e').must_equal("My neme is <NAME>")
end
it "does perform an in-place replacement" do
string = "My name is <NAME>"
string.re2_gsub!('a', 'e').must_be_same_as(string)
end
end
describe "#re2_sub" do
it "delegates to RE2.Replace to perform replacement" do
"My name is <NAME>".re2_sub('Robert', 'Crobert').must_equal("My name is <NAME>")
end
it "doesn't perform an in-place replacement" do
string = "My name is <NAME>"
string.re2_sub('Robert', 'Crobert').wont_be_same_as(string)
end
end
describe "#re2_gsub" do
it "delegates to RE2.GlobalReplace to perform replacement" do
"My name is <NAME>".re2_gsub('a', 'e').must_equal("My neme is <NAME>")
end
it "doesn't perform an in-place replacement" do
string = "My name is <NAME>"
string.re2_gsub('a', 'e').wont_be_same_as(string)
end
end
describe "#re2_match" do
it "delegates to RE2::Regexp#match to perform matches" do
md = "My name is <NAME>".re2_match('My name is (\S+) (\S+)')
md.must_be_instance_of(RE2::MatchData)
md[0].must_equal("My name is <NAME>")
md[1].must_equal("Robert")
md[2].must_equal("Paulson")
end
it "supports limiting the number of matches" do
md = "My name is <NAME>".re2_match('My name is (\S+) (\S+)', 0)
md.must_equal(true)
end
end
describe "#re2_escape" do
it "escapes the string for use in regular expressions" do
"1.5-2.0?".re2_escape.must_equal('1\.5\-2\.0\?')
end
end
describe "#re2_quote" do
it "escapes the string for use in regular expressions" do
"1.5-2.0?".re2_quote.must_equal('1\.5\-2\.0\?')
end
end
end
|
greensnark/re2
|
lib/re2/consumer.rb
|
<reponame>greensnark/re2<filename>lib/re2/consumer.rb<gh_stars>0
module RE2
class Consumer
include Enumerable
def each
if block_given?
while matches = consume
yield matches
end
else
to_enum(:each)
end
end
end
end
|
aidantwoods/secure_headers
|
spec/lib/secure_headers/middleware_spec.rb
|
<gh_stars>0
# frozen_string_literal: true
require "spec_helper"
module SecureHeaders
describe Middleware do
let(:app) { lambda { |env| [200, env, "app"] } }
let(:cookie_app) { lambda { |env| [200, env.merge("Set-Cookie" => "foo=bar"), "app"] } }
let(:middleware) { Middleware.new(app) }
let(:cookie_middleware) { Middleware.new(cookie_app) }
before(:each) do
reset_config
Configuration.default
end
it "warns if the hpkp report-uri host is the same as the current host" do
report_host = "report-uri.io"
reset_config
Configuration.default do |config|
config.hpkp = {
max_age: 10000000,
pins: [
{sha256: "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"},
{sha256: "73a2c64f9545172c1195efb6616ca5f7afd1df6f245407cafb90de3998a1c97f"}
],
report_uri: "https://#{report_host}/example-hpkp"
}
end
expect(Kernel).to receive(:warn).with(Middleware::HPKP_SAME_HOST_WARNING)
middleware.call(Rack::MockRequest.env_for("https://#{report_host}", {}))
end
it "sets the headers" do
_, env = middleware.call(Rack::MockRequest.env_for("https://looocalhost", {}))
expect_default_values(env)
end
it "respects overrides" do
request = Rack::Request.new("HTTP_X_FORWARDED_SSL" => "on")
SecureHeaders.override_x_frame_options(request, "DENY")
_, env = middleware.call request.env
expect(env[XFrameOptions::HEADER_NAME]).to eq("DENY")
end
it "uses named overrides" do
Configuration.override("my_custom_config") do |config|
config.csp[:script_src] = %w(example.org)
end
request = Rack::Request.new({})
SecureHeaders.use_secure_headers_override(request, "my_custom_config")
_, env = middleware.call request.env
expect(env[ContentSecurityPolicyConfig::HEADER_NAME]).to match("example.org")
end
context "cookies" do
before(:each) do
reset_config
end
context "cookies should be flagged" do
it "flags cookies as secure" do
Configuration.default { |config| config.cookies = {secure: true, httponly: OPT_OUT, samesite: OPT_OUT} }
request = Rack::Request.new("HTTPS" => "on")
_, env = cookie_middleware.call request.env
expect(env["Set-Cookie"]).to eq("foo=bar; secure")
end
end
it "allows opting out of cookie protection with OPT_OUT alone" do
Configuration.default { |config| config.cookies = OPT_OUT }
# do NOT make this request https. non-https requests modify a config,
# causing an exception when operating on OPT_OUT. This ensures we don't
# try to modify the config.
request = Rack::Request.new({})
_, env = cookie_middleware.call request.env
expect(env["Set-Cookie"]).to eq("foo=bar")
end
context "cookies should not be flagged" do
it "does not flags cookies as secure" do
Configuration.default { |config| config.cookies = {secure: OPT_OUT, httponly: OPT_OUT, samesite: OPT_OUT} }
request = Rack::Request.new("HTTPS" => "on")
_, env = cookie_middleware.call request.env
expect(env["Set-Cookie"]).to eq("foo=bar")
end
end
end
context "cookies" do
before(:each) do
reset_config
end
it "flags cookies from configuration" do
Configuration.default { |config| config.cookies = { secure: true, httponly: true, samesite: { lax: true} } }
request = Rack::Request.new("HTTPS" => "on")
_, env = cookie_middleware.call request.env
expect(env["Set-Cookie"]).to eq("foo=bar; secure; HttpOnly; SameSite=Lax")
end
it "flags cookies with a combination of SameSite configurations" do
cookie_middleware = Middleware.new(lambda { |env| [200, env.merge("Set-Cookie" => ["_session=foobar", "_guest=true"]), "app"] })
Configuration.default { |config| config.cookies = { samesite: { lax: { except: ["_session"] }, strict: { only: ["_session"] } }, httponly: OPT_OUT, secure: OPT_OUT} }
request = Rack::Request.new("HTTPS" => "on")
_, env = cookie_middleware.call request.env
expect(env["Set-Cookie"]).to match("_session=foobar; SameSite=Strict")
expect(env["Set-Cookie"]).to match("_guest=true; SameSite=Lax")
end
it "disables secure cookies for non-https requests" do
Configuration.default { |config| config.cookies = { secure: true, httponly: OPT_OUT, samesite: OPT_OUT } }
request = Rack::Request.new("HTTPS" => "off")
_, env = cookie_middleware.call request.env
expect(env["Set-Cookie"]).to eq("foo=bar")
end
it "sets the secure cookie flag correctly on interleaved http/https requests" do
Configuration.default { |config| config.cookies = { secure: true, httponly: OPT_OUT, samesite: OPT_OUT } }
request = Rack::Request.new("HTTPS" => "off")
_, env = cookie_middleware.call request.env
expect(env["Set-Cookie"]).to eq("foo=bar")
request = Rack::Request.new("HTTPS" => "on")
_, env = cookie_middleware.call request.env
expect(env["Set-Cookie"]).to eq("foo=bar; secure")
end
end
end
end
|
aidantwoods/secure_headers
|
spec/lib/secure_headers/headers/policy_management_spec.rb
|
# frozen_string_literal: true
require "spec_helper"
module SecureHeaders
describe PolicyManagement do
before(:each) do
reset_config
Configuration.default
end
let (:default_opts) do
{
default_src: %w(https:),
img_src: %w(https: data:),
script_src: %w('unsafe-inline' 'unsafe-eval' https: data:),
style_src: %w('unsafe-inline' https: about:),
report_uri: %w(/csp_report)
}
end
describe "#validate_config!" do
it "accepts all keys" do
# (pulled from README)
config = {
# "meta" values. these will shape the header, but the values are not included in the header.
report_only: false,
preserve_schemes: true, # default: false. Schemes are removed from host sources to save bytes and discourage mixed content.
# directive values: these values will directly translate into source directives
default_src: %w(https: 'self'),
frame_src: %w('self' *.twimg.com itunes.apple.com),
child_src: %w('self' *.twimg.com itunes.apple.com),
connect_src: %w(wss:),
font_src: %w('self' data:),
img_src: %w(mycdn.com data:),
manifest_src: %w(manifest.com),
media_src: %w(utoob.com),
object_src: %w('self'),
script_src: %w('self'),
style_src: %w('unsafe-inline'),
worker_src: %w(worker.com),
base_uri: %w('self'),
form_action: %w('self' github.com),
frame_ancestors: %w('none'),
plugin_types: %w(application/x-shockwave-flash),
block_all_mixed_content: true, # see [http://www.w3.org/TR/mixed-content/](http://www.w3.org/TR/mixed-content/)
upgrade_insecure_requests: true, # see https://www.w3.org/TR/upgrade-insecure-requests/
report_uri: %w(https://example.com/uri-directive)
}
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(config))
end
it "requires a :default_src value" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(script_src: %w('self')))
end.to raise_error(ContentSecurityPolicyConfigError)
end
it "requires a :script_src value" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_src: %w('self')))
end.to raise_error(ContentSecurityPolicyConfigError)
end
it "accepts OPT_OUT as a script-src value" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_src: %w('self'), script_src: OPT_OUT))
end.to_not raise_error
end
it "requires :report_only to be a truthy value" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_opts.merge(report_only: "steve")))
end.to raise_error(ContentSecurityPolicyConfigError)
end
it "requires :preserve_schemes to be a truthy value" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_opts.merge(preserve_schemes: "steve")))
end.to raise_error(ContentSecurityPolicyConfigError)
end
it "requires :block_all_mixed_content to be a boolean value" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_opts.merge(block_all_mixed_content: "steve")))
end.to raise_error(ContentSecurityPolicyConfigError)
end
it "requires :upgrade_insecure_requests to be a boolean value" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_opts.merge(upgrade_insecure_requests: "steve")))
end.to raise_error(ContentSecurityPolicyConfigError)
end
it "requires all source lists to be an array of strings" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_src: "steve"))
end.to raise_error(ContentSecurityPolicyConfigError)
end
it "allows nil values" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_src: %w('self'), script_src: ["https:", nil]))
end.to_not raise_error
end
it "rejects unknown directives / config" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_src: %w('self'), default_src_totally_mispelled: "steve"))
end.to raise_error(ContentSecurityPolicyConfigError)
end
# this is mostly to ensure people don't use the antiquated shorthands common in other configs
it "performs light validation on source lists" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_src: %w(self none inline eval), script_src: %w('self')))
end.to raise_error(ContentSecurityPolicyConfigError)
end
it "rejects anything not of the form allow-* as a sandbox value" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_opts.merge(sandbox: ["steve"])))
end.to raise_error(ContentSecurityPolicyConfigError)
end
it "accepts anything of the form allow-* as a sandbox value " do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_opts.merge(sandbox: ["allow-foo"])))
end.to_not raise_error
end
it "accepts true as a sandbox policy" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_opts.merge(sandbox: true)))
end.to_not raise_error
end
it "rejects anything not of the form type/subtype as a plugin-type value" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_opts.merge(plugin_types: ["steve"])))
end.to raise_error(ContentSecurityPolicyConfigError)
end
it "accepts anything of the form type/subtype as a plugin-type value " do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_opts.merge(plugin_types: ["application/pdf"])))
end.to_not raise_error
end
it "doesn't allow report_only to be set in a non-report-only config" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyConfig.new(default_opts.merge(report_only: true)))
end.to raise_error(ContentSecurityPolicyConfigError)
end
it "allows report_only to be set in a report-only config" do
expect do
ContentSecurityPolicy.validate_config!(ContentSecurityPolicyReportOnlyConfig.new(default_opts.merge(report_only: true)))
end.to_not raise_error
end
end
describe "#combine_policies" do
before(:each) do
reset_config
end
it "combines the default-src value with the override if the directive was unconfigured" do
Configuration.default do |config|
config.csp = {
default_src: %w(https:),
script_src: %w('self'),
}
end
default_policy = Configuration.dup
combined_config = ContentSecurityPolicy.combine_policies(default_policy.csp.to_h, style_src: %w(anothercdn.com))
csp = ContentSecurityPolicy.new(combined_config)
expect(csp.name).to eq(ContentSecurityPolicyConfig::HEADER_NAME)
expect(csp.value).to eq("default-src https:; script-src 'self'; style-src https: anothercdn.com")
end
it "combines directives where the original value is nil and the hash is frozen" do
Configuration.default do |config|
config.csp = {
default_src: %w('self'),
script_src: %w('self'),
report_only: false
}.freeze
end
report_uri = "https://report-uri.io/asdf"
default_policy = Configuration.dup
combined_config = ContentSecurityPolicy.combine_policies(default_policy.csp.to_h, report_uri: [report_uri])
csp = ContentSecurityPolicy.new(combined_config)
expect(csp.value).to include("report-uri #{report_uri}")
end
it "does not combine the default-src value for directives that don't fall back to default sources" do
Configuration.default do |config|
config.csp = {
default_src: %w('self'),
script_src: %w('self'),
report_only: false
}.freeze
end
non_default_source_additions = ContentSecurityPolicy::NON_FETCH_SOURCES.each_with_object({}) do |directive, hash|
hash[directive] = %w("http://example.org)
end
default_policy = Configuration.dup
combined_config = ContentSecurityPolicy.combine_policies(default_policy.csp.to_h, non_default_source_additions)
ContentSecurityPolicy::NON_FETCH_SOURCES.each do |directive|
expect(combined_config[directive]).to eq(%w("http://example.org))
end
end
it "overrides the report_only flag" do
Configuration.default do |config|
config.csp = {
default_src: %w('self'),
script_src: %w('self'),
report_only: false
}
end
default_policy = Configuration.dup
combined_config = ContentSecurityPolicy.combine_policies(default_policy.csp.to_h, report_only: true)
csp = ContentSecurityPolicy.new(combined_config)
expect(csp.name).to eq(ContentSecurityPolicyReportOnlyConfig::HEADER_NAME)
end
it "overrides the :block_all_mixed_content flag" do
Configuration.default do |config|
config.csp = {
default_src: %w(https:),
script_src: %w('self'),
block_all_mixed_content: false
}
end
default_policy = Configuration.dup
combined_config = ContentSecurityPolicy.combine_policies(default_policy.csp.to_h, block_all_mixed_content: true)
csp = ContentSecurityPolicy.new(combined_config)
expect(csp.value).to eq("default-src https:; block-all-mixed-content; script-src 'self'")
end
it "raises an error if appending to a OPT_OUT policy" do
Configuration.default do |config|
config.csp = OPT_OUT
end
default_policy = Configuration.dup
expect do
ContentSecurityPolicy.combine_policies(default_policy.csp.to_h, script_src: %w(anothercdn.com))
end.to raise_error(ContentSecurityPolicyConfigError)
end
end
end
end
|
aidantwoods/secure_headers
|
lib/secure_headers/headers/policy_management.rb
|
# frozen_string_literal: true
module SecureHeaders
module PolicyManagement
def self.included(base)
base.extend(ClassMethods)
end
DEFAULT_CONFIG = {
default_src: %w(https:),
img_src: %w(https: data: 'self'),
object_src: %w('none'),
script_src: %w(https:),
style_src: %w('self' 'unsafe-inline' https:),
form_action: %w('self')
}.freeze
DATA_PROTOCOL = "data:".freeze
BLOB_PROTOCOL = "blob:".freeze
SELF = "'self'".freeze
NONE = "'none'".freeze
STAR = "*".freeze
UNSAFE_INLINE = "'unsafe-inline'".freeze
UNSAFE_EVAL = "'unsafe-eval'".freeze
STRICT_DYNAMIC = "'strict-dynamic'".freeze
# leftover deprecated values that will be in common use upon upgrading.
DEPRECATED_SOURCE_VALUES = [SELF, NONE, UNSAFE_EVAL, UNSAFE_INLINE, "inline", "eval"].map { |value| value.delete("'") }.freeze
DEFAULT_SRC = :default_src
CONNECT_SRC = :connect_src
FONT_SRC = :font_src
FRAME_SRC = :frame_src
IMG_SRC = :img_src
MEDIA_SRC = :media_src
OBJECT_SRC = :object_src
SANDBOX = :sandbox
SCRIPT_SRC = :script_src
STYLE_SRC = :style_src
REPORT_URI = :report_uri
DIRECTIVES_1_0 = [
DEFAULT_SRC,
CONNECT_SRC,
FONT_SRC,
FRAME_SRC,
IMG_SRC,
MEDIA_SRC,
OBJECT_SRC,
SANDBOX,
SCRIPT_SRC,
STYLE_SRC,
REPORT_URI
].freeze
BASE_URI = :base_uri
CHILD_SRC = :child_src
FORM_ACTION = :form_action
FRAME_ANCESTORS = :frame_ancestors
PLUGIN_TYPES = :plugin_types
DIRECTIVES_2_0 = [
DIRECTIVES_1_0,
BASE_URI,
CHILD_SRC,
FORM_ACTION,
FRAME_ANCESTORS,
PLUGIN_TYPES
].flatten.freeze
# All the directives currently under consideration for CSP level 3.
# https://w3c.github.io/webappsec/specs/CSP2/
BLOCK_ALL_MIXED_CONTENT = :block_all_mixed_content
MANIFEST_SRC = :manifest_src
UPGRADE_INSECURE_REQUESTS = :upgrade_insecure_requests
WORKER_SRC = :worker_src
DIRECTIVES_3_0 = [
DIRECTIVES_2_0,
BLOCK_ALL_MIXED_CONTENT,
MANIFEST_SRC,
WORKER_SRC,
UPGRADE_INSECURE_REQUESTS
].flatten.freeze
ALL_DIRECTIVES = (DIRECTIVES_1_0 + DIRECTIVES_2_0 + DIRECTIVES_3_0).uniq.sort
# Think of default-src and report-uri as the beginning and end respectively,
# everything else is in between.
BODY_DIRECTIVES = ALL_DIRECTIVES - [DEFAULT_SRC, REPORT_URI]
DIRECTIVE_VALUE_TYPES = {
BASE_URI => :source_list,
BLOCK_ALL_MIXED_CONTENT => :boolean,
CHILD_SRC => :source_list,
CONNECT_SRC => :source_list,
DEFAULT_SRC => :source_list,
FONT_SRC => :source_list,
FORM_ACTION => :source_list,
FRAME_ANCESTORS => :source_list,
FRAME_SRC => :source_list,
IMG_SRC => :source_list,
MANIFEST_SRC => :source_list,
MEDIA_SRC => :source_list,
OBJECT_SRC => :source_list,
PLUGIN_TYPES => :media_type_list,
REPORT_URI => :source_list,
SANDBOX => :sandbox_list,
SCRIPT_SRC => :source_list,
STYLE_SRC => :source_list,
WORKER_SRC => :source_list,
UPGRADE_INSECURE_REQUESTS => :boolean
}.freeze
# These are directives that don't have use a source list, and hence do not
# inherit the default-src value.
NON_SOURCE_LIST_SOURCES = DIRECTIVE_VALUE_TYPES.select do |_, type|
type != :source_list
end.keys.freeze
# These are directives that take a source list, but that do not inherit
# the default-src value.
NON_FETCH_SOURCES = [
BASE_URI,
FORM_ACTION,
FRAME_ANCESTORS,
REPORT_URI
]
FETCH_SOURCES = ALL_DIRECTIVES - NON_FETCH_SOURCES - NON_SOURCE_LIST_SOURCES
STAR_REGEXP = Regexp.new(Regexp.escape(STAR))
HTTP_SCHEME_REGEX = %r{\Ahttps?://}
WILDCARD_SOURCES = [
UNSAFE_EVAL,
UNSAFE_INLINE,
STAR,
DATA_PROTOCOL,
BLOB_PROTOCOL
].freeze
META_CONFIGS = [
:report_only,
:preserve_schemes
].freeze
NONCES = [
:script_nonce,
:style_nonce
].freeze
module ClassMethods
# Public: generate a header name, value array that is user-agent-aware.
#
# Returns a default policy if no configuration is provided, or a
# header name and value based on the config.
def make_header(config)
return if config.nil? || config == OPT_OUT
header = new(config)
[header.name, header.value]
end
# Public: Validates each source expression.
#
# Does not validate the invididual values of the source expression (e.g.
# script_src => h*t*t*p: will not raise an exception)
def validate_config!(config)
return if config.nil? || config.opt_out?
raise ContentSecurityPolicyConfigError.new(":default_src is required") unless config.directive_value(:default_src)
if config.directive_value(:script_src).nil?
raise ContentSecurityPolicyConfigError.new(":script_src is required, falling back to default-src is too dangerous. Use `script_src: OPT_OUT` to override")
end
if !config.report_only? && config.directive_value(:report_only)
raise ContentSecurityPolicyConfigError.new("Only the csp_report_only config should set :report_only to true")
end
if config.report_only? && config.directive_value(:report_only) == false
raise ContentSecurityPolicyConfigError.new("csp_report_only config must have :report_only set to true")
end
ContentSecurityPolicyConfig.attrs.each do |key|
value = config.directive_value(key)
next unless value
if META_CONFIGS.include?(key)
raise ContentSecurityPolicyConfigError.new("#{key} must be a boolean value") unless boolean?(value) || value.nil?
elsif NONCES.include?(key)
raise ContentSecurityPolicyConfigError.new("#{key} must be a non-nil value") if value.nil?
else
validate_directive!(key, value)
end
end
end
# Public: combine the values from two different configs.
#
# original - the main config
# additions - values to be merged in
#
# raises an error if the original config is OPT_OUT
#
# 1. for non-source-list values (report_only, block_all_mixed_content, upgrade_insecure_requests),
# additions will overwrite the original value.
# 2. if a value in additions does not exist in the original config, the
# default-src value is included to match original behavior.
# 3. if a value in additions does exist in the original config, the two
# values are joined.
def combine_policies(original, additions)
if original == {}
raise ContentSecurityPolicyConfigError.new("Attempted to override an opt-out CSP config.")
end
original = Configuration.send(:deep_copy, original)
populate_fetch_source_with_default!(original, additions)
merge_policy_additions(original, additions)
end
def ua_to_variation(user_agent)
family = user_agent.browser
if family && VARIATIONS.key?(family)
family
else
OTHER
end
end
private
# merge the two hashes. combine (instead of overwrite) the array values
# when each hash contains a value for a given key.
def merge_policy_additions(original, additions)
original.merge(additions) do |directive, lhs, rhs|
if list_directive?(directive)
(lhs.to_a + rhs.to_a).compact.uniq
else
rhs
end
end.reject { |_, value| value.nil? || value == [] } # this mess prevents us from adding empty directives.
end
# Returns True if a directive expects a list of values and False otherwise.
def list_directive?(directive)
source_list?(directive) ||
sandbox_list?(directive) ||
media_type_list?(directive)
end
# For each directive in additions that does not exist in the original config,
# copy the default-src value to the original config. This modifies the original hash.
def populate_fetch_source_with_default!(original, additions)
# in case we would be appending to an empty directive, fill it with the default-src value
additions.each_key do |directive|
directive = if directive.to_s.end_with?("_nonce")
directive.to_s.gsub(/_nonce/, "_src").to_sym
else
directive
end
# Don't set a default if directive has an existing value
next if original[directive]
if FETCH_SOURCES.include?(directive)
original[directive] = original[DEFAULT_SRC]
end
end
end
def source_list?(directive)
DIRECTIVE_VALUE_TYPES[directive] == :source_list
end
def sandbox_list?(directive)
DIRECTIVE_VALUE_TYPES[directive] == :sandbox_list
end
def media_type_list?(directive)
DIRECTIVE_VALUE_TYPES[directive] == :media_type_list
end
# Private: Validates that the configuration has a valid type, or that it is a valid
# source expression.
def validate_directive!(directive, value)
ensure_valid_directive!(directive)
case ContentSecurityPolicy::DIRECTIVE_VALUE_TYPES[directive]
when :boolean
unless boolean?(value)
raise ContentSecurityPolicyConfigError.new("#{directive} must be a boolean. Found #{value.class} value")
end
when :sandbox_list
validate_sandbox_expression!(directive, value)
when :media_type_list
validate_media_type_expression!(directive, value)
when :source_list
validate_source_expression!(directive, value)
else
raise ContentSecurityPolicyConfigError.new("Unknown directive #{directive}")
end
end
# Private: validates that a sandbox token expression:
# 1. is an array of strings or optionally `true` (to enable maximal sandboxing)
# 2. For arrays, each element is of the form allow-*
def validate_sandbox_expression!(directive, sandbox_token_expression)
# We support sandbox: true to indicate a maximally secure sandbox.
return if boolean?(sandbox_token_expression) && sandbox_token_expression == true
ensure_array_of_strings!(directive, sandbox_token_expression)
valid = sandbox_token_expression.compact.all? do |v|
v.is_a?(String) && v.start_with?("allow-")
end
if !valid
raise ContentSecurityPolicyConfigError.new("#{directive} must be True or an array of zero or more sandbox token strings (ex. allow-forms)")
end
end
# Private: validates that a media type expression:
# 1. is an array of strings
# 2. each element is of the form type/subtype
def validate_media_type_expression!(directive, media_type_expression)
ensure_array_of_strings!(directive, media_type_expression)
valid = media_type_expression.compact.all? do |v|
# All media types are of the form: <type from RFC 2045> "/" <subtype from RFC 2045>.
v =~ /\A.+\/.+\z/
end
if !valid
raise ContentSecurityPolicyConfigError.new("#{directive} must be an array of valid media types (ex. application/pdf)")
end
end
# Private: validates that a source expression:
# 1. is an array of strings
# 2. does not contain any deprecated, now invalid values (inline, eval, self, none)
#
# Does not validate the invididual values of the source expression (e.g.
# script_src => h*t*t*p: will not raise an exception)
def validate_source_expression!(directive, source_expression)
if source_expression != OPT_OUT
ensure_array_of_strings!(directive, source_expression)
end
ensure_valid_sources!(directive, source_expression)
end
def ensure_valid_directive!(directive)
unless ContentSecurityPolicy::ALL_DIRECTIVES.include?(directive)
raise ContentSecurityPolicyConfigError.new("Unknown directive #{directive}")
end
end
def ensure_array_of_strings!(directive, value)
if (!value.is_a?(Array) || !value.compact.all? { |v| v.is_a?(String) })
raise ContentSecurityPolicyConfigError.new("#{directive} must be an array of strings")
end
end
def ensure_valid_sources!(directive, source_expression)
return if source_expression == OPT_OUT
source_expression.each do |expression|
if ContentSecurityPolicy::DEPRECATED_SOURCE_VALUES.include?(expression)
raise ContentSecurityPolicyConfigError.new("#{directive} contains an invalid keyword source (#{expression}). This value must be single quoted.")
end
end
end
def boolean?(source_expression)
source_expression.is_a?(TrueClass) || source_expression.is_a?(FalseClass)
end
end
end
end
|
Pazzik/barbershop
|
app.rb
|
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require 'sqlite3'
def get_db
db = SQLite3::Database.new 'barbershop.db'
db.results_as_hash = true
return db
end
def is_barber_exist? db,person
db.execute('select * from Persons where person=?',[person]).length > 0
end
def seed_db db, persons
persons.each do |person|
unless is_barber_exist? db,person
db.execute 'INSERT INTO Persons (person) values(?)',person
end
end
end
before do
db = get_db
@persons = db.execute 'select * from Persons'
end
configure do
db = get_db
db.execute 'CREATE TABLE IF NOT EXISTS
"Users"
(
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"username" TEXT,
"phone" TEXT,
"datestamp" TEXT,
"person" TEXT,
"color" TEXT
)'
db.execute 'CREATE TABLE IF NOT EXISTS
"Persons"
(
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"person" TEXT
)'
seed_db db, ['<NAME>','<NAME>','<NAME>']
end
get '/' do
erb "Hello! <a href=\"https://github.com/bootstrap-ruby/sinatra-bootstrap\">Original</a> pattern has been modified for <a href=\"http://rubyschool.us/\">Ruby School</a>"
end
get '/about' do
erb :about
end
get '/visit' do
erb :visit
end
get '/contacts' do
erb :contacts
end
get '/showusers' do
@users = []
db = get_db
db.execute 'select * from Users order by id desc' do |row|
@users << row
end
erb :showusers
end
post '/visit' do
@username = params[:username]
@phone = params[:phone]
@date_time = params[:date_time]
@person = params[:person]
@color = params[:color_picker]
hh = { :username => 'Enter your name',
:phone => 'Enter your phone',
:date_time => 'Enter date and time'}
hh.each do |key,value|
if params[key] == ''
@error = hh[key]
return erb :visit
end
end
db = get_db
db.execute 'INSERT INTO
Users
(
username,
phone,
datestamp,
person,
color
)
values(?,?,?,?,?)', [@username,@phone,@date_time,@person,@color]
f = File.open("./public/users.txt", "a")
f.write("User: #{@username} Phone: #{@phone} Date and Time: #{@date_time} Person: #{@person} Color: #{@color}\n");
f.close;
erb "<h2>Thanks for visit</h2>"
end
|
annomusa/MonoDylib
|
MonoDylib.podspec
|
<reponame>annomusa/MonoDylib<filename>MonoDylib.podspec<gh_stars>0
#
# Always run `pod lib lint MonoDylib.podspec' before pushing to git
# Syntax: https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'MonoDylib'
s.version = '0.1.1'
s.summary = 'This pod contains binaries of several MonoDylib, such as MarketplaceMonoDylib'
s.description = <<-DESC
Monodylib is a single framework that contains multiple libraries and expose it to user.
DESC
s.homepage = 'https://github.com/annomusa/MonoDylib'
s.author = { 'annomusa' => '<EMAIL>' }
s.source = { :http => "https://github.com/annomusa/MonoDylib/releases/download/#{s.version.to_s}/MonoDylib.zip" }
s.default_subspec = 'Marketplace'
s.ios.deployment_target = '11.0'
s.subspec 'Marketplace' do |sc|
sc.vendored_framework = 'MonoDylib/Marketplace/MarketplaceMonoDylib.xcframework'
sc.user_target_xcconfig = {
'SWIFT_INCLUDE_PATHS' => '$(PODS_XCFRAMEWORKS_BUILD_DIR)/MonoDylib/Marketplace/MarketplaceMonoDylib.framework/Modules'
}
end
end
|
kerven88/tubekit
|
tubekit.rb
|
<filename>tubekit.rb
class Tubekit < Formula
desc "Tool that helps you to operate Kubernetes clusters more effectively"
homepage "https://github.com/reconquest/tubekit"
url "https://github.com/reconquest/tubekit/releases/download/v3/tubekit_3_Darwin_x86_64.tar.gz"
sha256 "b966e7b014e0d16e22f0d15dbd7c80a084160c6851bf7ad767d0085ac3ac10d1"
bottle :unneeded
depends_on "kubernetes-cli"
def install
bin.install "tubectl"
end
test do
system "#{bin}/tubectl", "--tube-version"
assert_match /usage/i, shell_output("#{bin}/tubectl --tube-help")
end
end
|
jackg0h/cookie-brutefocer
|
twitter.rb
|
require 'mechanize'
def run
found = "nope"
key = "auth_token"
url = "https://twitter.com"
agent = Mechanize.new
count = 0
while found == "nope" do
#value = SecureRandom.urlsafe_base64
value = SecureRandom.hex(20)
cookie = Mechanize::Cookie.new(key, value)
cookie.domain = ".twitter.com"
cookie.path = "/"
agent.cookie_jar.add(cookie)
page = agent.get(url) #Get the starting page
link = page.link_with(:text => "Forgot password?")
print(value)
#if link = page.link_with(:text => "Sign in") # As long as there is still a nextpage link...
if link
agent.cookie_jar.clear!
else
#print "authorize\n"
found = "yes"
open('token.txt', 'a') { |f|
f.puts value
}
end
count = count + 1
end
print count
end
puts "Started At #{Time.now}"
puts "Running..."
threads = (1..10).map do |i|
Thread.new(i) do |i|
run
end
end
threads.each {|t| t.join}
puts "End at #{Time.now}"
|
ronin/payu
|
lib/payu.rb
|
# encoding: utf-8
require 'yaml'
require 'payu/version'
require 'payu/pos'
require 'payu/timestamp'
require 'payu/transaction'
require 'payu/response'
require 'payu/signature'
require 'payu/errors'
module Payu
ENCODINGS = ['ISO', 'WIN', 'UTF']
@@pos_table = {}
class SignatureInvalid < StandardError; end
class PosNotFound < StandardError; end
class RequestFailed < StandardError; end
class PosInvalid < StandardError; end
class TransactionInvalid < StandardError; end
class << self
# Loads configuration from specified YAML file creates Pos objects
def load_pos_from_yaml(filename)
if File.exist?(filename)
config = YAML.load_file(filename)
config.each do |name, config|
pos = Pos.new(
:pos_id => config['pos_id'],
:pos_auth_key => config['pos_auth_key'],
:key1 => config['key1'],
:key2 => config['key2'],
:gateway_url => config['gateway_url'],
:variant => config['variant'],
:add_signature => config['add_signature'],
:test_payment => config['test_payment']
)
@@pos_table[name] = pos
end
true
else
false
end
end
def add_pos(name, pos)
@@pos_table[name.to_s] = pos
end
# Combined accessor, returns Pos object with given pos_id or name
#
# @param [String, Integer] name_or_id name or pos_id of Pos
# @return [Object] the Pos object
def [](name_or_id)
get_pos_by_name(name_or_id) || get_pos_by_id(name_or_id) || raise(PosNotFound)
end
# Returns Pos object with given name, the same as in payments.yml file
#
# @param [String] name name of Pos
# @return [Object] the Pos object
def get_pos_by_name(name)
@@pos_table[name.to_s]
end
# Returns Pos object with given pos_id, the same as in payments.yml file
#
# @param [Integer] id pos_id of Pos
# @return [Object] the Pos object
def get_pos_by_id(pos_id)
pos_id = pos_id.to_i rescue 0
@@pos_table.each do |k, v|
return v if v.pos_id == pos_id
end
nil
end
end
end
if defined?(Rails)
require "payu/helpers"
ActionView::Base.send(:include, Payu::Helpers)
ActionController::Base.send(:include, Payu::Helpers)
end
|
johanesteves/rails-workout-app
|
config/routes.rb
|
Rails.application.routes.draw do
devise_for :users, :controllers => { registrations: 'registrations', :omniauth_callbacks => "users/omniauth_callbacks" }
root 'application#index'
get 'workouts/current_week', to: 'workouts#current_week', as: 'workout_current_week'
resources :workouts
get 'workouts/:id/exercises', to: 'workouts#exercises', as: 'workout_exercises'
resources :exercises
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
kandayo/likee
|
spec/integration/video_comments_spec.rb
|
<reponame>kandayo/likee
# frozen_string_literal: true
RSpec.describe 'Video Comments' do
before do
WebMock.allow_net_connect!
end
after do
WebMock.disable_net_connect!
end
it 'returns video comments' do
api = Likee::Api.new
collection = api.video_comments(video_id: '7025013457556632887')
expect(collection).to be_any
end
end
|
kandayo/likee
|
spec/integration/user_videos_spec.rb
|
<reponame>kandayo/likee<filename>spec/integration/user_videos_spec.rb
# frozen_string_literal: true
RSpec.describe 'Creator Videos' do
before do
WebMock.allow_net_connect!
end
after do
WebMock.disable_net_connect!
end
it 'returns creator videos' do
api = Likee::Api.new
collection = api.creator_videos(creator_id: '30007')
expect(collection).to be_any
end
end
|
kandayo/likee
|
spec/integration/trending_hashtags_spec.rb
|
<reponame>kandayo/likee
# frozen_string_literal: true
RSpec.describe 'Trending Hashtags' do
before do
WebMock.allow_net_connect!
end
after do
WebMock.disable_net_connect!
end
it 'returns trending hashtags' do
api = Likee::Api.new
collection = api.trending_hashtags
expect(collection).to be_any
end
end
|
kandayo/likee
|
lib/likee/mappings/hashtag_collection_mapping.rb
|
# frozen_string_literal: true
require_relative 'hashtag_mapping'
module Likee
class HashtagCollectionMapping
def self.call(data)
new(data).call
end
def initialize(data)
@data = data
freeze
end
def call
collection = data.dig('data', 'eventList')
return [] if collection.nil? || !collection.is_a?(Array)
collection.map do |hashtag_data|
Likee::HashtagMapping.(hashtag_data)
end
end
private
attr_reader :data
end
end
|
kandayo/likee
|
lib/likee/mappings/hashtag_mapping.rb
|
# frozen_string_literal: true
require_relative '../models/hashtag'
module Likee
class HashtagMapping
def self.call(data)
new(data).call
end
def initialize(data)
@data = data
freeze
end
def call
Hashtag.new(
id:,
name:,
videos_count:,
play_count:
)
end
private
attr_reader :data
def id
data['eventId']
end
def name
data['tagName']
end
def videos_count
data['postCnt'].to_i
end
def play_count
data['playCnt'].to_i
end
end
end
|
kandayo/likee
|
lib/likee/mappings/creator_mapping.rb
|
# frozen_string_literal: true
require_relative '../models/creator'
module Likee
class CreatorMapping
def self.call(data)
new(data).call
end
def initialize(data)
@data = data
freeze
end
def call
Creator.new(
id:,
username:,
nickname:,
avatar_url:,
country:,
gender:,
birthday:,
star_sign:,
bio:,
likes_count:,
fans_count:,
following_count:
)
end
private
attr_reader :data
def id
data['uid']
end
def username
data['likeeId']
end
def nickname
data['nick_name']
end
def avatar_url
data['bigUrl']
end
def country
data['exactCountryCode']
end
def gender
case data['gender']
when 0 then :male
when 1 then :female
else
:unknown
end
end
def birthday
birthday_string = data['birthday']
return unless birthday_string
Date.parse(birthday_string)
end
def star_sign
data['constellation']
end
def bio
data['bio']
end
def likes_count
data['allLikeCount']
end
def fans_count
data['fansCount']
end
def following_count
data['followCount']
end
end
end
|
kandayo/likee
|
spec/factories/config.rb
|
# frozen_string_literal: true
FactoryBot.define do
factory :config, class: Likee::Configuration do
user_agent { 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' }
referer { 'https://likee.video/' }
custom_device_id { nil }
custom_user_id { nil }
open_timeout { 5 }
read_timeout { 5 }
write_timeout { 5 }
keep_alive_idle_timeout { 45 }
proxy { nil }
initialize_with do
new(
user_agent:,
referer:,
custom_device_id:,
custom_user_id:,
open_timeout:,
read_timeout:,
write_timeout:,
keep_alive_idle_timeout:,
proxy:
)
end
end
end
|
kandayo/likee
|
lib/likee/resources/comment_resource_collection.rb
|
# frozen_string_literal: true
require_relative 'resource_collection'
require_relative 'comment_resource'
module Likee
class CommentResourceCollection < ResourceCollection
def resource_class
CommentResource
end
def fetch_resource(cursor:)
api.video_comments(video_id: video.id, cursor:)
end
def video
parent
end
end
end
|
kandayo/likee
|
lib/likee/resources/video_resource_collection.rb
|
<reponame>kandayo/likee
# frozen_string_literal: true
require_relative 'resource_collection'
require_relative 'video_resource'
module Likee
class VideoResourceCollection < ResourceCollection
def resource_class
VideoResource
end
def fetch_resource(cursor:)
api.creator_videos(creator_id: creator.id, cursor:)
end
def creator
parent
end
end
end
|
kandayo/likee
|
lib/likee/resources/creator_resource.rb
|
<reponame>kandayo/likee
# frozen_string_literal: true
require_relative 'resource'
require_relative 'video_resource_collection'
module Likee
class CreatorResource < Resource
def self.find(username, api:)
resource = api.find_creator(username)
new(api:, resource:)
end
def videos
@videos ||= VideoResourceCollection.new(api:, parent: self)
end
end
end
|
kandayo/likee
|
spec/likee/client_spec.rb
|
# frozen_string_literal: true
RSpec.describe Likee::Client do
let(:api) { double(:api) }
subject { described_class.new(api_class: api) }
describe '#find_creator' do
let(:creator) { build(:creator) }
let(:creator_videos_page1) { build_list(:video, 5) }
let(:creator_videos_page2) { build_list(:video, 5) }
let(:creator_videos_page3) { [] }
let(:comments_page1) { build_list(:comment, 5) }
let(:comments_page2) { build_list(:comment, 5) }
let(:comments_page3) { [] }
it 'paginates through the creator profile' do
expect(api).to receive(:new) { api }
expect(api).to receive(:find_creator).with('username') { creator }
expect(api)
.to receive(:creator_videos)
.with(creator_id: creator.id, cursor: 0)
.and_return(creator_videos_page1)
expect(api)
.to receive(:creator_videos)
.with(creator_id: creator.id, cursor: creator_videos_page1.last.id)
.and_return(creator_videos_page2)
expect(api)
.to receive(:creator_videos)
.with(creator_id: creator.id, cursor: creator_videos_page2.last.id)
.and_return(creator_videos_page3)
creator = subject.find_creator('username')
expect(creator.id).to eq(creator.id)
expect(creator.username).to eq(creator.username)
expect(creator.avatar_url).to eq(creator.avatar_url)
expect(creator.country).to eq(creator.country)
expect(creator.gender).to eq(creator.gender)
expect(creator.birthday).to eq(creator.birthday)
expect(creator.star_sign).to eq(creator.star_sign)
expect(creator.bio).to eq(creator.bio)
expect(creator.likes_count).to eq(creator.likes_count)
expect(creator.fans_count).to eq(creator.fans_count)
expect(creator.following_count).to eq(creator.following_count)
returned_video_ids = creator.videos.map { |video| video.id.to_s }
expected_video_ids = (creator_videos_page1 + creator_videos_page2 + creator_videos_page3).map { |video| video.id.to_s }
expect(returned_video_ids).to match_array(expected_video_ids)
end
it 'paginates through video comments' do
expect(api).to receive(:new) { api }
expect(api).to receive(:find_creator).with('username') { creator }
expect(api)
.to receive(:creator_videos)
.with(creator_id: creator.id, cursor: 0)
.and_return(creator_videos_page1)
creator = subject.find_creator('username')
video = creator.videos.first
expect(api)
.to receive(:video_comments)
.with(video_id: video.id, cursor: 0)
.and_return(comments_page1)
expect(api)
.to receive(:video_comments)
.with(video_id: video.id, cursor: comments_page1.last.id)
.and_return(comments_page2)
expect(api)
.to receive(:video_comments)
.with(video_id: video.id, cursor: comments_page2.last.id)
.and_return(comments_page3)
returned_comment_ids = video.comments.map { |comment| comment.id.to_s }
expected_comment_ids = (comments_page1 + comments_page2 + comments_page3).map { |comment| comment.id.to_s }
expect(returned_comment_ids).to match_array(expected_comment_ids)
end
it 'associates creator and its videos' do
expect(api).to receive(:new) { api }
expect(api).to receive(:find_creator).with('username') { creator }
expect(api)
.to receive(:creator_videos)
.with(creator_id: creator.id, cursor: 0)
.and_return(creator_videos_page1)
creator = subject.find_creator('username')
video = creator.videos.first
expect(video.creator).to eq(creator)
end
it 'associates videos and its comments' do
expect(api).to receive(:new) { api }
expect(api).to receive(:find_creator).with('username') { creator }
expect(api)
.to receive(:creator_videos)
.with(creator_id: creator.id, cursor: 0)
.and_return(creator_videos_page1)
creator = subject.find_creator('username')
video = creator.videos.first
expect(api)
.to receive(:video_comments)
.with(video_id: video.id, cursor: 0)
.and_return(comments_page1)
comment = video.comments.first
expect(comment.video).to eq(video)
end
it 'reads creator properties' do
expect(api).to receive(:new) { api }
expect(api).to receive(:find_creator).with('username') { creator }
creator = subject.find_creator('username')
expect(creator.id).to eq(creator.id)
expect(creator.username).to eq(creator.username)
expect(creator.avatar_url).to eq(creator.avatar_url)
expect(creator.country).to eq(creator.country)
expect(creator.gender).to eq(creator.gender)
expect(creator.birthday).to eq(creator.birthday)
expect(creator.star_sign).to eq(creator.star_sign)
expect(creator.bio).to eq(creator.bio)
expect(creator.likes_count).to eq(creator.likes_count)
expect(creator.fans_count).to eq(creator.fans_count)
expect(creator.following_count).to eq(creator.following_count)
end
it 'reads video properties' do
expect(api).to receive(:new) { api }
expect(api).to receive(:find_creator).with('username') { creator }
expect(api)
.to receive(:creator_videos)
.with(creator_id: creator.id, cursor: 0)
.and_return(creator_videos_page1)
creator = subject.find_creator('username')
video = creator.videos.first
expect(video.id).to eq(creator_videos_page1[0].id)
expect(video.uploaded_at).to eq(creator_videos_page1[0].uploaded_at)
expect(video.creator_id).to eq(creator_videos_page1[0].creator_id)
expect(video.creator_username).to eq(creator_videos_page1[0].creator_username)
expect(video.creator_nickname).to eq(creator_videos_page1[0].creator_nickname)
expect(video.creator_avatar_url).to eq(creator_videos_page1[0].creator_avatar_url)
expect(video.title).to eq(creator_videos_page1[0].title)
expect(video.description).to eq(creator_videos_page1[0].description)
expect(video.height).to eq(creator_videos_page1[0].height)
expect(video.width).to eq(creator_videos_page1[0].width)
expect(video.thumbnail_url).to eq(creator_videos_page1[0].thumbnail_url)
expect(video.url).to eq(creator_videos_page1[0].url)
expect(video.sound_id).to eq(creator_videos_page1[0].sound_id)
expect(video.sound_name).to eq(creator_videos_page1[0].sound_name)
expect(video.sound_owner_name).to eq(creator_videos_page1[0].sound_owner_name)
expect(video.sound_thumbnail).to eq(creator_videos_page1[0].sound_thumbnail)
expect(video.likes_count).to eq(creator_videos_page1[0].likes_count)
expect(video.comments_count).to eq(creator_videos_page1[0].comments_count)
expect(video.play_count).to eq(creator_videos_page1[0].play_count)
expect(video.share_count).to eq(creator_videos_page1[0].share_count)
expect(video.hashtags).to eq(creator_videos_page1[0].hashtags)
expect(video.mentions).to eq(creator_videos_page1[0].mentions)
expect(video.country).to eq(creator_videos_page1[0].country)
end
it 'reads comment properties' do
expect(api).to receive(:new) { api }
expect(api).to receive(:find_creator).with('username') { creator }
expect(api)
.to receive(:creator_videos)
.with(creator_id: creator.id, cursor: 0)
.and_return(creator_videos_page1)
creator = subject.find_creator('username')
video = creator.videos.first
expect(api)
.to receive(:video_comments)
.with(video_id: video.id, cursor: 0)
.and_return(comments_page1)
comment = video.comments.first
expect(comment.id).to eq(comments_page1[0].id)
expect(comment.created_at).to eq(comments_page1[0].created_at)
expect(comment.user_id).to eq(comments_page1[0].user_id)
expect(comment.user_username).to eq(comments_page1[0].user_username)
expect(comment.user_nickname).to eq(comments_page1[0].user_nickname)
expect(comment.user_avatar_url).to eq(comments_page1[0].user_avatar_url)
expect(comment.content).to eq(comments_page1[0].content)
expect(comment.likes_count).to eq(comments_page1[0].likes_count)
expect(comment.reply_user_id).to eq(comments_page1[0].reply_user_id)
expect(comment.reply_user_nickname).to eq(comments_page1[0].reply_user_nickname)
expect(comment.reply_content).to eq(comments_page1[0].reply_content)
end
end
describe '#trending_videos' do
let(:creator) { build(:creator) }
let(:trending_videos_page1) { build_list(:video, 5) }
let(:trending_videos_page2) { build_list(:video, 5) }
let(:trending_videos_page3) { [] }
it 'paginates through the trending videos' do
expect(api).to receive(:new) { api }
expect(api)
.to receive(:trending_videos)
.with(country: 'RU', language: 'ru', start: 0, cursor: 0)
.and_return(trending_videos_page1)
expect(api)
.to receive(:trending_videos)
.with(country: 'RU', language: 'ru', start: 0, cursor: trending_videos_page1.last.id)
.and_return(trending_videos_page2)
expect(api)
.to receive(:trending_videos)
.with(country: 'RU', language: 'ru', start: 0, cursor: trending_videos_page2.last.id)
.and_return(trending_videos_page3)
videos = subject.trending_videos(country: 'RU', language: 'ru')
returned_video_ids = videos.map { |video| video.id.to_s }
expected_video_ids = (trending_videos_page1 + trending_videos_page2 + trending_videos_page3).map { |video| video.id.to_s }
expect(returned_video_ids).to match_array(expected_video_ids)
end
it 'associates users and its creators' do
expect(api).to receive(:new) { api }
expect(api)
.to receive(:trending_videos)
.with(country: 'RU', language: 'ru', start: 0, cursor: 0)
.and_return(trending_videos_page1)
videos = subject.trending_videos(country: 'RU', language: 'ru')
video = videos.first
expect(api).to receive(:find_creator).with(video.creator_username) { creator }
expect(video.creator.id).to eq(creator.id)
end
end
end
|
kandayo/likee
|
lib/likee/resources/video_resource.rb
|
# frozen_string_literal: true
require_relative 'resource'
require_relative 'comment_resource_collection'
require_relative 'creator_resource'
module Likee
class VideoResource < Resource
def comments
@comments ||= CommentResourceCollection.new(api:, parent: self)
end
def creator
return parent unless parent.nil?
@creator ||= fetch_creator
end
private
def fetch_creator
CreatorResource.find(resource.creator_username, api:)
end
end
end
|
kandayo/likee
|
likee.gemspec
|
<reponame>kandayo/likee<gh_stars>1-10
# frozen_string_literal: true
require_relative 'lib/likee/version'
Gem::Specification.new do |spec|
spec.name = 'likee'
spec.version = Likee::VERSION
spec.authors = ['kandayo']
spec.email = ['<EMAIL>']
spec.summary = 'Likee API client for Ruby'
spec.description = 'A library designed to provide a stable and straightforward interface to the Likee API'
spec.homepage = 'https://github.com/kandayo/likee'
spec.license = 'BSD-3-Clause'
spec.required_ruby_version = '>= 3.1.0'
spec.metadata['homepage_uri'] = spec.homepage
spec.metadata['bug_tracker_uri'] = "#{spec.homepage}/issues"
spec.metadata['changelog_uri'] = "#{spec.homepage}/releases"
spec.metadata['documentation_uri'] = spec.homepage
spec.metadata['funding_uri'] = 'https://github.com/sponsors/kandayo'
spec.metadata['source_code_uri'] = spec.homepage
spec.metadata['rubygems_mfa_required'] = 'true'
spec.files = %w[LICENSE README.md] + Dir['lib/**/*'] + Dir['exe/**/*']
spec.require_paths = ['lib']
spec.bindir = 'exe'
spec.executables = []
spec.add_dependency 'net-http-persistent', '~> 4.0'
spec.add_development_dependency 'factory_bot', '~> 6.2'
spec.add_development_dependency 'oj', '~> 3.13', '>= 3.13.11'
spec.add_development_dependency 'pry', '~> 0.14.1'
spec.add_development_dependency 'rspec', '~> 3.10'
spec.add_development_dependency 'rubocop', '~> 1.24', '>= 1.24.1'
spec.add_development_dependency 'simplecov', '~> 0.21.2'
spec.add_development_dependency 'solargraph', '~> 0.44.2'
spec.add_development_dependency 'webmock', '~> 3.14'
end
|
kandayo/likee
|
spec/likee/mappings/comment_mapping_spec.rb
|
<reponame>kandayo/likee
# frozen_string_literal: true
RSpec.describe Likee::CommentMapping do
describe '#call' do
context 'comment with quote reply' do
let(:comment_data) { load_fixture('single_comment_with_reply') }
subject { described_class.new(comment_data) }
it 'parses the comment data' do
comment = subject.call
expect(comment.id).to eq(Likee::Snowflake.new('7048355918061286644'))
expect(comment.created_at).to eq(Time.at(1641073245))
expect(comment.user_id).to eq('445691124')
expect(comment.user_username).to eq('445691124')
expect(comment.user_nickname).to eq('ID:885806884')
expect(comment.content).to eq('hello')
expect(comment.reply_user_id).to eq('1629264715')
expect(comment.reply_user_nickname).to eq('<NAME> ')
expect(comment.reply_content).to eq('nice good video')
expect(comment.likes_count).to eq(0)
end
end
context 'single comment' do
let(:comment_data) { load_fixture('single_comment') }
subject { described_class.new(comment_data) }
it 'parses the comment data' do
comment = subject.call
expect(comment.id).to eq(Likee::Snowflake.new('7047285198079900385'))
expect(comment.created_at).to eq(Time.at(1640823948))
expect(comment.user_id).to eq('2926295777')
expect(comment.user_username).to eq('robbiecat4stream')
expect(comment.user_nickname).to eq('robbiecat gg dog')
expect(comment.content).to eq('early uuu')
expect(comment.reply_user_id).to be_nil
expect(comment.reply_user_nickname).to be_nil
expect(comment.reply_content).to be_nil
expect(comment.likes_count).to eq(2)
end
end
end
end
|
kandayo/likee
|
lib/likee/transport/exception_manager.rb
|
<reponame>kandayo/likee
# frozen_string_literal: true
module Likee
class Transport
class TransportError < StandardError
end
####
## Low level network errors
##
class ConnectionError < TransportError
end
class TimeoutError < ConnectionError
end
CONNECTION_ERROR_EXCEPTION_MESSAGE = 'Unexpected low level network error. (%<wrapped_exception_name>s)'
# rubocop:disable Layout/HashAlignment
NET_HTTP_EXCEPTIONS_MAP = {
IOError => ConnectionError,
EOFError => ConnectionError,
Errno::EADDRNOTAVAIL => ConnectionError,
Errno::ECONNABORTED => ConnectionError,
Errno::ECONNREFUSED => ConnectionError,
Errno::ECONNRESET => ConnectionError,
Errno::EHOSTDOWN => ConnectionError,
Errno::EHOSTUNREACH => ConnectionError,
Errno::EINVAL => ConnectionError,
Errno::ENETUNREACH => ConnectionError,
Errno::EPIPE => ConnectionError,
Errno::ETIMEDOUT => TimeoutError,
Net::HTTP::Persistent::Error => ConnectionError,
Net::HTTPBadResponse => ConnectionError,
Net::HTTPHeaderSyntaxError => ConnectionError,
Net::OpenTimeout => TimeoutError,
Net::ProtocolError => ConnectionError,
Net::ReadTimeout => TimeoutError,
Net::WriteTimeout => TimeoutError,
OpenSSL::SSL::SSLError => ConnectionError,
SocketError => ConnectionError
}.freeze
# rubocop:enable Layout/HashAlignment
####
## HTTP errors
##
class HTTPError < TransportError
attr_reader :response
def initialize(message, response)
super(message)
@response = response
end
end
class ServerError < HTTPError; end
class ClientError < HTTPError; end
class BadRequestError < HTTPError; end
class UnauthorizedError < HTTPError; end
class ForbiddenError < HTTPError; end
class NotFoundError < HTTPError; end
class ProxyAuthenticationRequired < HTTPError; end
class UnprocessableEntityError < HTTPError; end
class TooManyRequestsError < HTTPError; end
module ExceptionManager
def self.net_http_exceptions
NET_HTTP_EXCEPTIONS_MAP.keys
end
def self.build_exception_from_net_http_exception(net_http_exception)
net_http_exception_class =
if net_http_exception.is_a?(Net::HTTP::Persistent::Error)
case net_http_exception.message
when /connection refused/
Errno::ECONNREFUSED
when /host down/
Errno::EHOSTDOWN
else
net_http_exception.class
end
else
net_http_exception.class
end
exception_class = NET_HTTP_EXCEPTIONS_MAP[net_http_exception_class]
exception_message = CONNECTION_ERROR_EXCEPTION_MESSAGE % { wrapped_exception_name: net_http_exception_class }
exception_class.new(exception_message)
end
def self.raise_from_response(response)
message = "The server responded with a status of #{response.status}"
exception_class =
case response.status
when 400 then BadRequestError
when 401 then UnauthorizedError
when 403 then ForbiddenError
when 404 then NotFoundError
when 407 then ProxyAuthenticationRequired
when 422 then UnprocessableEntityError
when 429 then TooManyRequestsError
when 400..499
ClientError
else
ServerError
end
raise exception_class.new(message, response)
end
end
end
end
|
kandayo/likee
|
spec/likee/instrumentation_spec.rb
|
# frozen_string_literal: true
RSpec.describe Likee::Instrumentation do
before do
described_class.clear
end
after do
described_class.clear
end
describe '#subscribe' do
it 'subscribes with block' do
callable = -> {}
described_class.subscribe('spec', &callable)
expect(described_class.subscribers).to include('spec' => callable)
end
it 'raises error when block is not given' do
expect { described_class.subscribe }.to raise_exception(ArgumentError, '#subscribe expects a block')
end
end
describe '#unsubscribe' do
it 'unsubscribes the given subscriber' do
described_class.subscribe('spec') { nil }
expect(described_class.subscribers.keys).to include('spec')
described_class.unsubscribe('spec')
expect(described_class.subscribers.keys).to_not include('spec')
end
end
describe '#notify' do
let(:metrics_collector) { double(:metrics_collector) }
let(:config) { double(:config) }
let(:exception) { double(:exception) }
it 'notifies subscribers' do
expect(metrics_collector).to receive(:incr).twice
described_class.subscribe do |event|
expect(event.duration).to eq(10)
expect(event.http_status).to eq(200)
expect(event.method).to eq(:get)
expect(event.url).to eq('https://test.host/endpoint')
expect(event.config).to eq(config)
expect(event.exception).to eq(exception)
metrics_collector.incr
end
described_class.subscribe do |_event|
metrics_collector.incr
end
described_class.notify(
duration: 10,
http_status: 200,
method: :get,
url: 'https://test.host/endpoint',
config:,
exception:
)
end
end
describe '#clear' do
it 'clears the subscriber list' do
described_class.subscribe { nil }
described_class.subscribe { nil }
expect(described_class.subscribers.count).to eq(2)
described_class.clear
expect(described_class.subscribers.count).to eq(0)
end
end
describe '#subscribers' do
it 'returns the subscriber list' do
block1 = -> {}
block2 = -> {}
described_class.subscribe('spec1', &block1)
described_class.subscribe('spec2', &block2)
expect(described_class.subscribers).to include(
'spec1' => block1,
'spec2' => block2
)
end
end
end
|
kandayo/likee
|
lib/likee/transport.rb
|
<reponame>kandayo/likee<gh_stars>1-10
# frozen_string_literal: true
require 'net/http/persistent'
require_relative 'instrumentation'
require_relative 'transport/exception_manager'
require_relative 'transport/request'
require_relative 'transport/response'
require_relative 'util'
module Likee
class Transport
def initialize(config, instrumentation: Likee::Instrumentation)
@connection = Net::HTTP::Persistent.new(name: Util.object_identity(self))
@config = config
@instrumentation = instrumentation
configure_connection
freeze
end
def get(endpoint:, query_params: {})
request = Request.new(method: :get, endpoint:, query_params:)
perform(request)
end
def post(endpoint:, request_format: :plain, body: {})
request = Request.new(method: :post, endpoint:, request_format:, body:)
perform(request)
end
def reload
configure_connection
end
private
attr_reader :connection, :config, :instrumentation
def configure_connection
ensure_implicit_retry_is_disabled
configure_proxy
configure_timeouts
configure_default_headers
configure_keep_alive
end
def ensure_implicit_retry_is_disabled
connection.max_retries = 0
end
def configure_proxy
if config.proxy
connection.proxy = URI.parse(config.proxy)
else
connection.proxy_from_env
end
end
def configure_timeouts
connection.open_timeout = config.open_timeout
connection.read_timeout = config.read_timeout
connection.write_timeout = config.write_timeout
end
def configure_default_headers
connection.override_headers['User-Agent'] = config.user_agent
connection.override_headers['Referer'] = config.referer
end
def configure_keep_alive
connection.idle_timeout = config.keep_alive_idle_timeout
end
def perform(request)
net_http_request = request.to_net_http
request_start = Util.monotonic_time
net_http_response = connection.request(request.uri, net_http_request)
duration = compute_duration_ms(request_start)
response = Response.from_net_http(net_http_response)
instrumentation.notify(
duration:,
http_status: response.status,
method: request.method,
url: request.uri.to_s,
config:
)
raise_on_http_error!(response)
response
rescue *ExceptionManager.net_http_exceptions => e
duration = compute_duration_ms(request_start)
exception = ExceptionManager.build_exception_from_net_http_exception(e)
instrumentation.notify(
duration:,
http_status: nil,
method: request.method,
url: request.uri.to_s,
exception:,
config:
)
raise exception
end
def compute_duration_ms(request_start)
request_end = Util.monotonic_time
duration = request_end - request_start
(duration * 1000).to_i
end
def raise_on_http_error!(response)
return if response.success?
ExceptionManager.raise_from_response(response)
end
end
end
|
kandayo/likee
|
lib/likee/mappings/video_mapping.rb
|
# frozen_string_literal: true
require 'time'
require_relative '../models/snowflake'
require_relative '../models/video'
require_relative '../util'
module Likee
class VideoMapping
def self.call(data)
new(data).call
end
def initialize(data)
@data = data
freeze
end
def call
Video.new(
id:,
uploaded_at:,
creator_id:,
creator_username:,
creator_nickname:,
creator_avatar_url:,
title:,
description:,
height:,
width:,
thumbnail_url:,
url:,
sound_id:,
sound_name:,
sound_owner_name:,
sound_thumbnail:,
likes_count:,
comments_count:,
play_count:,
share_count:,
hashtags:,
mentions:,
country:
)
end
private
attr_reader :data
def id
Snowflake.new(data['postId'])
end
def uploaded_at
unix_timestamp = data['postTime']
return if unix_timestamp.nil?
Time.at(unix_timestamp)
end
def creator_id
data['posterUid']
end
def creator_username
data['likeeId']
end
def creator_nickname
data['nickname']
end
def creator_avatar_url
data['avatar']
end
def title
data['title']
end
def description
data['msgText']
end
def height
data['videoHeight']
end
def width
data['videoWidth']
end
def thumbnail_url
data['coverUrl']
end
def url
data['videoUrl']
end
def sound_id
data.dig('sound', 'soundId') || data.dig('cloudMusic', 'musicId') || data['musicId']
end
def sound_name
data.dig('sound', 'soundName') || data.dig('cloudMusic', 'musicName') || data['musicName']
end
def sound_owner_name
data.dig('sound', 'ownerName')
end
def sound_thumbnail
data.dig('sound', 'avatar') || data.dig('cloudMusic', 'avatar')
end
def likes_count
data['likeCount']
end
def comments_count
data['commentCount']
end
def play_count
data['playCount']
end
def share_count
data['shareCount']
end
def hashtags
payload = data['hashtagInfos']
return [] if payload.nil? || payload.empty?
hashtags_data = Util.load_json(payload)
hashtags_data.map do |tag|
Video::Hashtag.new(id: tag['ev_id'].to_s, name: tag['hs_tg'])
end
end
def mentions
payload = data['atUserInfos']
return [] if payload.nil? || payload.empty?
mentions_data = Util.load_json(payload)
mentions_data.map do |tag|
Video::Mention.new(id: tag['uid'].to_s, name: tag['name'])
end
end
def country
data['country'] || data['videoCountry']
end
end
end
|
kandayo/likee
|
lib/likee/client.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require_relative 'resources/creator_resource'
require_relative 'resources/trending_videos_resource_collection'
require_relative 'api'
module Likee
class Client
def initialize(api_class: Likee::Api, **args)
@api = api_class.new(**args)
freeze
end
# Finds creator by username.
#
# @param username [String] the creator username
#
# @return [Likee::CreatorResource]
def find_creator(username)
CreatorResource.find(username, api:)
end
# Returns the trending videos from a given location.
#
# @param country [String] the country two-letter code (alpha-2)
# @param language [String] the two-letter language code
# @param start [Integer]
#
# @return [Likee::TrendingVideosResourceCollection]
def trending_videos(country: :US, language: :us, start: 0)
TrendingVideosResourceCollection.new(country:, language:, start:, api:)
end
private
attr_reader :api
end
end
|
kandayo/likee
|
spec/factories/creator.rb
|
<filename>spec/factories/creator.rb<gh_stars>1-10
# frozen_string_literal: true
FactoryBot.define do
factory :creator, class: Likee::Creator do
sequence(:id, &:to_s)
sequence(:username) { |n| "user_#{n}" }
nickname { 'Nickname' }
avatar_url { 'https://likee.video/no_avatar.png' }
country { 'RU' }
gender { :male }
birthday { Date.new(2022, 12, 31) }
star_sign { 'Taurus' }
bio { '' }
likes_count { 100_000 }
fans_count { 10_000 }
following_count { 10 }
end
end
|
kandayo/likee
|
spec/likee/transport_spec.rb
|
# frozen_string_literal: true
RSpec.describe Likee::Transport do
let(:config) { build(:config) }
subject { described_class.new(config) }
describe '#get' do
it 'without query params' do
expected_request =
stub_request(:get, 'https://test.host/videos')
.with(
headers: {
'Referer' => 'https://likee.video/',
'User-Agent' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
}
)
.to_return(status: 200, body: '{}')
response = subject.get(endpoint: 'https://test.host/videos')
expect(expected_request).to have_been_requested
expect(response.status).to eq(200)
expect(response.body).to eq('{}')
end
it 'with query params' do
expected_request =
stub_request(:get, 'https://test.host/videos?page=1&per=10&q=term')
.with(
headers: {
'Referer' => 'https://likee.video/',
'User-Agent' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
}
)
.to_return(status: 200, body: '{}')
response = subject.get(endpoint: 'https://test.host/videos', query_params: { q: 'term', page: 1, per: 10 })
expect(expected_request).to have_been_requested
expect(response.status).to eq(200)
expect(response.body).to eq('{}')
end
end
describe '#post' do
it 'with json body' do
expected_request =
stub_request(:post, 'https://test.host/videos')
.with(
body: '{"uid":"111"}',
headers: {
'Content-Type' => 'application/json',
'Referer' => 'https://likee.video/',
'User-Agent' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
}
)
.to_return(status: 200, body: '{}')
response = subject.post(endpoint: 'https://test.host/videos', request_format: :json, body: { uid: '111' })
expect(expected_request).to have_been_requested
expect(response.status).to eq(200)
expect(response.body).to eq('{}')
end
it 'with form data' do
expected_request =
stub_request(:post, 'https://test.host/videos')
.with(
body: { uid: '111' },
headers: {
'Content-Type' => 'application/x-www-form-urlencoded',
'Referer' => 'https://likee.video/',
'User-Agent' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
}
)
.to_return(status: 200, body: '{}')
response = subject.post(endpoint: 'https://test.host/videos', request_format: :form_url_encoded, body: { uid: '111' })
expect(expected_request).to have_been_requested
expect(response.status).to eq(200)
expect(response.body).to eq('{}')
end
it 'with plain body' do
expected_request =
stub_request(:post, 'https://test.host/videos')
.with(
body: '<xml></xml>',
headers: {
'Referer' => 'https://likee.video/',
'User-Agent' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
}
)
.to_return(status: 200, body: '{}')
response = subject.post(endpoint: 'https://test.host/videos', body: '<xml></xml>')
expect(expected_request).to have_been_requested
expect(response.status).to eq(200)
expect(response.body).to eq('{}')
end
end
describe '#reload', skip: 'proxy rotation feature is not public yet' do
it 'reloads the configuration and updates the cached connections' do
request_with_original_referer =
stub_request(:get, 'https://test.host/videos')
.with(
headers: {
'Referer' => 'https://likee.video/'
}
)
subject.get(endpoint: 'https://test.host/videos')
config.referer = 'https://google.com'
subject.reload
request_with_new_referer =
stub_request(:get, 'https://test.host/videos')
.with(
headers: {
'Referer' => 'https://google.com/'
}
)
subject.get(endpoint: 'https://test.host/videos')
expect(request_with_original_referer).to have_been_requested
expect(request_with_new_referer).to have_been_requested
end
end
describe '#reload' do
it 'reloads the configuration' do
expect(subject.reload).to be_truthy
end
end
describe 'proxy' do
let(:config) { build(:config, proxy: 'http://user:pass@example.com') }
it 'loads the proxy from the configuration' do
expected_request = stub_request(:get, 'https://test.host/videos')
subject.get(endpoint: 'https://test.host/videos')
expect(expected_request).to have_been_requested
end
end
describe 'response content type' do
context 'when response has a known Content-Type header' do
it 'parses the body' do
stub_request(:get, 'https://test.host/videos')
.to_return(
body: '{"username":"@Likee_Russia"}',
headers: {
'Content-Type' => 'application/json;charset=UTF-8'
}
)
response = subject.get(endpoint: 'https://test.host/videos')
expect(response.body).to eq({ 'username' => '@Likee_Russia' })
end
end
context 'when response has a unknown Content-Type header' do
it 'does not parses the body' do
stub_request(:get, 'https://test.host/videos')
.to_return(
body: '{"username":"@Likee_Russia"}',
headers: {
'Content-Type' => 'unknown/unknown'
}
)
response = subject.get(endpoint: 'https://test.host/videos')
expect(response.body).to eq('{"username":"@Likee_Russia"}')
end
end
context 'when response has no Content-Type header' do
it 'does not parses the body' do
stub_request(:get, 'https://test.host/videos')
.to_return(
body: '{"username":"@Likee_Russia"}'
)
response = subject.get(endpoint: 'https://test.host/videos')
expect(response.body).to eq('{"username":"@Likee_Russia"}')
end
end
end
describe 'response encoding' do
context 'when Content-Type has a known charset identifier' do
context 'when encoding is not utf8' do
it 'encodes the body to utf8' do
stub_request(:get, 'https://test.host/videos')
.to_return(
body: 'returned body'.encode('ISO-8859-1'),
headers: {
'Content-Type' => 'text/html; charset=iso-8859-1'
}
)
response = subject.get(endpoint: 'https://test.host/videos')
expect(response.body.encoding.name).to eq('UTF-8')
end
end
context 'when encoding is already utf8' do
it 'does nothing' do
stub_request(:get, 'https://test.host/videos')
.to_return(
body: 'returned body',
headers: {
'Content-Type' => 'text/html; charset=utf-8'
}
)
response = subject.get(endpoint: 'https://test.host/videos')
expect(response.body.encoding.name).to eq('UTF-8')
end
end
end
context 'when Content-Type has a invalid charset identifier' do
it 'does nothing' do
stub_request(:get, 'https://test.host/videos')
.to_return(
body: 'returned body',
headers: {
'Content-Type' => 'text/html; charset=xxx'
}
)
response = subject.get(endpoint: 'https://test.host/videos')
expect(response.body.encoding.name).to eq('UTF-8')
end
end
context 'when response has no Content-Type header' do
it 'does nothing' do
stub_request(:get, 'https://test.host/videos').to_return(body: 'returned body')
response = subject.get(endpoint: 'https://test.host/videos')
expect(response.body.encoding.name).to eq('UTF-8')
end
end
end
describe 'instrumentation' do
let(:instrumentation) { double(:instrumentation) }
subject { described_class.new(config, instrumentation:) }
before do
allow(Likee::Util).to receive(:monotonic_time).and_return(0.000, 0.020)
end
it 'notifies when request is successful' do
stub_request(:get, 'https://test.host/videos')
expect(instrumentation)
.to receive(:notify)
.with(
hash_including(
duration: 20,
http_status: 200,
method: 'GET',
url: 'https://test.host/videos',
config:
)
)
subject.get(endpoint: 'https://test.host/videos')
end
it 'notifies when a connection error occurs' do
stub_request(:get, 'https://test.host/videos').to_timeout
expect(instrumentation)
.to receive(:notify)
.with(
hash_including(
duration: 20,
http_status: nil,
method: 'GET',
url: 'https://test.host/videos',
config:,
exception: instance_of(described_class::TimeoutError)
)
)
begin
subject.get(endpoint: 'https://test.host/videos')
rescue described_class::TimeoutError
nil
end
end
end
describe 'net/http/persistent exceptions' do
it 'handles IOError' do
stub_request(:get, 'https://test.host').to_raise(IOError)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (IOError)')
end
it 'handles EOFError' do
stub_request(:get, 'https://test.host').to_raise(EOFError)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (EOFError)')
end
it 'handles Errno::EADDRNOTAVAIL' do
stub_request(:get, 'https://test.host').to_raise(Errno::EADDRNOTAVAIL)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (Errno::EADDRNOTAVAIL)')
end
it 'handles Errno::ECONNABORTED' do
stub_request(:get, 'https://test.host').to_raise(Errno::ECONNABORTED)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (Errno::ECONNABORTED)')
end
it 'handles Errno::ECONNREFUSED' do
stub_request(:get, 'https://test.host').to_raise(Errno::ECONNREFUSED)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (Errno::ECONNREFUSED)')
end
it 'handles Errno::ECONNRESET' do
stub_request(:get, 'https://test.host').to_raise(Errno::ECONNRESET)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (Errno::ECONNRESET)')
end
it 'handles Errno::EHOSTDOWN' do
stub_request(:get, 'https://test.host').to_raise(Errno::EHOSTDOWN)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (Errno::EHOSTDOWN)')
end
it 'handles Errno::EHOSTUNREACH' do
stub_request(:get, 'https://test.host').to_raise(Errno::EHOSTUNREACH)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (Errno::EHOSTUNREACH)')
end
it 'handles Errno::EINVAL' do
stub_request(:get, 'https://test.host').to_raise(Errno::EINVAL)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (Errno::EINVAL)')
end
it 'handles Errno::ENETUNREACH' do
stub_request(:get, 'https://test.host').to_raise(Errno::ENETUNREACH)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (Errno::ENETUNREACH)')
end
it 'handles Errno::EPIPE' do
stub_request(:get, 'https://test.host').to_raise(Errno::EPIPE)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (Errno::EPIPE)')
end
it 'handles Errno::ETIMEDOUT' do
stub_request(:get, 'https://test.host').to_raise(Errno::ETIMEDOUT)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::TimeoutError, 'Unexpected low level network error. (Errno::ETIMEDOUT)')
end
it 'handles Net::Net::HTTP::Persistent::Error' do
stub_request(:get, 'https://test.host').to_raise(Net::HTTP::Persistent::Error)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (Net::HTTP::Persistent::Error)')
end
it 'handles Net::HTTPBadResponse' do
stub_request(:get, 'https://test.host').to_raise(Net::HTTPBadResponse)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (Net::HTTPBadResponse)')
end
it 'handles Net::HTTPHeaderSyntaxError' do
stub_request(:get, 'https://test.host').to_raise(Net::HTTPHeaderSyntaxError)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (Net::HTTPHeaderSyntaxError)')
end
it 'handles Net::OpenTimeout' do
stub_request(:get, 'https://test.host').to_raise(Net::OpenTimeout)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::TimeoutError, 'Unexpected low level network error. (Net::OpenTimeout)')
end
it 'handles Net::ProtocolError' do
stub_request(:get, 'https://test.host').to_raise(Net::ProtocolError)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (Net::ProtocolError)')
end
it 'handles Net::ReadTimeout' do
stub_request(:get, 'https://test.host').to_raise(Net::ReadTimeout)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::TimeoutError, 'Unexpected low level network error. (Net::ReadTimeout)')
end
it 'handles Net::WriteTimeout' do
stub_request(:get, 'https://test.host').to_raise(Net::WriteTimeout)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::TimeoutError, 'Unexpected low level network error. (Net::WriteTimeout)')
end
it 'handles OpenSSL::SSL::SSLError' do
stub_request(:get, 'https://test.host').to_raise(OpenSSL::SSL::SSLError)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (OpenSSL::SSL::SSLError)')
end
it 'handles SocketError' do
stub_request(:get, 'https://test.host').to_raise(SocketError)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ConnectionError, 'Unexpected low level network error. (SocketError)')
end
end
describe 'http response exceptions' do
it 'raises BadRequestError when status is 400 Bad Request' do
stub_request(:get, 'https://test.host').to_return(status: 400)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::BadRequestError, 'The server responded with a status of 400')
end
it 'raises Unauthorized Error when status is 401 Unauthorized' do
stub_request(:get, 'https://test.host').to_return(status: 401)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::UnauthorizedError, 'The server responded with a status of 401')
end
it 'raises Forbidden Error when status is 403 Forbidden' do
stub_request(:get, 'https://test.host').to_return(status: 403)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ForbiddenError, 'The server responded with a status of 403')
end
it 'raises NotFoundError when status is 404 Not Found' do
stub_request(:get, 'https://test.host').to_return(status: 404)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::NotFoundError, 'The server responded with a status of 404')
end
it 'raises ProxyAuthenticationRequired when status is 407 Proxy Authentication Required' do
stub_request(:get, 'https://test.host').to_return(status: 407)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ProxyAuthenticationRequired, 'The server responded with a status of 407')
end
it 'raises UnprocessableEntityError when status is 422 Unprocessable Entity' do
stub_request(:get, 'https://test.host').to_return(status: 422)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::UnprocessableEntityError, 'The server responded with a status of 422')
end
it 'raises UnprocessableEntityError when status is 429 Too Many Requests' do
stub_request(:get, 'https://test.host').to_return(status: 429)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::TooManyRequestsError, 'The server responded with a status of 429')
end
it 'raises ClientError when status is 415 Random Error' do
stub_request(:get, 'https://test.host').to_return(status: 415)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ClientError, 'The server responded with a status of 415')
end
it 'raises ServerError when status is 500 Internal Server Error' do
stub_request(:get, 'https://test.host').to_return(status: 500)
expect { subject.get(endpoint: 'https://test.host') }
.to raise_exception(described_class::ServerError, 'The server responded with a status of 500')
end
end
end
|
kandayo/likee
|
lib/likee/models/creator.rb
|
<reponame>kandayo/likee<gh_stars>1-10
# frozen_string_literal: true
module Likee
Creator = Struct.new(
:id,
:username,
:nickname,
:avatar_url,
:country,
:gender,
:birthday,
:star_sign,
:bio,
:likes_count,
:fans_count,
:following_count,
keyword_init: true
)
end
|
kandayo/likee
|
lib/likee/mappings/video_collection_mapping.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require_relative 'video_mapping'
module Likee
class VideoCollectionMapping
def self.call(data)
new(data).call
end
def initialize(data)
@data = data
freeze
end
def call
collection = data.dig('data', 'videoList')
return [] if collection.nil? || !collection.is_a?(Array)
collection.map do |video_data|
Likee::VideoMapping.(video_data)
end
end
private
attr_reader :data
end
end
|
kandayo/likee
|
spec/likee/mappings/hashtag_mapping_spec.rb
|
# frozen_string_literal: true
RSpec.describe Likee::HashtagMapping do
describe '#call' do
let(:hashtag_data) { load_fixture('single_hashtag_from_get_recommend_hashtag') }
subject { described_class.new(hashtag_data) }
it 'parses the hashtag data' do
hashtag = subject.call
expect(hashtag.id).to eq('6933972637669342631')
expect(hashtag.name).to eq('ParaNaPose')
expect(hashtag.videos_count).to eq(1380)
expect(hashtag.play_count).to eq(1611960)
end
end
end
|
kandayo/likee
|
lib/likee/resources/trending_videos_resource_collection.rb
|
<filename>lib/likee/resources/trending_videos_resource_collection.rb<gh_stars>1-10
# frozen_string_literal: true
require_relative 'resource_collection'
require_relative 'video_resource'
module Likee
class TrendingVideosResourceCollection < ResourceCollection
def initialize(country:, language:, start:, **args)
super(**args)
@country = country
@language = language
@start = start
end
def resource_class
VideoResource
end
def fetch_resource(cursor:)
api.trending_videos(country:, language:, start:, cursor:)
end
private
attr_reader :country, :language, :start
end
end
|
kandayo/likee
|
spec/likee/mappings/video_mapping_spec.rb
|
<reponame>kandayo/likee<filename>spec/likee/mappings/video_mapping_spec.rb
# frozen_string_literal: true
RSpec.describe Likee::VideoMapping do
describe '#call' do
context 'POST /likee-activity-flow-micro/videoApi/getUserVideo' do
context 'when cloudMusic attribute is present' do
let(:video_data) { load_fixture('single_video_from_get_user_video') }
subject { described_class.new(video_data) }
it 'parses the video data' do
video = subject.call
expect(video.id).to eq(Likee::Snowflake.new('6928156767853015171'))
expect(video.uploaded_at).to eq(Time.at(1613087199))
expect(video.creator_username).to eq('TioDjShow')
expect(video.creator_id).to eq('2551771267')
expect(video.creator_nickname).to eq('<NAME>')
expect(video.creator_avatar_url).to eq('https://img.like.video/na_live/3a1/0dSqPh.jpg')
expect(video.title).to eq('🎉Carnaval Virtual🎊')
expect(video.description).to eq(' esse ano vai ser assim #CarnavalVirtual #Trendings #Virals #DestaquesDaSemana @Sophiashow💕シ ')
expect(video.height).to eq(960)
expect(video.width).to eq(528)
expect(video.thumbnail_url).to eq('https://videosnap.like.video/na_live/3a2/1bwgRm_4.jpg?wmk_sdk=1&type=8')
expect(video.url).to eq('https://video.like.video/na_live/4aB/061bfQ_4.mp4?crc=334407246&type=5')
expect(video.sound_id).to eq('46997')
expect(video.sound_name).to eq('Só Depois Do Carnaval')
expect(video.sound_owner_name).to be_nil
expect(video.sound_thumbnail).to eq('https://img.like.video/asia_live/4h2/0uexVg.jpg')
expect(video.likes_count).to eq(602)
expect(video.comments_count).to eq(27)
expect(video.play_count).to eq(8257)
expect(video.share_count).to eq(13)
expect(video.hashtags).to match_array(
[
Likee::Video::Hashtag.new(id: '6461986135898597418', name: 'Virals'),
Likee::Video::Hashtag.new(id: '6521971805228232672', name: 'Trendings'),
Likee::Video::Hashtag.new(id: '6677488115831016377', name: 'DestaquesDaSemana'),
Likee::Video::Hashtag.new(id: '6926415516839971769', name: 'CarnavalVirtual')
]
)
expect(video.mentions).to eq(
[
Likee::Video::Mention.new(id: '1330860176', name: 'Sophiashow💕シ')
]
)
expect(video.country).to eq('BR')
end
end
context 'when cloudMusic attribute is not present' do
let(:video_data) { load_fixture('single_video_from_get_user_video_wo_cloud_music') }
subject { described_class.new(video_data) }
it 'parses the video data' do
video = subject.call
expect(video.sound_id).to eq('2628314853825440072')
expect(video.sound_name).to eq('XXX')
expect(video.sound_owner_name).to eq('<NAME>')
expect(video.sound_thumbnail).to eq('https://img.like.video/na_live/3a2/2hDoRr.jpg')
end
end
context 'when both hashtags and mentions are blank' do
let(:video_data) { load_fixture('single_video_from_get_user_video') }
subject { described_class.new(video_data) }
it 'parses the video data' do
video_data['hashtagInfos'] = '[]'
video_data['atUserInfos'] = '[]'
video = subject.call
expect(video.hashtags).to eq([])
expect(video.mentions).to eq([])
end
end
end
context 'POST /official_website/VideoApi/getEventVideo' do
let(:video_data) { load_fixture('single_video_from_get_event_video') }
subject { described_class.new(video_data) }
it 'parses the video data' do
video = subject.call
expect(video.id).to eq(Likee::Snowflake.new('6928156767853015171'))
expect(video.uploaded_at).to eq(Time.at(1613087199))
expect(video.creator_username).to eq('TioDjShow')
expect(video.creator_id).to eq('2551771267')
expect(video.creator_nickname).to eq('<NAME>')
expect(video.creator_avatar_url).to eq('https://img.like.video/na_live/3a1/0dSqPh.jpg')
expect(video.title).to eq('🎉Carnaval Virtual🎊')
expect(video.description).to eq(' esse ano vai ser assim #CarnavalVirtual #Trendings #Virals #DestaquesDaSemana @Sophiashow💕シ ')
expect(video.height).to eq(960)
expect(video.width).to eq(528)
expect(video.thumbnail_url).to eq('https://videosnap.like.video/na_live/3a2/1bwgRm_4.jpg?wmk_sdk=1&type=8')
expect(video.url).to eq('https://video.like.video/na_live/4aB/061bfQ_4.mp4?crc=334407246&type=5')
expect(video.sound_id).to eq('46997')
expect(video.sound_name).to eq('Só Depois Do Carnaval')
expect(video.sound_owner_name).to be_nil
expect(video.sound_thumbnail).to eq('https://img.like.video/asia_live/4h2/0uexVg.jpg')
expect(video.likes_count).to eq(602)
expect(video.comments_count).to eq(27)
expect(video.play_count).to eq(8257)
expect(video.share_count).to eq(13)
expect(video.hashtags).to match_array(
[
Likee::Video::Hashtag.new(id: '6461986135898597418', name: 'Virals'),
Likee::Video::Hashtag.new(id: '6521971805228232672', name: 'Trendings'),
Likee::Video::Hashtag.new(id: '6677488115831016377', name: 'DestaquesDaSemana'),
Likee::Video::Hashtag.new(id: '6926415516839971769', name: 'CarnavalVirtual')
]
)
expect(video.mentions).to eq(
[
Likee::Video::Mention.new(id: '1330860176', name: 'Sophiashow💕シ')
]
)
expect(video.country).to eq('BR')
end
end
context 'POST /official_website/VideoApi/getVideoInfo' do
let(:video_data) { load_fixture('single_video_from_get_video_info') }
subject { described_class.new(video_data) }
it 'parses the video data' do
video = subject.call
expect(video.id).to eq(Likee::Snowflake.new('6928156767853015171'))
expect(video.uploaded_at).to eq(Time.at(1613087199))
expect(video.creator_username).to eq('TioDjShow')
expect(video.creator_id).to eq('2551771267')
expect(video.creator_nickname).to eq('<NAME>')
expect(video.creator_avatar_url).to eq('https://img.like.video/na_live/3a1/0dSqPh.jpg')
expect(video.title).to eq('🎉Carnaval Virtual🎊')
expect(video.description).to eq(' esse ano vai ser assim #CarnavalVirtual #Trendings #Virals #DestaquesDaSemana @Sophiashow💕シ ')
expect(video.height).to eq(960)
expect(video.width).to eq(528)
expect(video.thumbnail_url).to eq('https://videosnap.like.video/na_live/3a2/1bwgRm_4.jpg?wmk_sdk=1&type=8')
expect(video.url).to eq('https://video.like.video/na_live/4aB/061bfQ_4.mp4?crc=334407246&type=5')
expect(video.sound_id).to eq('46997')
expect(video.sound_name).to eq('Só Depois Do Carnaval')
expect(video.sound_owner_name).to be_nil
expect(video.sound_thumbnail).to eq('https://img.like.video/asia_live/4h2/0uexVg.jpg')
expect(video.likes_count).to eq(602)
expect(video.comments_count).to eq(27)
expect(video.play_count).to eq(8257)
expect(video.share_count).to eq(13)
expect(video.hashtags).to match_array(
[
Likee::Video::Hashtag.new(id: '6461986135898597418', name: 'Virals'),
Likee::Video::Hashtag.new(id: '6521971805228232672', name: 'Trendings'),
Likee::Video::Hashtag.new(id: '6677488115831016377', name: 'DestaquesDaSemana'),
Likee::Video::Hashtag.new(id: '6926415516839971769', name: 'CarnavalVirtual')
]
)
expect(video.mentions).to eq(
[
Likee::Video::Mention.new(id: '1330860176', name: 'Sophiashow💕シ')
]
)
expect(video.country).to eq('BR')
end
end
end
end
|
kandayo/likee
|
lib/likee/transport/content_type.rb
|
<reponame>kandayo/likee
# frozen_string_literal: true
require 'uri'
require_relative '../util'
module Likee
module ContentType
class Entry
attr_reader :mime_type
def initialize(mime_type:, serializer:, deserializer:)
@mime_type = mime_type
@serializer = serializer
@deserializer = deserializer
end
def load(payload)
@deserializer.call(payload)
end
def dump(data)
@serializer.call(data)
end
end
PASSTHROUGH_CONTENT_TYPE = ContentType::Entry.new(
mime_type: nil,
deserializer: ->(payload) { payload },
serializer: ->(data) { data }
)
def self.find(name)
types.fetch(name, PASSTHROUGH_CONTENT_TYPE)
end
def self.find_by_mime_type(mime_type)
content_type = types.values.find { |entry| entry.mime_type == mime_type }
content_type || PASSTHROUGH_CONTENT_TYPE
end
def self.register(name:, mime_type:, serializer:, deserializer:)
types[name] = Entry.new(mime_type:, serializer:, deserializer:)
end
def self.types
@types ||= {}
end
end
end
# :nocov:
Likee::ContentType.register(
name: :json,
mime_type: 'application/json',
deserializer: ->(payload) { Likee::Util.load_json(payload) },
serializer: ->(data) { Likee::Util.dump_json(data) }
)
Likee::ContentType.register(
name: :form_url_encoded,
mime_type: 'application/x-www-form-urlencoded',
deserializer: ->(payload) { URI_decode_www_form(payload) },
serializer: ->(data) { URI.encode_www_form(data) }
)
|
kandayo/likee
|
lib/likee/util.rb
|
# frozen_string_literal: true
require 'securerandom'
begin
require 'oj'
rescue LoadError
require 'json'
end
module Likee
module Util
class << self
def dump_json(hash)
if Object.const_defined?(:Oj)
Oj.dump(hash, mode: :compat)
else
hash.to_json
end
end
def load_json(payload)
if Object.const_defined?(:Oj)
Oj.load(payload, mode: :compat)
else
JSON.parse(payload)
end
end
def monotonic_time
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
def random_device_id
SecureRandom.uuid.delete('-')
end
def random_user_id(length = 10)
Array.new(length) { Random.rand(1..9) }.join.to_i
end
def object_identity(object)
"#{object.class.name}(0x#{object_id.to_s(16)})"
end
end
end
end
|
kandayo/likee
|
lib/likee/models/hashtag.rb
|
# frozen_string_literal: true
module Likee
Hashtag = Struct.new(
:id,
:name,
:videos_count,
:play_count,
keyword_init: true
)
end
|
kandayo/likee
|
spec/integration/user_profile_spec.rb
|
# frozen_string_literal: true
RSpec.describe 'Creator Profile' do
before do
WebMock.allow_net_connect!
end
after do
WebMock.disable_net_connect!
end
it 'finds a creator by username' do
api = Likee::Api.new
creator = api.find_creator('Likee_USA')
expect(creator.id).to eq('30007')
end
end
|
kandayo/likee
|
spec/support/fixtures.rb
|
<filename>spec/support/fixtures.rb
# frozen_string_literal: true
require 'oj'
module Fixture
def load_fixture(fixture_name)
Oj.load(load_fixture_raw(fixture_name))
end
def load_fixture_raw(fixture_name)
fixture_path = File.join(File.dirname(__FILE__), '..', 'fixtures', "#{fixture_name}.json")
File.read(fixture_path)
end
end
RSpec.configure do |config|
config.include Fixture
end
|
kandayo/likee
|
lib/likee/models/snowflake.rb
|
<filename>lib/likee/models/snowflake.rb
# frozen_string_literal: true
require 'time'
module Likee
class Snowflake
include Comparable
attr_reader :id, :timestamp
def initialize(id)
@id = id.is_a?(Integer) ? id : Integer(id)
@timestamp = Time.at(@id >> 32)
freeze
end
def <=>(other)
id <=> other.id
end
def inspect
"#<Likee::Snowflake @id=#{id} @timestamp=#{timestamp}>"
end
def to_i
id
end
def to_s
id.to_s
end
end
end
|
kandayo/likee
|
lib/likee/transport/response.rb
|
<reponame>kandayo/likee
# frozen_string_literal: true
require_relative 'content_type'
module Likee
class Transport
class Response
attr_reader :status, :body
def self.from_net_http(net_http_response)
status = net_http_response.code
body = net_http_response.body
content_type = net_http_response['Content-Type']
new(status:, body:, content_type:)
end
def initialize(status:, body:, content_type:)
content_type, charset = parse_content_type_header(content_type)
body = ensure_utf8_encode(body, original_encode: charset) if charset
body = content_type.load(body) if content_type
@status = Integer(status)
@body = body
freeze
end
def success?
status.between?(200, 299)
end
private
def parse_content_type_header(header)
return unless header
mime_type = header.split(';').first
return unless mime_type
content_type = ContentType.find_by_mime_type(mime_type)
charset = parse_charset_from_content_type(header)
[content_type, charset]
end
def parse_charset_from_content_type(header)
return unless header =~ /charset=([^;|$]+)/
begin
::Encoding.find(Regexp.last_match(1))
rescue StandardError
nil
end
end
def ensure_utf8_encode(body, original_encode: Encoding::UTF_8)
body = body.dup if body.frozen?
body
.force_encoding(original_encode)
.encode(Encoding::UTF_8)
.freeze
end
end
end
end
|
kandayo/likee
|
spec/likee_spec.rb
|
<filename>spec/likee_spec.rb<gh_stars>1-10
# frozen_string_literal: true
RSpec.describe Likee do
describe '.build_api' do
it 'instantiates and return an Likee::Api instance' do
instance = double(:instance)
options = {
proxy: 'proxy.org'
}
expect(Likee::Api).to receive(:new).with(**options) { instance }
api = described_class.build_api(**options)
expect(api).to eq(instance)
end
end
describe '.build_client' do
it 'instantiates and return a Likee::Client instance' do
instance = double(:instance)
options = {
proxy: 'proxy.org'
}
expect(Likee::Client).to receive(:new).with(**options) { instance }
client = described_class.build_client(**options)
expect(client).to eq(instance)
end
end
end
|
kandayo/likee
|
lib/likee/models/comment.rb
|
<filename>lib/likee/models/comment.rb
# frozen_string_literal: true
module Likee
Comment = Struct.new(
:id,
:created_at,
:user_id,
:user_username,
:user_nickname,
:user_avatar_url,
:content,
:reply_user_id,
:reply_user_nickname,
:reply_content,
:likes_count,
keyword_init: true
)
end
|
kandayo/likee
|
lib/likee/mappings/comment_mapping.rb
|
# frozen_string_literal: true
require_relative '../models/comment'
require_relative '../util'
module Likee
class CommentMapping
def self.call(data)
new(data).call
end
def initialize(data)
@data = data.freeze
end
def call
Comment.new(
id:,
created_at:,
user_id:,
user_username:,
user_nickname:,
user_avatar_url:,
content:,
reply_user_id:,
reply_user_nickname:,
reply_content:,
likes_count:
)
end
private
attr_reader :data
def id
Snowflake.new(data['commentId'])
end
def created_at
Time.at(data['commentTime'].to_i)
end
def user_id
data['uid']
end
def user_username
data['userName']
end
def user_nickname
data['nickName']
end
def user_avatar_url
data['avatar']
end
def content
content_data['txt']
end
def reply_user_id
user_id = content_data['re_uid']
return if user_id.nil? || Integer(user_id).zero?
user_id.abs.to_s
end
def reply_user_nickname
nickname = content_data['re_n']
return if nickname.nil? || nickname.empty?
nickname
end
def reply_content
content = content_data['re_txt']
return if content.nil? || content.empty?
content
end
def content_data
@content_data ||= Util.load_json(data['comMsg'])
end
def likes_count
data['likeCount'].to_i
end
end
end
|
kandayo/likee
|
lib/likee/resources/resource_collection.rb
|
# frozen_string_literal: true
require_relative 'resource'
module Likee
class ResourceCollection < Resource
include Enumerable
def initialize(**args)
super
@cached_collection ||= {}
end
# @abstract Subclass is expected to implement #resource_class
# @!method resource_class
# The resource wrapper class.
# @abstract Subclass is expected to implement #fetch_resource
# @!method fetch_resource(cursor:)
# The method used to fetch the resource through pagination
def each(&)
return to_enum(:each) unless block_given?
cursor = 0
loop do
@cached_collection[cursor] ||= begin
collection = fetch_resource(cursor:)
collection.map do |resource|
resource_class.new(api:, resource:, parent:)
end
end
collection = @cached_collection[cursor]
collection.freeze
if collection.empty?
@cached_collection.freeze
break
end
cursor = collection.last.id
collection.each(&)
end
end
end
end
|
kandayo/likee
|
lib/likee/instrumentation.rb
|
<reponame>kandayo/likee
# frozen_string_literal: true
require_relative 'util'
module Likee
class Instrumentation
class Event
attr_reader :duration, :http_status, :method, :url, :exception, :config
def initialize(duration:, http_status:, method:, url:, config:, exception: nil)
@duration = duration
@http_status = http_status
@method = method
@url = url
@exception = exception
@config = config
freeze
end
end
private_constant :Event
class << self
def subscribe(name = Util.random_device_id, &block)
raise ArgumentError, '#subscribe expects a block' unless block
subscribers[name] = block
name
end
def unsubscribe(name)
subscribers.delete(name)
end
def notify(duration:, http_status:, method:, url:, config:, exception: nil)
event = Event.new(duration:, http_status:, method:, url:, exception:, config:)
subscribers.each_value do |subscriber|
subscriber.call(event)
end
end
def clear
subscribers.clear
end
def subscribers
@subscribers ||= {}
end
end
end
end
|
kandayo/likee
|
lib/likee/api.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require_relative 'transport'
require_relative 'mappings/comment_collection_mapping'
require_relative 'mappings/creator_mapping'
require_relative 'mappings/hashtag_collection_mapping'
require_relative 'mappings/video_collection_mapping'
require_relative 'configuration'
require_relative 'util'
module Likee
class Api
TRENDING_VIDEOS_ENDPOINT = 'https://api.like-video.com/likee-activity-flow-micro/videoApi/getSquareVideos'
CREATOR_VIDEOS_ENDPOINT = 'https://api.like-video.com/likee-activity-flow-micro/videoApi/getUserVideo'
TRENDING_HASHTAGS_ENDPOINT = 'https://likee.video/official_website/RecommendApi/getRecommendHashtag'
HASHTAG_VIDEOS_ENDPOINT = 'https://likee.video/official_website/VideoApi/getEventVideo'
VIDEO_COMMENTS_ENDPOINT = 'https://likee.video/live/home/comments'
INITIAL_STATE_CREATOR_DATA_REGEX = /"userinfo":(?<user_info>{.*}),"/
def initialize(
transport: Likee::Transport,
user_agent: 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
referer: 'https://likee.video/',
custom_device_id: nil,
custom_user_id: nil,
keep_alive_idle_timeout: 45,
open_timeout: 5,
read_timeout: 5,
write_timeout: 5,
proxy: nil
)
@config = Likee::Configuration.new(
user_agent:,
referer:,
custom_device_id:,
custom_user_id:,
open_timeout:,
read_timeout:,
write_timeout:,
keep_alive_idle_timeout:,
proxy:
)
@transport = transport.new(@config)
freeze
end
# Returns the trending videos from a given location.
#
# @param country [String] the country two-letter code (alpha-2)
# @param language [String] the two-letter language code
# @param limit [Integer] the number of videos to fetch per iteration
# @param start [Integer]
# @param cursor [String] the last video id from the previous iteration
# @param user_id [String] the user id
# @param device_id [String] the device id
#
# @return [Array<Likee::Video>]
def trending_videos(country: :US, language: :en, start: 0, cursor: 0, limit: 30, user_id: nil, device_id: nil)
http_response = transport.post(
endpoint: TRENDING_VIDEOS_ENDPOINT,
request_format: :json,
body: {
scene: 'WELOG_POPULAR',
fetchNum: limit,
startNum: start,
lastPostId: cursor,
deviceId: device_id || config.custom_device_id || Util.random_device_id,
uid: user_id || config.custom_user_id || Util.random_user_id,
language:,
country:
}
)
VideoCollectionMapping.(http_response.body)
end
# Returns the trending hashtags from a given location.
#
# @param country [String] the country two-letter code (alpha-2)
# @param language [String] the two-letter language code
# @param page [Integer]
# @param per [Integer]
#
# @return [Array<Likee::Hashtag>]
def trending_hashtags(country: :US, language: :en, page: 1, per: 100)
http_response = transport.post(
endpoint: TRENDING_HASHTAGS_ENDPOINT,
request_format: :form_url_encoded,
body: {
pagesize: per,
page:,
language:,
country:
}
)
HashtagCollectionMapping.(http_response.body)
end
# Returns the videos of the given hashtag.
#
# @param hashtag_id [String] the hashtag id
# @param country [String] the country two-letter code (alpha-2)
# @param page [Integer]
# @param per [Integer]
#
# @return [Array<Likee:Video>]
def hashtag_videos(hashtag_id:, country: :US, page: 1, per: 50)
http_response = transport.post(
endpoint: HASHTAG_VIDEOS_ENDPOINT,
request_format: :form_url_encoded,
body: {
topicId: hashtag_id,
pageSize: per,
page:,
country:
}
)
VideoCollectionMapping.(http_response.body)
end
# Finds creator by username.
#
# @param username [String] the creator username
#
# @return [Array<Likee:Video>]
def find_creator(username)
http_response = transport.get(endpoint: "https://likee.video/@#{username}")
can_extract_data =
http_response.body =~ INITIAL_STATE_CREATOR_DATA_REGEX
return unless can_extract_data
profile_data = Regexp.last_match(1)
parsed_profile_data = Util.load_json(profile_data)
Likee::CreatorMapping.(parsed_profile_data)
end
# Returns the videos of the given creator.
#
# @param user_id [String] the hashtag id
# @param cursor [String] the last video id from the previous iteration
# @param limit [Integer] the number of entries to fetch per iteration
#
# @return [Array<Likee:Video>]
def creator_videos(creator_id:, cursor: 0, limit: 100)
http_response = transport.post(
endpoint: CREATOR_VIDEOS_ENDPOINT,
request_format: :json,
body: {
count: limit,
lastPostId: cursor,
tabType: 0,
uid: creator_id
}
)
VideoCollectionMapping.(http_response.body)
end
# Returns the comments of the given video.
#
# @param video_id [String] the video id
# @param language [String] a two-letter language code
# @param cursor [Integer] the last comment id from the previous iteration
# @param limit [Integer] the number of entries to fetch per iteration
#
# @return [Array<Likee:Video>]
def video_comments(video_id:, language: :en, cursor: 0, limit: 49)
http_response = transport.get(
endpoint: VIDEO_COMMENTS_ENDPOINT,
query_params: {
post_id: video_id,
lang: language,
page_size: limit,
last_comment_id: cursor
}
)
CommentCollectionMapping.(http_response.body)
end
private
attr_reader :transport, :config
end
end
|
kandayo/likee
|
spec/likee/util_spec.rb
|
# frozen_string_literal: true
RSpec.describe Likee::Util do
describe '.dump_json' do
let(:hash) do
{ a: 1 }
end
context 'when Oj is defined' do
it 'dumps using Oj' do
allow(Object).to receive(:const_defined?).with(:Oj) { false }
expect(Oj).to_not receive(:dump)
expect(hash).to receive(:to_json).and_call_original
expect(described_class.dump_json(hash)).to eq('{"a":1}')
end
end
context 'when Oj is not defined' do
it 'dumps using stdlib JSON' do
allow(Object).to receive(:const_defined?).with(:Oj) { true }
expect(Oj).to receive(:dump).with(hash, any_args).and_call_original
expect(hash).to_not receive(:to_json)
expect(described_class.dump_json(hash)).to eq('{"a":1}')
end
end
end
describe '.load_json' do
let(:json) { '{"a":1}' }
context 'when Oj is defined' do
it 'dumps using Oj' do
allow(Object).to receive(:const_defined?).with(:Oj) { false }
expect(Oj).to_not receive(:load)
expect(JSON).to receive(:parse).with(json).and_call_original
expect(described_class.load_json(json)).to eq({ 'a' => 1 })
end
end
context 'when Oj is not defined' do
it 'dumps using stdlib JSON' do
allow(Object).to receive(:const_defined?).with(:Oj) { true }
expect(Oj).to receive(:load).with(json, any_args).and_call_original
expect(JSON).to_not receive(:parse)
expect(described_class.load_json(json)).to eq({ 'a' => 1 })
end
end
end
describe '.monotonic_time' do
it 'returns the monotonic_time' do
monotonic_time = double(:monotonic_time)
allow(Process).to receive(:clock_gettime).with(Process::CLOCK_MONOTONIC) { monotonic_time }
expect(described_class.monotonic_time).to eq(monotonic_time)
end
end
describe '.random_device_id' do
it 'generates a random device id' do
allow(SecureRandom).to receive(:uuid) { '29608418-f57d-41fd-9557-d968b9e65c96' }
expect(described_class.random_device_id).to eq('29608418f57d41fd9557d968b9e65c96')
end
end
describe '.random_user_id' do
it 'generates a random user id' do
allow(Random).to receive(:rand).with(1..9) { 1 }
expect(described_class.random_user_id).to eq(1111111111)
end
end
describe '.object_identity' do
it 'returns the object identity' do
expect(described_class.object_identity(String.new)).to include('String(0x')
end
end
end
|
kandayo/likee
|
lib/likee/transport/request.rb
|
# frozen_string_literal: true
require_relative 'content_type'
module Likee
class Transport
class Request
attr_reader :uri, :method, :request_content_type, :body
def initialize(method:, endpoint:, query_params: {}, request_format: :plain, body: nil)
@uri = build_uri(endpoint, query_params:)
@method = normalize_method(method)
@request_content_type = ContentType.find(request_format)
@body = body
freeze
end
def to_net_http
request = Net::HTTPGenericRequest.new(method, request_has_body?, response_has_body?, path, headers)
request.body = request_content_type.dump(body)
request
end
private
def build_uri(endpoint, query_params:)
uri = URI.parse(endpoint)
uri.query = URI.encode_www_form(query_params) if query_params.any?
uri
end
def normalize_method(method)
method.to_s.upcase
end
def request_has_body?
!!body
end
def response_has_body?
method != 'HEAD'
end
def path
uri.request_uri
end
def headers
{
'Content-Type' => request_content_type.mime_type
}
end
end
end
end
|
kandayo/likee
|
spec/integration/hashtag_videos_spec.rb
|
# frozen_string_literal: true
RSpec.describe 'Hashtag Videos' do
before do
WebMock.allow_net_connect!
end
after do
WebMock.disable_net_connect!
end
it 'returns hashtag videos' do
api = Likee::Api.new
collection = api.hashtag_videos(hashtag_id: '7034231050079308729')
expect(collection).to be_any
end
end
|
kandayo/likee
|
lib/likee/mappings/comment_collection_mapping.rb
|
# frozen_string_literal: true
require_relative 'comment_mapping'
module Likee
class CommentCollectionMapping
def self.call(data)
new(data).call
end
def initialize(data)
@data = data
freeze
end
def call
collection = data['data']
return [] if collection.nil? || !collection.is_a?(Array)
collection.map do |video_data|
Likee::CommentMapping.(video_data)
end
end
private
attr_reader :data
end
end
|
kandayo/likee
|
spec/factories/video.rb
|
<filename>spec/factories/video.rb
# frozen_string_literal: true
FactoryBot.define do
factory :video, class: Likee::Video do
sequence(:id, &:to_s)
uploaded_at { Time.now }
sequence(:creator_id, &:to_s)
sequence(:creator_username) { |n| "user_#{n}" }
creator_nickname { 'Creator Nickname' }
creator_avatar_url { 'https://likee.video/no_avatar.png' }
title { 'Title' }
description { 'Description' }
height { 111 }
width { 222 }
thumbnail_url { 'thumb.png' }
url { 'video.mp4' }
sound_id { 1 }
sound_name { 'Rock' }
sound_owner_name { '<NAME>' }
sound_thumbnail { 'rock.png' }
likes_count { 1_000_000 }
comments_count { 11_000 }
play_count { 1_000_000_000 }
share_count { 200_000 }
hashtags { [] }
mentions { [] }
country { 'RU' }
end
end
|
kandayo/likee
|
spec/likee/mappings/creator_mapping_spec.rb
|
<gh_stars>1-10
# frozen_string_literal: true
RSpec.describe Likee::CreatorMapping do
describe '#call' do
let(:creator_data) { load_fixture('creator_profile_data') }
subject { described_class.new(creator_data) }
it 'parses the creator data' do
creator = subject.call
expect(creator.id).to eq('30007')
expect(creator.username).to eq('Likee_USA')
expect(creator.nickname).to eq('Likee US')
expect(creator.avatar_url).to eq('https://img.like.video/asia_live/3s2/0dwqyT.jpg')
expect(creator.country).to eq('US')
expect(creator.gender).to eq(:male)
expect(creator.birthday).to eq(Date.new(2014, 2, 3))
expect(creator.star_sign).to eq('Aquarius')
expect(creator.bio).to eq('bio content')
expect(creator.likes_count).to eq(14891646)
expect(creator.fans_count).to eq(33493455)
expect(creator.following_count).to eq(1071)
end
end
end
|
kandayo/likee
|
lib/likee/configuration.rb
|
# frozen_string_literal: true
module Likee
class Configuration
attr_reader :user_agent, :referer, :custom_device_id, :custom_user_id,
:open_timeout, :read_timeout, :write_timeout,
:keep_alive_idle_timeout, :proxy
def initialize(
user_agent:,
referer:,
custom_device_id:,
custom_user_id:,
open_timeout:,
read_timeout:,
write_timeout:,
keep_alive_idle_timeout:,
proxy:
)
@user_agent = user_agent
@referer = referer
@custom_device_id = custom_device_id
@custom_user_id = custom_user_id
@open_timeout = open_timeout
@read_timeout = read_timeout
@write_timeout = write_timeout
@keep_alive_idle_timeout = keep_alive_idle_timeout
@proxy = proxy
freeze
end
end
end
|
kandayo/likee
|
spec/support/instrumentation.rb
|
# frozen_string_literal: true
RSpec.configure do |config|
def reset_instrumentation
Likee.instrumentation.clear
end
config.before(:suite) do
reset_instrumentation
end
config.before(:each) do
reset_instrumentation
end
end
|
kandayo/likee
|
lib/likee/resources/comment_resource.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require_relative 'resource'
module Likee
class CommentResource < Resource
def video
parent
end
end
end
|
kandayo/likee
|
spec/likee/models/snowflake_spec.rb
|
# frozen_string_literal: true
RSpec.describe Likee::Snowflake do
describe '#timestamp' do
context 'when snowflake is a Integer' do
subject { described_class.new(6914348117433371910) }
it 'returns the timestamp' do
expect(subject.timestamp).to eq(Time.parse('2021-01-05T18:42:02Z'))
end
end
context 'when snowflake is a String' do
subject { described_class.new('6914348117433371910') }
it 'returns the timestamp' do
expect(subject.timestamp).to eq(Time.parse('2021-01-05T18:42:02Z'))
end
end
context 'when snowflake is invalid' do
subject { described_class.new('abcd') }
it 'raises ArgumentError' do
expect { subject.timestamp }.to raise_error(ArgumentError)
end
end
end
describe '#inspect' do
subject { described_class.new(6914348117433371910) }
it 'formats the snowflake' do
expect(subject.inspect).to eq("#<Likee::Snowflake @id=#{subject.id} @timestamp=#{subject.timestamp}>")
end
end
describe '#to_i' do
subject { described_class.new(6914348117433371910) }
it 'returns the snowflake id' do
expect(subject.to_i).to eq(6914348117433371910)
end
end
describe '#to_s' do
subject { described_class.new(6914348117433371910) }
it 'returns the snowflake id as a string' do
expect(subject.to_s).to eq('6914348117433371910')
end
end
describe 'Comparable Behaviour' do
it 'computes equality based on snowflake id' do
snowflake1 = described_class.new('6914348117433371910')
snowflake2 = described_class.new('6914348117433371910')
expect(snowflake1 == snowflake2).to be_truthy
end
it 'computes comparisons based on snowflake id' do
snowflake1 = described_class.new('6914348117433371910')
snowflake2 = described_class.new('6914348117433371920')
expect(snowflake2 > snowflake1).to be_truthy
end
end
end
|
kandayo/likee
|
lib/likee/resources/resource.rb
|
<reponame>kandayo/likee
# frozen_string_literal: true
module Likee
class Resource
def initialize(api:, resource: nil, parent: nil)
@api = api
@resource = resource
@parent = parent
end
def inspect
io = StringIO.new
io << self.class.name
if resource
io << '{'
io << "\n"
resource.each_pair do |attribute_name, value|
io << " :#{attribute_name}"
io << ' => '
io << value.inspect
io << "\n"
end
io << '}'
elsif parent
io << '[Parent: '
io << parent.inspect
io << ']'
end
io.string
end
def respond_to_missing?(name, *args)
(!resource.nil? && resource.respond_to?(name)) || super
end
def method_missing(name, *args, &)
if !resource.nil? && resource.respond_to?(name)
resource.public_send(name)
else
super
end
end
private
attr_reader :api, :resource, :parent
end
end
|
kandayo/likee
|
spec/factories/comment.rb
|
# frozen_string_literal: true
FactoryBot.define do
factory :comment, class: Likee::Comment do
sequence(:id, &:to_s)
created_at { Time.now }
sequence(:user_id, &:to_s)
sequence(:user_username) { |n| "user_#{n}" }
user_nickname { 'Creator Nickname' }
user_avatar_url { 'https://likee.video/no_avatar.png' }
content { 'Content' }
likes_count { 1_000_000 }
sequence(:reply_user_id, &:to_s)
reply_user_nickname { 'Reply User Nickname' }
reply_content { 'Reply Content' }
end
end
|
kandayo/likee
|
lib/likee/models/video.rb
|
<reponame>kandayo/likee
# frozen_string_literal: true
module Likee
Video = Struct.new(
:id,
:uploaded_at,
:creator_id,
:creator_username,
:creator_nickname,
:creator_avatar_url,
:title,
:description,
:height,
:width,
:thumbnail_url,
:url,
:sound_id,
:sound_name,
:sound_owner_name,
:sound_thumbnail,
:likes_count,
:comments_count,
:play_count,
:share_count,
:hashtags,
:mentions,
:country,
keyword_init: true
)
Video::Hashtag = Struct.new(
:id,
:name,
keyword_init: true
)
Video::Mention = Struct.new(
:id,
:name,
keyword_init: true
)
end
|
kandayo/likee
|
lib/likee.rb
|
<reponame>kandayo/likee
# frozen_string_literal: true
require_relative 'likee/api'
require_relative 'likee/client'
require_relative 'likee/version'
module Likee
class << self
# Builds an instance of the Likee API client.
#
# @param user_agent [String] the User-Agent header used by the library
#
# @param referer [String] the Referer header used by the library
#
# @param custom_device_id [String] optional, the library automatically
# generates a random device ID for each request, however you might want
# to set a consistent one
#
# @param custom_user_id [String] optional, the library automatically
# generates a random user ID for each request, however you might want to
# set a consistent one
#
# @param keep_alive_idle_timeout [Integer] maximum time an unused connection
# can remain idle before being automatically closed. If a connection
# hasn't been used for this number of seconds it will automatically
# be reset upon the next use to avoid attempting to send to a closed
# connection
#
# @param open_timeout [Integer] number of seconds to wait for the
# connection to open
#
# @param read_timeout [Integer] number of seconds to wait for data
#
# @param write_timeout [Integer] number of seconds to wait for data to
# reach the service
#
# @param proxy [String] optional, a string containing your proxy address
#
# @return [Likee::Client]
def build_client(**args)
Likee::Client.new(**args)
end
# Builds an instance of the Likee API low level client.
#
# @param (see #clean)
#
# @return [Likee::Api]
def build_api(**args)
Likee::Api.new(**args)
end
def instrumentation
Likee::Instrumentation
end
end
end
|
kandayo/likee
|
spec/likee/configuration_spec.rb
|
# frozen_string_literal: true
RSpec.describe Likee::Configuration do
subject do
described_class.new(
user_agent: 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
referer: 'https://likee.video/',
custom_device_id: '111',
custom_user_id: '222',
open_timeout: 5,
read_timeout: 5,
write_timeout: 5,
keep_alive_idle_timeout: 45,
proxy: 'http://username:password@proxy.example.com'
)
end
it 'reads the configuration' do
expect(subject.user_agent).to eq('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)')
expect(subject.referer).to eq('https://likee.video/')
expect(subject.custom_device_id).to eq('111')
expect(subject.custom_user_id).to eq('222')
expect(subject.open_timeout).to eq(5)
expect(subject.read_timeout).to eq(5)
expect(subject.write_timeout).to eq(5)
expect(subject.keep_alive_idle_timeout).to eq(45)
expect(subject.proxy).to eq('http://username:password@proxy.example.com')
end
end
|
kandayo/likee
|
examples/quickstart.rb
|
# frozen_string_literal: true
require 'likee'
# please refer to the documentation to find all available options
# the default options are sensible, however you might need a proxy depending
# on your use case
client = Likee.build_client
# 💃🏻 find a creator by username
creator = client.find_creator('charlidamelio')
# returns an enumerable, pagination is automatically handled
creator_most_liked_videos =
creator.videos.select { |video| video.likes_count > 100_000 }.first(10)
creator_most_liked_videos.each do |video|
# ❤️ see likes count
puts video.likes_count
# 💬 see comments count
puts video.comments_count
# ▶️ see play count
puts video.play_count
# 🔗 see share count
puts video.share_count
# 🎧 get song name, owner, et cetera
puts video.song_name
# #️⃣ get the hashtags
puts video.hashtags
# 🔔 get the mentioned users
puts video.mentions
# 🎥 get the video url
puts video.url
# check out Likee::Video class to see all available properties
# also returns an enumerable, pagination is automatically handled
video.comments.each do |comment|
puts comment.user_nickname
puts comment.content
end
end
trending_videos = client.trending_videos(country: 'US')
trending_videos.each do |video|
# 💃🏻 get the creator profile
creator = video.creator
# 📈 see creator stats
puts creator.likes_count
puts creator.fans_count
puts creator.following_count
# the client design is straightforward
creator.videos.first(10).each do |creator_video|
creator_video.comments.each do |comment|
# resources can consistently access its parents
puts comment.video.creator == creator
end
end
end
client
.trending_hashtags(country: 'US')
.first(10)
.flat_map do |hashtag|
hashtag.videos.select { |v| v.user_username == 'charlidamelio' }
end
# 🔍 search users, hashtags and videos
client.search_user("<NAME>")
client.search_hashtag('#LikeeNewYear2022')
client.search_video('toosie slide')
# alternatively, the low level api client is also available 🤘🏻
api = Likee.build_api
api.creator_videos(creator_id: '111', cursor: '69453454234234212', limit: 30)
|
kronus/angular-ruby-2014-example
|
spec/spec_helper.rb
|
<reponame>kronus/angular-ruby-2014-example
require 'rubygems'
require 'spork'
require 'database_cleaner'
Spork.prefork do
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.use_transactional_fixtures = false
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
config.before :each do
if Capybara.current_driver == :selenium
DatabaseCleaner.strategy = :truncation
else
DatabaseCleaner.strategy = :transaction
end
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
# Include Factory Girl syntax to simplify calls to factories
config.include FactoryGirl::Syntax::Methods
config.include ControllerMacros
end
end
Spork.each_run do
# This code will be run each time you run your specs.
FactoryGirl.reload
end
# Faker does not support random dates
# https://github.com/stympy/faker/pull/73
# So lets extends Faker
# https://gist.github.com/rjackson/4694263
class Faker::Date
def self.random
Date.today-rand(10_000)
end
end
|
kronus/angular-ruby-2014-example
|
app/models/employee.rb
|
<gh_stars>10-100
class Employee < ActiveRecord::Base
validates_presence_of :first_name, on: :create
validates_presence_of :last_name, on: :create
validates_presence_of :email, on: :create
validates_presence_of :start_date, on: :create
end
|
kronus/angular-ruby-2014-example
|
db/seeds.rb
|
<reponame>kronus/angular-ruby-2014-example
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
# user name:string password:string password_confirmation:string
User.create!(name: 'Luke', password: '<PASSWORD>', password_confirmation: '<PASSWORD>')
# employee first_name:string last_name:string email:string start_date:date
Employee.create!([
{
:first_name => 'Sue',
:last_name => 'Hove',
:email => '<EMAIL>',
:start_date => DateTime.new(2006,1,7)
},
{
:first_name => 'Matt',
:last_name => 'Boles',
:email => '<EMAIL>',
:start_date => DateTime.new(2006,2,17)
},
{
:first_name => 'Mike',
:last_name => 'Kollen',
:email => '<EMAIL>',
:start_date => DateTime.new(2006,3,1)
},
{
:first_name => 'Jennifer',
:last_name => 'Jaegel',
:email => '<EMAIL>',
:start_date => DateTime.new(2006,4,1)
}
])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.