message_db.dart 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'package:flutter/material.dart';
  5. import 'package:path/path.dart';
  6. import 'package:path_provider/path_provider.dart';
  7. import 'package:provider/provider.dart';
  8. import 'package:sport/bean/login.dart';
  9. import 'package:sport/bean/message.dart';
  10. import 'package:sport/provider/user_model.dart';
  11. import 'package:sqflite/sqflite.dart';
  12. class MessageItem {
  13. int? status;
  14. int? curId;
  15. int? id;
  16. // 时间
  17. DateTime? dateTime;
  18. int? day;
  19. int? time;
  20. String? type;
  21. MessageData? data;
  22. bool? self;
  23. MessageItem({this.status, this.curId, this.id, this.dateTime, this.day, this.time, this.type, this.data, this.self});
  24. MessageItem.fromJson(Map<String, dynamic> map) {
  25. id = map['id'];
  26. dateTime = DateTime.parse(map['created_at']);
  27. day = dateTime?.day;
  28. time = dateTime?.millisecondsSinceEpoch;
  29. if (map['data'] != null) {
  30. try {
  31. data = MessageData.fromJson(json.decode(map['data']));
  32. } catch (e) {
  33. print(e);
  34. }
  35. }
  36. self = (map['self'] ?? 0) == 1;
  37. curId = map['curId'];
  38. type = map['type'];
  39. }
  40. }
  41. class MessageDB {
  42. static final MessageDB _instance = new MessageDB.internal();
  43. factory MessageDB() => _instance;
  44. static Database? _db;
  45. MessageDB.internal();
  46. Future<Database> get db async {
  47. if (_db != null) {
  48. return _db!;
  49. }
  50. _db = await initDb();
  51. return _db!;
  52. }
  53. final String TABLE = 'Message';
  54. final String USERTABLE = "user";
  55. initDb() async {
  56. String databasesPath = await getDatabasesPath();
  57. String path = join(databasesPath, 'message.db');
  58. var db = await openDatabase(path, version: 6, onCreate: _onCreate, onUpgrade: _onUpgrade);
  59. return db;
  60. }
  61. FutureOr<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
  62. if (newVersion > oldVersion) {
  63. try {
  64. await db.execute("drop table $TABLE");
  65. } catch (e) {
  66. print(e);
  67. }
  68. try {
  69. await db.execute("drop table $USERTABLE");
  70. } catch (e) {
  71. print(e);
  72. }
  73. }
  74. await _onCreate(db, newVersion);
  75. }
  76. // @messageId 本地数据库的id
  77. // @status 该条数据是否是已读的
  78. // @message 信息
  79. // @userId 跟谁聊天的信息 跟谁 跟谁 跟谁 跟谁 ...
  80. FutureOr<void> _onCreate(Database db, int version) async {
  81. // 表1: message表
  82. await db.execute(
  83. 'CREATE TABLE $TABLE(id INTEGER PRIMARY KEY, chat_id INTEGER, status INTEGER, self INTEGER, type TEXT, data TEXT, curId INTEGER, created_at TEXT)');
  84. // 表2: 用户表
  85. await db.execute('CREATE TABLE $USERTABLE(id INTEGER PRIMARY KEY, me INTEGER, user_id INTEGER, name TEXT , avatar TEXT, isTop INTEGER)');
  86. }
  87. Future<int> createChatUser(int me, MessageUser user) async {
  88. var dbClient = await db;
  89. var result = await dbClient.insert(USERTABLE, {
  90. "me": me,
  91. "user_id": user.id,
  92. "name": user.name,
  93. "avatar": user.avatar,
  94. "isTop": 0,
  95. });
  96. return result;
  97. }
  98. Future insertAll(List<Map<String, dynamic>> items) async {
  99. var dbClient = await db;
  100. var batch = dbClient.batch();
  101. items.forEach((item) {
  102. batch.insert(TABLE, item);
  103. });
  104. batch.commit();
  105. }
  106. // 最新的那些...
  107. Future<List<Map<String, dynamic>>> findLatest() async {
  108. var dbClient = await db;
  109. return await dbClient.rawQuery(
  110. 'SELECT * FROM $TABLE ORDER BY curId DESC LIMIT 1',
  111. );
  112. }
  113. Future<List<Map<String, dynamic>>> findAll() async {
  114. var dbClient = await db;
  115. return await dbClient.rawQuery(
  116. 'SELECT * FROM $TABLE ORDER BY messageId DESC',
  117. );
  118. }
  119. Future<List<Map<String, dynamic>>> findHasUserId(int me, int userId) async {
  120. var dbClient = await db;
  121. return await dbClient.rawQuery("SELECT * FROM $USERTABLE where me = $me and user_id = $userId limit 1");
  122. }
  123. // 更新状态...
  124. Future updateStatus(int chatId) async {
  125. var dbClient = await db;
  126. // status = 0:已读状态, 1:未读
  127. await dbClient.update(
  128. TABLE,
  129. {"status": 0},
  130. where: "chat_id = ?",
  131. whereArgs: [chatId],
  132. );
  133. }
  134. Future updateData(MessageItem item) async {
  135. var dbClient = await db;
  136. item.status = 0;
  137. await dbClient.update(
  138. TABLE,
  139. {"data": json.encode(item.data)},
  140. where: "id = ?",
  141. whereArgs: [item.id],
  142. );
  143. }
  144. // 更新状态...
  145. Future updateIsTop(int id, int isTop) async {
  146. var dbClient = await db;
  147. // status = 0 表示 没有置顶 ... 1:已经置顶
  148. await dbClient.update(
  149. USERTABLE,
  150. {"isTop": isTop},
  151. // Ensure that the Dog has a matching id.
  152. where: "id = ?",
  153. // Pass the Dog's id as a whereArg to prevent SQL injection.
  154. whereArgs: [id],
  155. );
  156. }
  157. Future<List<Map<String, dynamic>>> getMessageForUserId(int chatId) async {
  158. var dbClient = await db;
  159. return await dbClient.rawQuery(
  160. 'SELECT * FROM $TABLE WHERE chat_id = $chatId order by id desc',
  161. );
  162. }
  163. // 删除数据表格
  164. Future<int> delete() async {
  165. var dbClient = await db;
  166. return await dbClient.delete("$TABLE");
  167. }
  168. // 获取还有多少未读的数量
  169. Future<List<Map<String, dynamic>>> getMessageUnRead(String self) async {
  170. var dbClient = await db;
  171. return await dbClient.rawQuery("select u.*, c.*, ccc.cout from "
  172. "$TABLE c, "
  173. "(select chat_id, max(id) mid FROM $TABLE group by chat_id) cc,"
  174. "(select chat_id, sum(status) cout FROM $TABLE group by chat_id) ccc, "
  175. "$USERTABLE u "
  176. "where u.me = $self and u.id = ccc.chat_id and cc.chat_id = ccc.chat_id and c.id = cc.mid order by u.isTop desc, c.id desc;");
  177. }
  178. // 删除数据库
  179. void deleteTable() async {
  180. var databasesPath = await getDatabasesPath();
  181. String path = join(databasesPath, 'message.db');
  182. await deleteDatabase(path);
  183. print('删除数据库');
  184. }
  185. Future<int> deleteMessage(int messageId) async {
  186. var dbClient = await db;
  187. return await dbClient.delete("$TABLE", where: "messageId = ?", whereArgs: [messageId]);
  188. }
  189. Future<int> deleteUserIdMessage(int userId) async {
  190. var dbClient = await db;
  191. return await dbClient.delete("$TABLE", where: "chat_id=?", whereArgs: [userId]);
  192. }
  193. Future<int> deleteMessageIdMessage(int messageId) async {
  194. var dbClient = await db;
  195. return await dbClient.delete("$TABLE", where: "id=?", whereArgs: [messageId]);
  196. }
  197. void updateChatUser(int id, MessageUser other) async {
  198. var dbClient = await db;
  199. await dbClient.update(
  200. USERTABLE,
  201. {"name": other.name, "avatar": other.avatar},
  202. where: "id = ?",
  203. whereArgs: [id],
  204. );
  205. }
  206. // Future<int> delete(int time) async {
  207. // var dbClient = await db;
  208. // return await dbClient.delete(TABLE, where: "time <= ?", whereArgs: [time]);
  209. // }
  210. }