Code Monkey home page Code Monkey logo

fcmex's Introduction

Fcmex

GitHub Workflow Status Hex.pm Hex Docs Coverage Status

A Firebase Cloud Message client for Elixir

Installation

Add to dependencies

def deps do
  [{:fcmex, "~> 0.6.0"}]
end
mix deps.get

Usage

Fcmex by default reading FCM server key from your environment variable FCM_SERVER_KEY on runtime.

If FCM_SERVER_KEY is not found in your environment, it fallbacks to search following line.

config :fcmex,
  server_key: "a_example_key"
  • Send notification message to a device
{:ok, body} = Fcmex.push("user_token",
  notification: %{
    title: "foo",
    body: "bar",
    click_action: "open_foo",
    icon: "new",
  }
)
  • Send messsage to the topic
{:ok, body} = Fcmex.push("/topics/topic_name",
  notification: %{
    title: "foo",
    body: "bar",
    click_action: "open_foo",
    icon: "new",
  }
)
  • Send data message to a device. Difference between notification message and data message is decribed in here.
{:ok, body} = Fcmex.push("user_token",
  data: %{
    nick: "Mario",
    body: "great match!",
    room: "PortugalVSDenmark",
  }
)
  • You can use notification, and data as custom key-value store
{:ok, body} = Fcmex.push("user_token",
  notification: %{
    title: "foo",
    body: "bar",
    click_action: "open_foo",
    icon: "new",
  },
  data: %{
    nick: "Mario",
    body: "great match!",
    room: "PortugalVSDenmark",
  }
)
  • Send message to multiple devices
[ok: body] = Fcmex.push(["user_token", "user_token_2"],
  notification: %{
    title: "foo",
    body: "bar",
    click_action: "open_foo",
    icon: "new",
  }
)

As the FCM limitation of multiple send at once is up to 1000, Fcmex chunks tokens to list of 1000 tokens.

If specified tokens is over than 1000 tokens, then response is returned by keyword list chunked by every 1000 requests. (order is not guaranteed)

[ok: result, ok: result2, ...]

If one of request goes something wrong (e.g. timeout, server error), then fcmex returns results with :error keyword.

[ok: result, error: result2, ...]
  • Topic subscription
# create a subscription
{:ok, result} = Fcmex.Subscription.subscribe("topic_name", "fcm_token")

# get subscription information related with specified token
{:ok, result} = Fcmex.Subscription.get("fcm_token")
iex> result
 %{
   "application" => "application_name",
   "applicationVersion" => "3.6.1",
   "authorizedEntity" => "1234567890",
   "platform" => "IOS",
   "rel" => %{"topics" => %{"test_topic" => %{"addDate" => "2018-05-03"}}},
   "scope" => "*"
 }}

# create multiple subscriptions
{:ok, result} = Fcmex.Subscription.subscribe("topic_name", ["fcm_token", "fcm_token2"])

# unsubscribe a topic
{:ok, result} = Fcmex.Subscription.unsubscribe("topic_name", "fcm_token")

# batch unsubscribe from a topic
{:ok, result} = Fcmex.Subscription.unsubscribe("topic_name", ["fcm_token", "fcm_token2"])
  • Check if token is unregistered or not
iex> Fcmex.unregistered?(token)
true

iex> tokens = ["token1", "token2", ...]
iex> Fcmex.filter_unregistered_tokens(tokens)
["token1"]

Options

You can use these options as well.

  • priority: default: "high"
  • collapse_key: default: nil
  • time_to_live: default: nil
  • content_available: default: nil
Fcmex.push(["user_token", "user_token_2"],
  notification: %{
    title: "foo",
    body: "bar",
    click_action: "open_foo",
    icon: "new",
  },
  priority: "normal",
  collapse_key: "data",
  time_to_live: 1000,
  content_available: true
)

A more detail of parameters are available on Firebase doc page.

Configuration

You can set httpoison option as below.

config :fcmex,
  fcm_server_key: {:system, "FCM_SERVER_KEY"} || System.get_env("FCM_SERVER_KEY"),
  httpoison_options: [ssl: [{:versions, [:'tlsv1.2']}], recv_timeout: 500]

fcmex uses Poison to encode/decode JSON by default. If you want to use alternative library like Jason, add the package to mix.exs and set the module to config.

# mix.exs
def deps do
 [
   ...,
   {:jason, "~> 1.3"}
 ]
end
# config/config.exs
config :fcmex, :json_library, Jason

Testing

If you start contributing and you want to run mix test, first you need to export FCM_SERVER_KEY environment variable in the same shell as the one you will be running mix test in.

export FCM_SERVER_KEY="yourkey"
mix test

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Contributors

shufo
Shuhei Hayashibara
nukosuke
Nukosuke
nietaki
Jacek Królikowski
qgadrian
Adrián Quintás
Fabi755
Fabian Keunecke
mbramson
Mathew Bramson

License

MIT

fcmex's People

Contributors

dependabot-preview[bot] avatar fabi755 avatar github-actions[bot] avatar mbramson avatar nietaki avatar nukosuke avatar qgadrian avatar renovate[bot] avatar shufo 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

fcmex's Issues

Returns error on invalid topic name

/cc @qgadrian

Context

Problem

  • Error message is ambiguous when topic name format is wrong

Solution

  • Returns error tuple like {:error, InvalidTopicNameFormat} or raise an error in the case of an error.

Error after upgrading erlang 23

Hi this morning i upgrade erlang to 23 and fcmex return this error on execution of Fcmex.push:

09:00:42.633 [error] GenServer #PID<0.9388.0> terminating ** (FunctionClauseError) no function clause matching in Fcmex.Util.parse_result/1 (fcmex 0.3.2) lib/util.ex:12: Fcmex.Util.parse_result({:error, %HTTPoison.Error{id: nil, reason: {:options, {:sslv3, {:versions, [:"tlsv1.2", :"tlsv1.1", :tlsv1, :sslv3]}}}}}) (flow 1.0.0) lib/flow/materialize.ex:731: anonymous fn/4 in Flow.Materialize.mapper/2 (flow 1.0.0) lib/flow/materialize.ex:699: Flow.Materialize."-mapper_ops/1-lists^foldl/2-0-"/3 (flow 1.0.0) lib/flow/materialize.ex:699: anonymous fn/5 in Flow.Materialize.mapper_ops/1 (flow 1.0.0) lib/flow/map_reducer.ex:59: Flow.MapReducer.handle_events/3 (gen_stage 1.0.0) lib/gen_stage.ex:2395: GenStage.consumer_dispatch/6 (gen_stage 1.0.0) lib/gen_stage.ex:2574: GenStage.take_pc_events/3 (stdlib 3.13) gen_server.erl:680: :gen_server.try_dispatch/4 (stdlib 3.13) gen_server.erl:756: :gen_server.handle_msg/6 (stdlib 3.13) proc_lib.erl:226: :proc_lib.init_p_do_apply/3 Last message: {:"$gen_consumer", {#PID<0.9387.0>, #Reference<0.3834918260.1681915906.212152>}, [%{to: ["234324234234234231"]}]} 09:00:42.637 [error] ** (exit) exited in: GenStage.close_stream(%{}) ** (EXIT) an exception was raised: ** (FunctionClauseError) no function clause matching in Fcmex.Util.parse_result/1 (fcmex 0.3.2) lib/util.ex:12: Fcmex.Util.parse_result({:error, %HTTPoison.Error{id: nil, reason: {:options, {:sslv3, {:versions, [:"tlsv1.2", :"tlsv1.1", :tlsv1, :sslv3]}}}}}) (flow 1.0.0) lib/flow/materialize.ex:731: anonymous fn/4 in Flow.Materialize.mapper/2 (flow 1.0.0) lib/flow/materialize.ex:699: Flow.Materialize."-mapper_ops/1-lists^foldl/2-0-"/3 (flow 1.0.0) lib/flow/materialize.ex:699: anonymous fn/5 in Flow.Materialize.mapper_ops/1 (flow 1.0.0) lib/flow/map_reducer.ex:59: Flow.MapReducer.handle_events/3 (gen_stage 1.0.0) lib/gen_stage.ex:2395: GenStage.consumer_dispatch/6 (gen_stage 1.0.0) lib/gen_stage.ex:2574: GenStage.take_pc_events/3 (stdlib 3.13) gen_server.erl:680: :gen_server.try_dispatch/4 (stdlib 3.13) gen_server.erl:756: :gen_server.handle_msg/6 (stdlib 3.13) proc_lib.erl:226: :proc_lib.init_p_do_apply/3 (gen_stage 1.0.0) lib/gen_stage/stream.ex:160: GenStage.Stream.close_stream/1 (elixir 1.10.3) lib/stream.ex:1415: Stream.do_resource/5 (elixir 1.10.3) lib/enum.ex:3383: Enum.reverse/1 (elixir 1.10.3) lib/enum.ex:2982: Enum.to_list/1 (shuttertop 0.3.1) lib/shuttertop/fcm/pusher_http.ex:9

Support for HTTP v1 API

Hi,

This seems to be the most popular Elixir library for interfacing with Firebase Cloud Messaging so I thought I'd open a feature request here first. The current Firebase docs recommend that users eventually migrate over to the HTTP v1 API. Are there any plans to add support? Or would you rather accept a pull request?

Thanks for the work!

fcmex doesn't compile with retry v 0.10.0

Here's a repro:

[I] ~/r/fcmex (master|✔) $ mix compile
==> exactor
Compiling 10 files (.ex)
Generated exactor app
# lots of lines cut
Generated credo app
==> fcmex
Compiling 6 files (.ex)
Generated fcmex app
[I] ~/r/fcmex (master|✔) $ mix deps.update retry
Resolving Hex dependencies...
Dependency resolution completed:
Unchanged:
  bunt 0.2.0
  certifi 1.2.1
  credo 0.8.1
  earmark 1.2.2
  ex_doc 0.16.1
  exactor 2.2.3
  excoveralls 0.7.0
  exjsx 3.2.1
  exvcr 0.8.10
  flow 0.12.0
  gen_stage 0.12.0 RETIRED!
    (invalid) Cancel and info messages in producer_consumer can be delivered out of order, leading to data loss
  hackney 1.8.6
  httpoison 0.11.2
  idna 5.0.2
  jsx 2.8.2
  meck 0.8.4
  metrics 1.0.1
  mimerl 1.0.2
  poison 3.1.0
  ssl_verify_fun 1.1.1
  unicode_util_compat 0.2.0
Upgraded:
  retry 0.7.0 => 0.10.0
* Updating retry (Hex package)
[I] ~/r/fcmex (master|✚1…) $ mix compile
==> retry
Compiling 2 files (.ex)
Generated retry app
==> fcmex
Compiling 6 files (.ex)

== Compilation error in file lib/fcmex/subscription.ex ==
** (ArgumentError) invalid syntax, only "retry", "after" and "else" are permitted
    expanding macro: Retry.retry/2
    lib/fcmex/subscription.ex:66: Fcmex.Subscription.request/1
    (elixir) expanding macro: Kernel.|>/2
    lib/fcmex/subscription.ex:69: Fcmex.Subscription.request/1
[I] ~/r/fcmex (master|✚1…) [1] $

It popped up in our project when we were using fcmex as a dependency because we didn't have retry locked to an earlier version.

I'm going to look at what's causing it and see if there's an obvious fix, just raising it as an issue for now.

Testing error

Hello. Thanks for good project.
I'm running test after setup FCM_SERVER_KEY, but it shows error like

1) test payload test (FcmexTest)
     test/fcmex_test.exs:182
     Expected false or nil, got true
     code: refute Map.has_key?(payload, :mutable_content)
     stacktrace:
       test/fcmex_test.exs:184: (test)

.
14:13:22.134 [error] GenServer #PID<0.2279.0> terminating
** (ExVCR.RequestNotMatchError) Request did not match with any one in the current cassette: fixture/vcr_cassettes/over_thousand_messages.json.
Delete the current cassette with [mix vcr.delete] and re-record.

Request: [:post, "https://fcm.googleapis.com/fcm/send", [{"Content-Type", "application/json"}, {"Authorization", "key=my_fcm_server_key"}], "{\"to\":null,\"time_to_live\":null,\"registration_ids\":[\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\",\"FCM_TOKEN\"
...
Finished in 1.5 seconds
10 tests, 2 failures

Do I have to setup registration id, or something else?
Failure happens in test payload test (FcmexTest) and test request 1000+ more messages (FcmexTest).

Thanks.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v3
  • erlef/setup-beam v1
  • ubuntu 20.04
.github/workflows/contributors.yml
  • akhilmhdh/contributors-readme-action v2.3.6
.github/workflows/release-please.yml
  • google-github-actions/release-please-action v3
  • actions/checkout v3
  • erlef/setup-beam v1
mix
mix.exs
  • httpoison >= 0.0.0
  • poison >= 0.0.0
  • flow ~> 1.2.0
  • retry ~> 0.18.0
  • credo ~> 1.3
  • ex_doc >= 0.0.0
  • exvcr >= 0.0.0
  • excoveralls ~> 0.14 and >= 0.14.4

  • Check this box to trigger a request for Renovate to run again on this repository

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.