星期二, 3月 19, 2019

[Nodejs] Use emitter.setMaxListeners() to increase limit 事件監聽超過最大限制

發現nodejs噴出了Use emitter.setMaxListeners() to increase limit 的警告,
找到stackoverflow的討論,但也有人說明是不是要把on 用once取代掉或有on被寫在for回圈裡面。

By default, a maximum of 10 listeners can be registered for any single event.
If it's your code, you can specify maxListeners via:
const emitter = new EventEmitter()
emitter.setMaxListeners(100)
// or 0 to turn off the limit
emitter.setMaxListeners(0)
But if it's not your code you can use the trick to increase the default limit globally:
require('events').EventEmitter.prototype._maxListeners = 100;
Of course you can turn off the limits but be careful:
// turn off limits by default (BE CAREFUL)
require('events').EventEmitter.prototype._maxListeners = 0;
BTW. The code should be at the very beginning of the app.
ADD: Since node 0.11 this code also works to change the default limit:
require('events').EventEmitter.defaultMaxListeners = 0

星期三, 3月 06, 2019

[FCM] 如何在web端取得registration token

如何在用戶的 web client端產生網頁的registration token

https://firebase.google.com/docs/cloud-messaging/js/client#access_the_registration_token

[FCM] firebase常見q&a

  1. Do I have to unsubscribe the old token and subscribe the new token to topics?
AFAIK, you don't have to unsubscribe the old token, since it will be discarded by FCM itself. For the new token, yes, you'll have to subscribe it to the topic you need. The usual thing is done (in Android) by having subscribeToTopic() in onTokenRefreshed().

  1. Do I have to remove the old token and add the new token to device groups?
Yes. You have to handle the mapping/relationships for Device Group Messaging. See my answer here. This is different from topics. The token will be invalidated, but will be kept as part of the list of registration tokens for the corresponding registration key.
It's why there's a possibility to receive a NotRegistred error on one of the tokens if you send to Device Group. :)

  1. Is it possible to get information about device groups/topics for a token?
For Device Group Messaging (same with #2), the developer (you) have to manage these details yourself. For topics, you can use the InstanceID API. Specifically, set details parameter to true:
[optional] boolean details: set this query parameter to true to get available IID token details, including connection information and FCM or GCM topic subscription information (if any) for the device associated with this token. When not specified, defaults to false.

  1. Can I add a token to a device group more than once?
Ahmm. Yes. Do you mean the same token? If so, I haven't tried it yet. Might as well do some checking on the client side before adding.

  1. Can I subscribe a token to a topic more than once?
If you mean re-subscribing, then yes. If you mean duplicate request to subscribe, I think the result would still be a success. No changes in behavior though.

  1. Will multiple subscriptions/additions of the same token result in receiving duplicate messages?
Tested it out. You won't receive duplicate messages for both duplicate topic subscriptions and adding the same token to a device group. It seems that FCM ignores the request to subscribe/add a Registration token if it's already subscribed/added to a device group.

星期一, 2月 18, 2019

星期六, 2月 16, 2019

解決無法bitbucket.org連線的問題

記錄無法bitbucket連線的問題

Q: Could not resolve hostname bitbucket.org: Temporary failure in name resolution
A:
sudo vim /etc/resolv.conf
nameserver 8.8.8.8
search bitbucket.org
測試連線
nslookup bitbucket.org
Server: 10.211.55.1
Address: 10.211.55.1#53

Non-authoritative answer:
Name: bitbucket.org
Address: 18.205.93.2
Name: bitbucket.org
Address: 18.205.93.1
Name: bitbucket.org
Address: 18.205.93.0


星期二, 1月 29, 2019

[AWS] NODEJS SES (Simple Email Services)寄信

第一次設定ses的流程,有需要的朋友可以試試。
寄送信件有發信跟寄信需要設定。SES的操作介面都有

開始設定

1.進入SES設定
https://console.aws.amazon.com/ses/home

2. 設定domain發信


接續上步之後,就可以看到一堆dns相關資訊,這裡我是設定到cloudflare上。填完設定後就會通過domain認證


有通過認證後,就可以看到verified的綠字了


2. 測試發信

新增一個測試的信件,再去這個信箱發信,點擊驗證link。之後email才能測試寄件


接著你可以用Domain/Email Address來寄信。

Domain寄信
則可以自定要發信的email名稱,這樣就可以依不同服務寄送信件給用戶。EX:註冊信



Email Address寄信
可以用驗證過的信箱寄信給指定信箱


3.設定S3收信

可以寄信就要設定收信了,大多都會將信件存到s3上,
請至Email Receiving做規則設定

4.設定IM

沒有開就不能跟SES API整合,參考錯誤處理2

5.移出沙盒模式

沒有開就不能寄沒驗證過的信箱,參考錯誤處理3



之後就要填寫一些相關的資訊,之後就等support team回覆開通就可以串接了。
查看進度可以點以下連結

nodejs aws-sdk錯誤處理


1. Signature時間逾期
{"message":"Signature expired: 20190129T112038Z is now earlier than 20190129T131757Z

要校正機器的時間設定,因為是裝ubuntu可參考下面的
sudo apt-get install ntp ntpdate
sudo ntpdate ntp.ubuntu.com

2. 權限不足

{"message":"User `arn:aws:iam::161004446739:user/<你的帳號>' is not authorized to perform `ses:SendEmail' on resource `arn:aws:ses:us-east-1:<你的awsid>:identity/tester1@gmail.com'"

要去im設定ses的群組,才能使用

3.信箱沒有驗證

{"message":"Email address is not verified. The following identities failed the check in region US-EAST-1: bigdstut@gmail.com","stack":"MessageRejected: Email address is not verified. 
寄信的對像沒有通過驗證,預設是在沙盒模式中
https://docs.aws.amazon.com/zh_tw/ses/latest/DeveloperGuide/request-production-access.html?icmpid=docs_ses_console

參考

https://docs.aws.amazon.com/zh_tw/ses/latest/DeveloperGuide/verify-domain-procedure.html

https://docs.aws.amazon.com/zh_tw/ses/latest/DeveloperGuide/dns-txt-records.html?icmpid=docs_ses_console

https://docs.aws.amazon.com/zh_tw/ses/latest/DeveloperGuide/dkim.html

網域dkim
https://docs.aws.amazon.com/zh_tw/ses/latest/DeveloperGuide/easy-dkim-setup-domain.html

如何設定寫入s3權限
https://docs.aws.amazon.com/zh_tw/ses/latest/DeveloperGuide/receiving-email-permissions.html

寫code
https://github.com/nodemailer/nodemailer-ses-transport
https://medium.com/@yashoda.charith10/sending-emails-using-aws-ses-nodejs-460b8cc6d0d5

http://jsnwork.kiiuo.com/archives/2539/amazon-ses-%E8%A8%AD%E5%AE%9A-email%EF%BC%8C%E8%AE%93%E4%BD%BF%E7%94%A8%E8%80%85%E5%AF%84%E4%BF%A1%E4%BC%BA%E6%9C%8D%E5%99%A8%E6%94%B6%E4%BF%A1%E8%BD%89%E5%AF%84%E7%B5%A6%E7%AE%A1%E7%90%86/

星期二, 1月 15, 2019

星期六, 1月 12, 2019

[AngularJS] 1.x 動態產生表單ng-form的筆記

常常需要寫到在一個form裡面再透過ng-repeat產生多個ng-form
可以參考以下範例
http://embed.plnkr.co/Zu8CPGymfHVKt83S4SzA/preview

簡單記錄一下完成的做法,不然每次用都會忘記...

ng-form的name不需要額外透過ng-repeat的$index動態產生不一樣的流水號也可以做,
先前還有故意產生ticket.formId但其實也不需要!!




星期五, 1月 11, 2019

React.js 異常錯誤大小事

1. 確認Ref的寫法是不是沒有更新,更新就會正常了
uikit.min.js?r=0.2995152529685583:51 Uncaught Error: Minified React error #119; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=119 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    at r (uikit.min.js?r=0.2995152529685583:51)
 Object.addComponentAsRefTo 


星期三, 10月 31, 2018

[three.js] 南北極模糊問題

一行指令解決南北極模糊

var maxAnisotropy = this.renderer.getMaxAnisotropy();

texture.anisotropy = maxAnisotropy;


https://www.jianshu.com/p/9b2702987dd2

星期一, 10月 22, 2018

[FCM] firebase admin 初探筆記: 從backend丟訊息

記錄一下nodejs使用FCM Admin的相關筆記,
主要要透過自已的backend與fcm做溝通,
跟web notification無關。

1. 安裝


npm install firebase-admin --save

2. Firebase開專案


3. 設定金鑰

專案設定頁->點擊服務帳戶的Tab->產生新的私密金鑰



4. 初始化SDK


var admin = require('firebase-admin');
var serviceAccount = require('path/to/serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://.firebaseio.com'
});


當然如果不要透過下載.json,也是可以用變數的方式做初始化。


5. 發送訊息 send()

接著就可以透過admin.messaging()內的send方法發送訊息

// The topic name can be optionally prefixed with "/topics/".
var topic = 'highScores';
// See documentation on defining a message payload.
var message = {
  data: {
    score: '850',
    time: '2:45'
  },
  topic: topic};
// Send a message to devices subscribed to the provided topic.
admin.messaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

也可以在send方法內使用測試模式

admin.messaging().send(message, dryRun)

指定條件的訊息

在message也可以加condition

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";
// See documentation on defining a message payload.
var message = {
  notification: {
    title: '$GOOG up 1.43% on the day',
    body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  condition: condition};
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
admin.messaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

定義訊息

透過fcm可以推播包含webpush/apns(iOS)/android等消息。

一個封裝訊息的欄位參數

参数说明
data键值对映射,其中所有键和值都是字符串。
notification一个包含 title 和 body 字段的对象。
android一个由 Android 消息专用字段组成的对象。要了解详情,请参阅 Android 专用字段
apns一个由 Apple 推送通知服务 (APNS) 专用字段组成的对象。要了解详情,请参阅 APNS 专用字段
webpush一个由 WebPush 协议专用字段组成的对象。要了解详情,请参阅 WebPush 专用字段
token一个用于标识消息的收件人设备的注册令牌。
topic要将消息发送至的主题名称。该主题名称不能包含 /topics/ 前缀。
condition发送消息时所依据的条件,例如 "foo" in topics && "bar" in topics

綜合的訊息

以下是一個主題的推播,並推發到andriod/apns



var message = {
  notification: {
    title: '$GOOG up 1.43% on the day',
    body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
  },
  android: {
    ttl: 3600 * 1000,
    notification: {
      icon: 'stock_ticker_update',
      color: '#f45342',
    },
  },
  apns: {
    payload: {
      aps: {
        badge: 42,
      },
    },
  },
  topic: 'industry-tech'
};

常見授權錯誤

如果你在send訊息出現以下錯誤,

Credential implementation provided to initializeApp() via the \"credential\" property failed to fetch a valid Google OAuth2 access token with the following error

通常都是你目前環境的時間跟FCM的不一致,
只要同步時間就好了,

$>sudo service ntp restart

官方文件
https://firebase.google.com/docs/admin/setup?authuser=2
https://firebase.google.com/docs/cloud-messaging/admin/send-messages?authuser=1

星期一, 3月 26, 2018

[react.js] react-redux 使用流程

實作大多採用react-redux來整合原本的redux,
對於第一次入手的人感覺就是要懂一堆第三方套件後才能好好寫。
自已久久寫一下也會忘記大部份的邏輯,所以記錄一下。


目錄結構

actions =>放觸發的action定義
   -index.js =>負責匯出各redux的動作

constants => app state,
  -models 把各別的state 分類
      -index.js 匯出每個個別的app state
  -ActionTypes.js 匯出action要用的變數

reducers =>定義所有reducers
  -ui
    -UIReducer.js => Layout的reducer
  -index.js =>匯出所有reducers並combine所有reducer

store
  - index.js => 匯入所有app reducers與產生一個app store

產生一個新的redux動作


  1. 到constants/models定義新的redux state
  2. 到constants/index.js 匯出剛剛定義的 reduxstate
  3. 到ActionType.js加新的redux事件
  4. 到actions新增一個對應的 <你的新redux命名>Actions.js 檔案
  5. 到reducers新增一個對應的reducer,<你的新redux命名>Reducer.js 檔案
  6. 到reducers/index.js 匯入剛剛新加的reducer
  7. 到containers下找對應的container元件呼叫要使用的actions並匯入

    1. 登入元件範例    







其他你感興趣的文章

Related Posts with Thumbnails