用MQK寫一個自動記賬的應用
不知道大家平時是否記賬,反正我是不記的。最近想知道平時都花了多少錢,比如做一個支出的趨勢圖看看,順便在看看支出明細。
作為一個工程師,查看消費短信遠遠達不到我的要求。最好是可以把每一筆消費都記錄在數據庫里面,這樣就想怎么玩就怎么玩。沒事用SELECT查詢消費清單,或者用GROUP sum 一下每段時間的消費總額,這樣感覺就很爽。
銀行一般都有消費短信的提醒,可以分析短信的內容得到消費記錄,再保存到數據庫里面。
思路是這樣的,寫一個Android的App,接收到短信后把短信內容發送給PHP后端程序分析并入庫。我手上的這臺安卓是一個備用機,所以接收到短信之后,還要把其他所有的短信用郵件發送到郵箱。
下面是數據庫保存支出的時間和金額,金額的單位按分保存。
mysql> select * from payments;
+----+------+-------+---------------------+---------------------+---------------------+
| id | bank | money | charge_time | created_at | updated_at |
+----+------+-------+---------------------+---------------------+---------------------+
| 1 | | 6000 | 2017-10-02 22:04:00 | 2017-10-05 00:02:56 | 2017-10-05 00:02:56 |
| 2 | | 6000 | 2017-10-02 22:04:00 | 2017-10-05 00:12:29 | 2017-10-05 00:12:29 |
| 3 | | 6000 | 2017-10-02 22:04:00 | 2017-10-05 00:15:06 | 2017-10-05 00:15:06 |
| 4 | | 6000 | 2017-10-02 22:04:00 | 2017-10-05 00:15:14 | 2017-10-05 00:15:14 |
| 5 | | 98 | 2017-10-05 08:28:00 | 2017-10-05 00:28:33 | 2017-10-05 00:28:33 |
| 6 | | 351 | 2017-10-05 08:29:00 | 2017-10-05 00:29:19 | 2017-10-05 00:29:19 |
| 7 | | 98 | 2017-10-05 08:33:00 | 2017-10-05 00:33:37 | 2017-10-05 00:33:37 |
| 8 | | 3901 | 2017-10-05 08:35:00 | 2017-10-05 00:36:15 | 2017-10-05 00:36:15 |
| 9 | | 1000 | 2017-10-06 06:25:00 | 2017-10-05 22:25:31 | 2017-10-05 22:25:31 |
| 10 | | 4300 | 2017-10-07 04:17:00 | 2017-10-06 20:17:31 | 2017-10-06 20:17:31 |
| 11 | | 17800 | 2017-10-07 05:48:00 | 2017-10-06 21:48:42 | 2017-10-06 21:48:42 |
| 12 | | 2340 | 2017-10-07 07:09:00 | 2017-10-06 23:09:36 | 2017-10-06 23:09:36 |
| 13 | | 450 | 2017-10-08 00:12:00 | 2017-10-07 16:12:16 | 2017-10-07 16:12:16 |
| 14 | | 2700 | 2017-10-08 00:30:00 | 2017-10-07 16:30:28 | 2017-10-07 16:30:28 |
| 15 | | 1100 | 2017-10-08 01:58:00 | 2017-10-07 17:58:37 | 2017-10-07 17:58:37 |
| 16 | | 11600 | 2017-10-08 01:53:00 | 2017-10-07 17:59:00 | 2017-10-07 17:59:00 |
| 17 | | 2800 | 2017-10-08 04:52:00 | 2017-10-07 20:52:19 | 2017-10-07 20:52:19 |
+----+------+-------+---------------------+---------------------+---------------------+
17 rows in set (0.00 sec)
郵件接收短信
用到的框架
因為后端只是提供一個接口保存支出和發送郵件,所以框架選擇了lumen
,沒有用laravel。用symfony/swiftmailer
發送郵件。郵件發送過程通常需要很長時間,不希望支出接口把Android客戶端請求Hold太久時間,用mqk/mqk
做后臺背景任務。
MQK是純PHP的多進程背景任務處理框架,客戶端使用K::invoke('Mailer', 'Subject', 'example@qq.com')
發起一個異步調用。MQK會將任務進入消息隊列,并在后臺執行。特別適合郵件發送這樣的場景。
這里我使用了MQK的另外一個特性:事件機制,短信接口在接收到短信后派發一個接收到短信的事件。
事件機制相當于觀察者模式,特別適合對代碼進行解耦。另外MQK使用固定的進程池,和其他的消息隊列組件不同。一般的消息隊列組件會在消息到達的時候啟動一個新的進程并在任務完成后銷毀,在消息吞吐量比較大的時候會產生很大的開銷。
MQK使用和php-fpm類似的進程管理機制,啟動固定的多個進程,如果進程數量不夠的時候,可以動態的調整。
https://github.com/imcj/mqk 是MQK項目的地址,可以用 composer require mqk/mqk
安裝。
- 定義短信保存接口的路由
# routes/web.php
$router->post('/', 'InboxController@sms');
- 實現控制器
\K::dispatch
作用是派發事件,message.in
是事件名。MessageInEvent
是事件,定義在App\Events\MessageInEvent
class InboxController
{
public function sms(Request $request)
{
$sender = $request->get("sender");
$message = $request->get("message");
\K::dispatch("message.in", new MessageInEvent($sender, $message));
}
}
- 定義MessageInEvent
# app/Events/MessageInEvent.php
class MessageInEvent extends \Symfony\Component\EventDispatcher\Event
{
public $sender;
public $message;
public function __construct($sender, $message)
{
$this->sender = $sender;
$this->message = $message;
}
}
- 監聽MessageIn事件
\K::addListener
監聽message.in
事件,接收短信分析出時間和金額,然后保存。
最后用Swift Mailer
將短信轉發到我的郵箱。
# /bootstrap.php
\K::addListener("message.in", function(MessageInEvent $event) {
$sender = $event->sender;
$message = $event->message;
$financeMessage = new Message();
$payment = $financeMessage->extract($message);
if ($payment) {
$payment->save();
}
$transport = (new \Swift_SmtpTransport(getenv("SMTP_HOST"), (int)getenv("SMTP_PORT"), 'ssl'))
->setUsername(getenv("SMTP_USER"))
->setPassword(getenv("SMTP_PASSWORD"));
$mailer = new \Swift_Mailer($transport);
$message = (new \Swift_Message("SMS from {$sender}"))
->setFrom(['weicongju@qq.com' => 'weicongju'])
->setTo(['weicongju@qq.com' => 'weicongju'])
->setBody($message);
$mailer->send($message);
});
使用qqq
上面的lumen項目已經把源代碼push到github上了,只需要clone下來并部署一下就可以用了。
Download source code
$ git clone https://github.com/imcj/qqq
安裝依賴
$ composer install
配置數據庫和SMTP
編輯 .env 文件
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=data
DB_USERNAME=root
DB_PASSWORD=123456
SMTP_HOST=smtp.qq.com
SMTP_PORT=465
SMTP_USER=
SMTP_PASSWORD=
QUEUE_DRIVER=array
部署數據庫
$ php artisan migate
運行演示
$ php -S localhost:8000 -t public
Android
Android完整源代碼在 https://github.com/imcj/QQQAndroid
iOS沒有辦法監聽短信,只能用一個Android備用機處理。思路是android.provider/Telephony.SMS_RECEIVED
Intent 接收短信。
修改配置文件
拷貝 app/src/main/assets/config.properties.example
到 app/src/main/asset/config.properties
沒有sentry的可以在 https://getsentry.com 申請并注冊一個項目
app/src/main/assets/config.properties
apiURL=新部署的API URL
sentry=Sentry DSN
配置短信接收
配置IncomingBroadcastReceiver
作為短信的Receiver 。
<application>
<receiver android:permission="android.permission.BROADCAST_SMS" android:name=".IncomingBroadcastReceiver" android:enabled="true" android:exported="true">
<intent-filter android:priority="2147483647">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
在IncomingBroadcastReceiver中查詢接收的短信。調HTTPGateway.sendMessage
發送短信。這里短信接收的接口使用MQK異步發送郵件和寫入記錄,接口響應時間只有40ms。
public class IncomingBroadcastReceiver extends BroadcastReceiver {
HTTPGateway gateway;
@Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (null == bundle)
return;
final Object[] objects = (Object[]) bundle.get("pdus");
for (int i = 0, size = objects.length; i < size; i++) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) objects[i]);
String phoneNumber = smsMessage.getDisplayOriginatingAddress();
String body = smsMessage.getMessageBody();
gateway.message(phoneNumber, body);
Log.i("receive", phoneNumber + " " + body);
}
} catch (Exception e) {
Log.e("Receive", e.getMessage());
}
Log.i("info", "On receive");
}
}
Android異常重啟
考慮到在莫名的情況下Android會崩潰,增加一個Android異常后重啟的功能。設置默認的異常處理,出現異常的時候重啟自己。
設置Application啟動的Java類。
<application
...
android:name=".QQQApplication">
</application>
在QQQApplication中捕獲異常并重啟App
public class QQQApplication extends Application {
private static QQQApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
Thread.setDefaultUncaughtExceptionHandler(restartHandler);
}
private Thread.UncaughtExceptionHandler restartHandler = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread thread, Throwable ex) {
restartApp();
}
};
public void restartApp() {
Intent intent = new Intent(instance,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
instance.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
}
}
使用SentryAndroid捕獲異常
Sentry是一個全平臺的異常捕獲軟件,當軟件出現異常時把錯誤信息發送到Sentry后臺,方便出現問題的時候追蹤錯誤
在MainActivity中配置Sentry。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context ctx = this.getApplicationContext();
// Use the Sentry DSN (client key) from the Project Settings page on Sentry
String sentryDsn = "https://[key]:[secret]@sentry.io/[id]?options";
Sentry.init(sentryDsn, new AndroidSentryClientFactory(ctx));
}
}