Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #===============================================================================
- # Gab Heroku Online Ranking
- #-----------------------------------------------------------------------------
- # @author : Gabriel "Gab!" Teles
- # @date : 2014/07/19
- # @version : 1.0a
- #-----------------------------------------------------------------------------
- #
- # Permite criar um ranking online utilizando o Heroku para armazenamento e
- # processamento dos dados.
- #
- #-----------------------------------------------------------------------------
- #
- # Utilização:
- #
- # - OnlineRanking.sendScore(name, points)
- # Envia para o servidor uma entrada de nome e pontuação. Pode ser utilizado
- # em condicionais dos eventos, visto que retorna "true" quando sucesso e
- # "false" em caso de erro. No modo de testes o erro será mostrado.
- #
- # - OnlineRanking.getRanking(n)
- # Requere os "n" primeiros do ranking. Também pode ser utilizado em
- # condicionais; o procedimento de sucesso/falho é idêntico ao do método
- # anterior.
- #
- # #---------------------------------------------------------------------#
- # # ATENÇÃO: Os métodos abaixo só funcionarão corretamente após fazer o #
- # # requerimento das pontuações do servidor através do método acima. #
- # #---------------------------------------------------------------------#
- #
- # - OnlineRanking.getName(n)
- # Requere o nome do n-ésimo (começando do 0) colocado no ranking.
- #
- # - OnlineRanking.getScore(n)
- # Requere a pontuação do n-ésimo (començando do 0) colocado no ranking.
- #
- # - OnlineRanking.getDate(n, format="%d/%m/%y %H:%M")
- # Requere a data de entrada do n-ésimo (começando do 0) colocado no ranking.
- # Não é necessário especificar o segundo argumento, apenas para o caso de
- # querer alterar formato da data. O padrão é: dia/mês/ano hora:minuto.
- # Para saber mais sobre formatação da data veja a referência do método
- # Time#strftime na documentação do Ruby:
- # http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-strftime
- #
- #===============================================================================
- module Gab
- module OnlineRanking
- #===============================================================================
- # * CONFIGURAÇÃO
- #===============================================================================
- # IP do aplicativo no Heroku
- HEROKU_IP = "50.16.239.160"
- # URL do aplicativo no Heroku
- HEROKU_URL = "glacial-inlet-1181.herokuapp.com"
- #===============================================================================
- # * FIM DA CONFIGURAÇÃO
- #===============================================================================
- end
- end
- module Socket
- Socket = Win32API.new('ws2_32', 'socket', 'lll', 'l')
- Connect = Win32API.new('ws2_32', 'connect', 'ppl', 'l')
- Close = Win32API.new('ws2_32', 'closesocket', 'p', 'l')
- Send = Win32API.new('ws2_32', 'send', 'ppll', 'l')
- Recv = Win32API.new('ws2_32', 'recv', 'ppll', 'l')
- Inet_addr = Win32API.new('ws2_32', 'inet_addr', 'p', 'l')
- Htons = Win32API.new('ws2_32', 'htons', 'l', 'l')
- Shutdown = Win32API.new('ws2_32', 'shutdown', 'pl', 'l')
- AF_INET = 2
- SOCK_STREAM = 1
- IPPROTO_TCP = 6
- module_function
- def sockaddr_in(host, port)
- sin_family = AF_INET
- sin_port = Htons.(port)
- in_addr = Inet_addr.(host)
- sockaddr_in = [sin_family, sin_port, in_addr].pack('sSLx8')
- return sockaddr_in
- end
- def socket()
- return Socket.(AF_INET, SOCK_STREAM, IPPROTO_TCP)
- end
- def connect_sock(sock, sockaddr)
- Connect.(sock, sockaddr, sockaddr.size)
- end
- def connect(host = "127.0.0.1", port = 9999)
- sockaddr = sockaddr_in(host, port)
- sock = socket()
- connect_sock(sock, sockaddr)
- return sock
- end
- def send(socket, data)
- value = Send.(socket, data, data.length, 0)
- if value == -1
- shutdown(socket, 2)
- return false
- end
- return true
- end
- def recv(socket, len = 256)
- buffer = [].pack('x'+len.to_s)
- value = Recv.(socket, buffer, len, 0)
- return buffer.gsub(/\x00/, "") if value != -1
- return false
- end
- def gets(socket, delimiter=$/)
- line = ""
- line << recv(socket, 1) until line[-1] == delimiter
- return line
- end
- def shutdown(socket, how)
- Shutdown.(socket, how)
- end
- def close(socket)
- Close.(socket)
- end
- end
- module OnlineRanking
- # GABOA : GAB BULLSHIT OBFUSCATION ALGORITHMS
- ALGORITHMS = [
- ->(data, compress) {
- if compress
- "A" + compress([
- data[:points],
- Time.now.to_i,
- *data[:name].unpack("C*")
- ].pack("DIC*")).reverse.strip
- else
- data = decompress(data.reverse).unpack("DIC*")
- points = data.shift
- date = data.shift
- name = data.pack("C*")
- [name, points, date]
- end
- },
- ->(data, compress) {
- if compress
- "B" + compress([
- Time.now.to_i,
- data[:points],
- *data[:name].unpack("C*")
- ].pack("IDC*").reverse).reverse.strip
- else
- data = decompress(data.reverse).reverse.unpack("IDC*")
- date = data.shift
- points = data.shift
- name = data.pack("C*")
- [name, points, date]
- end
- },
- ->(data, compress) {
- if compress
- "C" + compress([
- Time.now.to_i,
- data[:points],
- *data[:name].unpack("C*").reverse
- ].pack("IDC*")).reverse.strip
- else
- data = decompress(data.reverse).unpack("IDC*")
- date = data.shift
- points = data.shift
- name = data.reverse.pack("C*")
- [name, points, date]
- end
- }
- ]
- module_function
- def decompress(string)
- stringIO = Zlib::Inflate.inflate(string.unpack('m*').first)
- object = Marshal.load(stringIO)
- return object
- end
- def compress(object)
- return [Zlib::Deflate.deflate(Marshal.dump(object))].pack('m*')
- end
- def getPath(path)
- host = Socket.connect(Gab::OnlineRanking::HEROKU_IP, 80)
- return compress("Não foi possível se conectar ao servidor.") if host.zero?
- # Request
- Socket.send(host, "GET #{path} HTTP/1.1\r\n")
- Socket.send(host, "Host: #{Gab::OnlineRanking::HEROKU_URL}\r\n")
- Socket.send(host, "Accept: text/html\r\n")
- Socket.send(host, "\r\n")
- # Response
- response = Socket.gets(host).rstrip
- if response == "HTTP/1.1 200 OK"
- # Header
- header = {}
- until (line = Socket.gets(host).rstrip).empty?
- definition = line.split(": ")
- header[definition.shift] = definition.join
- break if header.has_key?("Content-Length")
- end
- # Body
- return Socket.recv(host, header["Content-Length"].to_i)
- else
- return compress("Ocorreu um erro ao receber o requerimento do servidor.")
- end
- end
- def getRanking(num = 5)
- @ranking ||= []
- response = decompress(getPath("/get/#{num}"))
- if response.is_a?(Array)
- @ranking = response
- return true
- else
- msgbox(response) if $TEST
- return false
- end
- end
- def sendScore(name, points)
- hash = ALGORITHMS.sample[{name: name, points: points}, true]
- response = decompress(getPath("/set/#{hash}"))
- if response.is_a?(String)
- msgbox(response) if $TEST
- return false
- else
- return true
- end
- end
- def getInfo(index, info)
- default, i = case info
- when :pos then [ 0, 0]
- when :name then ["", 1]
- when :score then [ 0, 2]
- when :date then [ 0, 3]
- end
- return @ranking.size >= index ? default : @ranking[index][i]
- end
- def getName(index)
- return getInfo(index, :name)
- end
- def getScore(index)
- return getInfo(index, :score)
- end
- def getDate(index, format="%d/%m/%y %H:%M")
- date = Time.at(getInfo(index, :date))
- return date.strftime(format)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment