Coder Social home page Coder Social logo

layer-ruby's Introduction

Ruby Client for Layer

Build Status Gem Version Yard Docs

Ruby client for the Layer Server API and Layer Client API.

Installation

Add this line to your application's Gemfile:

gem 'layer-ruby', require: 'layer'

And then execute:

$ bundle

Or install it yourself as:

$ gem install layer-ruby

Usage

Please refer to the Layer Platform API documentation and Layer Client REST API documentation for details about the required payloads and responses.

Configuration

To use the Layer Platform API, you need your Layer APP ID as well as a Layer Platform API Token. The gem reads both values from the LAYER_APP_ID and LAYER_PLATFORM_TOKEN environment variables. Alternatively you can specify the values by configuring the Layer::Client like this:

Layer::Client.configure do |config|
  config.app_id = 'YOUR_APP_ID_HERE'
  config.token = 'YOUR_PLATFORM_TOKEN_HERE'
end

Using the gem with multiple applications at once

It's possible to create a new instance of Layer::Client::Platform and passing both the app id and the token to the initializer:

platform_client = Layer::Client::Platform.new('YOUR_APP_ID_HERE', 'YOUR_PLATFORM_TOKEN_HERE')

The client will not use any global configuration. You can pass the client as a second parameter to any operations (create, find) described above.

Using the Layer Client REST API

To use the Layer Client REST API, you need a way to generate identitiy tokens. You might want to use the layer-identity_token gem for that. Using this gem, you can create a new client using the REST API like this:

client = Layer::Client.authenticate { |nonce| Layer::IdentityToken.new('user_id_here', nonce) }

Afterwards, pass the client as an additional argument to the resource's methods:

# Finds all conversations of the authenticated user
Layer::Conversation.all(client)

Documentation

Please refer to the full documentation for details on how to use Announcements, Block Lists, Conversations, Messages, Rich Content, and WebHooks.

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake rspec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/benedikt/layer-ruby. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Related Work

Check out the layer-identity_token gem to generate authentication tokens for the Layer SDK.

layer-ruby's People

Contributors

benedikt avatar curbsaleem avatar peakxu avatar riyad avatar we5 avatar wiseleyb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

layer-ruby's Issues

Could not find conversation error recently started (last 2 days)

Hi There,

we have some code that looks up conversations between 2 users. It does this by getting the conversation list of one of the users and then iterating over the result until it finds a conversation that includes the other user.

The code is as follows:

def get_conversation(user1, user2)

  conversation = nil

  layer_client = get_layer_client(user1)
  client_conversations = Layer::Conversation.all(layer_client)
  puts "client_conversations: #{client_conversations.inspect}"
  
  matches = client_conversations.select { |c|
    puts "iter conversation: #{c.inspect}"
    c.attributes["participants"].include? user2.id.to_s
  }

  puts "matches: #{matches.inspect}"
  if matches.count > 0
    conversation = matches[0]
  end
end

When this method is called, we receive a 'not_found' error

{
  "code": 102,
  "id": "not_found",
  "message": "A Conversation with the specified identifier could not be found.",
  "url": "https://developer.layer.com/docs/client/rest#not_found"
}

Before running the above code, we created a conversation and then made sure it exists using curl commands as below:

Create Conversation

curl -X POST \
      -H 'Accept: application/vnd.layer+json; version=1.0' \
      -H 'Authorization: Bearer KOO2lnsIwsRrpdRNPcbx2wQ7wnyevvNaI2QN5ay4SUhFzJdQ' \
      -H 'Content-Type: application/json' \
      https://api.layer.com/apps/4d832b8c-7656-11e5-b603-70c100000104/conversations \
      -d '{"participants":["2","3"],"distinct":false,"metadata":{"background_color":"#3c3c3c"}}'

Fetch Conversation

curl -X GET \
     -H 'Accept: application/vnd.layer+json; version=1.0' \
     -H 'Authorization: Bearer KOO2lnsIwsRrpdRNPcbx2wQ7wnyevvNaI2QN5ay4SUhFzJdQ' \
     -H 'Content-Type: application/json' \
     https://api.layer.com/apps/4d832b8c-7656-11e5-b603-70c100000104/users/2/conversations

sending custom payload returns 422 error

Hi There,

I haven't determined if this a layer-ruby issue or an issue with the platform API so thought I would start here. Yea re trying to send a custom payload to Layer as follows:

  payload = {
    sender: { user_id: sender.id.to_s },
    parts: [
      { mime_type: "metadata", body: { message_type: "simple-text" } },
      { mime_type: "text/plain", body: message }
    ]
  }

  conversation.messages.create(payload)

when I run this code, I get the following:

RestClient::UnprocessableEntity: 422 Unprocessable Entity  
   from /usr/local/bundle/gems/rest-client-1.8.0/lib/restclient/abstract_response.rb:74:in `return!'  
   from /usr/local/bundle/gems/rest-client-1.8.0/lib/restclient/request.rb:495:in `process_result'  
   from /usr/local/bundle/gems/rest-client-1.8.0/lib/restclient/request.rb:421:in `block in transmit'  

I'm not sure if the gem is constructing the payload wrong when I include the custom part. It works if I just send a message with a single part of mime_type = text/plain.

thanks

set custom If-None-Match header

After reading over https://developer.layer.com/docs/platform/introduction#deduplication, I'm not sure I understand the point of the current behavior here

'If-None-Match' => SecureRandom.uuid
for setting the If-None-Match header. As it is now, every request would generate a new uuid, making de-duplication on Layer's end impossible.

Instead, I should be able to send the If-None-Match header per request in order to avoid potential duplication. If that makes sense, I'd be willing to open a PR.

Error on conversation creation/save

When rapidly creating new conversations, I have been encountering the following error on conversation creation or when saving an updated convo:

RestClient::InternalServerError (500 Internal Server Error):
  app/controllers/api/v1/users_controller.rb:78:in `block in create'
  app/controllers/api/v1/users_controller.rb:58:in `create'

Update:

conversation = Layer::Conversation.find(classroom.conversation_id)
conversation.participants << user.id.to_s
conversation.save

Create:

conversation = Layer::Conversation.create({participants: [user.id.to_s]})
conversation.metadata = data
conversation.messages.create({ sender: { name: 'Server' }, parts: [{ body: conversation_starter, mime_type: 'text/plain' }]})
conversation.save

2.0 API

Are there any plans for 2.0 support? Or anyway to make a single 2.0 request using the library?

Thanks!

How to get messages in a conversation

Hi @benedikt

I'm back and trying to work on a migration script to move messages from an old system to a new system. As part of this migration I want to mark the messages as read. In order to do this I need to get the messages associated to a conversation so that I can send a 'read' receipt for each message

However I'm unable to see how I can get the messages in a conversation using the library

So far I've got :

def mark_as_read(conversation, recipient)
  layer_client = Layer::Client.authenticate { |nonce| Layer::IdentityToken.new(recipient.id, nonce) }
    conversation2 = Layer::Conversation.find(conversation.id, layer_client)

    conversation2.messages.each do |message|
      log_event "message: #{message.inspect}"
      #message.read!
    end
end

Any feedback on how to accomplish this? maybe the library doesn't support this feature

thanks
Ben

Store status when creating distinct conversation

Using layer api when we try to create a distinct conversation, it can either return an existing conversation or create a new one. If it returns an existing conversation status is 200 and when it creates one the status is 201. We've a unique requirement where we want to know if the conversation was created or returned. And based on that we need to add metadata. Is it possible to expose this attribute on the Layer::Conversation object?

404 Resource Not Found for every request

Hi there, each request returns a 404 error. A request interception revealed that the app id isn't filled in: POST https://api.layer.com/apps//webhooks. The client itself seems to be properly configured, as I can access the app id and platform token. Any ideas?

Identity metadata

I'm having an issue updating metadata on a user Identity object.

The error is:

{
  "url": "https://developer.layer.com/docs/platform",
  "data": {
    "property": "metadata"
  },
  "code": 9,
  "id": "invalid_operation",
  "message": "Patch operation \"set\" on \"metadata\" is not allowed."
}

Talking to Layer team they said

yeah, you can only update or delete individual keys/values in identity metadata currently
In other words: you CAN update metadata, just don’t write the entire object

Is this something that's supported? Conversation has methods for metadata, but Identity didn't

Thanks!

new uninitialised constant error in latest code

Hi Benedikt,

I'm getting a new error after updating to the latest code. I had first updated my gemfile to point to 0.5 instead of the master branch after which i encountered this issue. I then reverted my gemfile back to point to master and was still getting this error

NameError: uninitialized constant Layer::Exceptions::Exceptions
    from /usr/local/bundle/bundler/gems/layer-ruby-4e977da41d83/lib/layer/client.rb:79:in `rescue in request'
    from /usr/local/bundle/bundler/gems/layer-ruby-4e977da41d83/lib/layer/client.rb:66:in `request'
    from /usr/local/bundle/bundler/gems/layer-ruby-4e977da41d83/lib/layer/client/platform.rb:18:in `request'
    from /usr/local/bundle/bundler/gems/layer-ruby-4e977da41d83/lib/layer/client.rb:38:in `post'
    from /usr/local/bundle/bundler/gems/layer-ruby-4e977da41d83/lib/layer/operations/create.rb:13:in `create'
    from /fitmo/app/services/messaging/message_service.rb:25:in `get_conversation'

how to reproduce this issue is to create a distinct conversation without any metadata. afterwards try to create the same conversation but this time with meta data. It should fail because distinct conversations need to be unique.

Before I modified the Gemfile, i.e. before I updated to the latest code, I got a meaningful "Layer::Exceptions::Conflict:" exception.

cheers

422 Unprocessable Entity

To create message, I m using

conversation.messages.create({sender: {user_id: current_user.id.to_s, name: current_user.id.to_s }, parts: [{ body: 'example', mime_type: 'text/plain' }]})

But getting 422 Unprocessable Entity

Get messages in conversation

Thank you for making this project. It saves me a lot of time. But I face myself with a problem.
I'de like to know if it there is a way to retrieve all message in a conversation. In the Layer docs they supply methods for doing this in IOS/Android.

And according with their API:
If User A wants to talk to User B, they should not need to create a new Conversation every time they talk. By reusing an existing Conversation, they can access the message history and context around their previous communications.

I have a _Layer::Conversation_ object, but the _.messages_ method returns a _Layer::RelationProxy_. There is a way of achieving this?

Thank you!

undefined method `participants=' for #<Layer::Conversation:0x00000007e31d20>

conversation.participants.class
=> Layer::Patch::Array
2.1.5 :014 > conversation.participants = ["55804bd569702d409a4d7d00", "55a3c04069702d18cb290000"]
NoMethodError: undefined method participants=' for #<Layer::Conversation:0x00000007e31d20> from /home/sahil/.rvm/gems/ruby-2.1.5@curb/gems/layer-ruby-0.4.1/lib/layer/resource.rb:49:inmethod_missing'
from (irb):14
from /home/sahil/.rvm/gems/ruby-2.1.5@curb/gems/railties-4.2.0/lib/rails/commands/console.rb:110:in start' from /home/sahil/.rvm/gems/ruby-2.1.5@curb/gems/railties-4.2.0/lib/rails/commands/console.rb:9:instart'
from /home/sahil/.rvm/gems/ruby-2.1.5@curb/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:68:in console' from /home/sahil/.rvm/gems/ruby-2.1.5@curb/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:39:inrun_command!'
from /home/sahil/.rvm/gems/ruby-2.1.5@curb/gems/railties-4.2.0/lib/rails/commands.rb:17:in <top (required)>' from bin/rails:8:inrequire'
from bin/rails:8:in `

'

InvalidHeader on Layer::Client.authenticate

Hi, I'm getting a Layer::Exceptions::InvalidHeader Exception when calling Layer::Client.authenticate after upgrading to v0.7.

With v0.6 everything works OK.

Any ideas?
Thanks.

NoMethodError: private method `include' called for #<Class:#<Layer::RelationProxy:0x007fd1f67016e0>>

Hey!

The gem works perfectly on development but on staging (using Heroku) I'm experiencing an error. When I try to create a message for a Layer::Conversation instance it throws:

NoMethodError: private method `include' called for #<Class:#<Layer::RelationProxy:0x007fd1f67016e0>>
    from /app/vendor/bundle/ruby/2.0.0/gems/attr_encrypted-1.3.4/lib/attr_encrypted.rb:259:in `method_missing'
    from /app/vendor/bundle/ruby/2.0.0/gems/layer-ruby-0.4.1/lib/layer/relation_proxy.rb:10:in `block in initialize'
    from /app/vendor/bundle/ruby/2.0.0/gems/layer-ruby-0.4.1/lib/layer/relation_proxy.rb:10:in `each'
    from /app/vendor/bundle/ruby/2.0.0/gems/layer-ruby-0.4.1/lib/layer/relation_proxy.rb:10:in `initialize'
    from /app/vendor/bundle/ruby/2.0.0/gems/layer-ruby-0.4.1/lib/layer/conversation.rb:8:in `new'
    from /app/vendor/bundle/ruby/2.0.0/gems/layer-ruby-0.4.1/lib/layer/conversation.rb:8:in `messages'
    from (irb):10
    from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/commands/console.rb:90:in `start'
    from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/commands/console.rb:9:in `start'
    from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/commands/commands_tasks.rb:69:in `console'
    from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
    from /app/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/commands.rb:17:in `<top (required)>'
    from /app/bin/rails:4:in `require'
    from /app/bin/rails:4:in `<main>'

I'm using the same keys from layer for the Development and Staging environments.

Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.