Created
June 6, 2023 09:03
-
-
Save Jalson1982/857dad4ffc20c4d242f33c7b988de676 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {openDatabase} from 'react-native-sqlite-storage'; | |
import {RootState, store} from '../store'; | |
import { | |
ADD_MESSAGE, | |
GET_LOCAL_DB_DATA, | |
S_UPDATE_UNREADS, | |
TABLE_SPINNER, | |
} from '../helpers/constants'; | |
import {Message} from '../interfaces&classes/message-classes'; | |
import {postProcessMessages, sequenceMessages} from '../helpers/helpers'; | |
import {IObjectNumber} from '../interfaces&classes/common'; | |
import {Platform} from 'react-native'; | |
let errorCB = err => {}; | |
let successCB = () => {}; | |
let openCB = () => {}; | |
// var db = openDatabase("8seatchatTable.db", "1.0", "Test Database", 200000, openCB, errorCB); | |
var db = openDatabase( | |
{ | |
name: '8seatchatTable.db', | |
location: 'default', | |
createFromLocation: '~8seatchatTable.db', | |
}, | |
openCB, | |
errorCB, | |
); | |
export const getDBConnection = async () => { | |
return openDatabase({ | |
name: '8seatchatTable', | |
location: 'default', | |
createFromLocation: '8seatchatTable.db', | |
}); | |
}; | |
export const deleteDb = async () => { | |
db.transaction(tx => { | |
tx.executeSql( | |
'DROP TABLE IF EXISTS Messages', | |
[], | |
(tx, results) => { | |
// | |
}, | |
err => { | |
// | |
}, | |
); | |
}); | |
db.transaction(tx => { | |
tx.executeSql( | |
'DROP TABLE IF EXISTS EncryptionKeys', | |
[], | |
(tx, results) => { | |
// | |
}, | |
err => { | |
// | |
}, | |
); | |
}); | |
}; | |
export const createTable = async () => { | |
// create table if not exists | |
db.transaction(function (txn) { | |
txn.executeSql( | |
"SELECT name FROM sqlite_master WHERE type='table' AND name='Messages'", | |
[], | |
function (tx, res) { | |
if (res.rows.length == 0) { | |
// | |
// txn.executeSql('DROP TABLE IF EXISTS Messages', []); | |
txn.executeSql( | |
'CREATE TABLE IF NOT EXISTS Messages(_id VARCHAR(36) PRIMARY KEY, tableId VARCHAR(36), text LONGTEXT, code INTEGER, image TEXT, sender VARCHAR(36), time TIMESTAMP, mine BOOLEAN,showInfo BOOLEAN,emoji BOOLEAN, fontSize INTEGER,isEdit BOOLEAN,isDelete BOOLEAN,sent BOOLEAN,isRead BOOLEAN,_index INTEGER, updatedAt TIMESTAMP)', | |
[], | |
); | |
} | |
}, | |
err => {}, | |
); | |
}); | |
}; | |
export const bulkSaveChatData = (messages: Message[]) => { | |
let query = | |
'INSERT OR REPLACE INTO Messages (_id, tableId, text, code, image, sender, time, mine, showInfo, emoji, fontSize, isEdit, isDelete, sent, _index,isRead, updatedAt) VALUES '; | |
let queryArray: string[] = []; | |
messages.forEach((m, i) => { | |
// | |
queryArray.push( | |
`('${m._id}','${m.tableId}','${m.text.replace(/'/g, "''")}',${m.code},'${ | |
m.image | |
}','${m.sender}',${m.time},${m.mine},${m.showInfo},${m.emoji},${ | |
m.fontSize | |
},${m.isEdit},${m.isDelete},${m.sent},${m.index},${m.isRead}, ${ | |
m.updatedAt | |
})`, | |
); | |
}); | |
return new Promise((resolve, reject) => { | |
db.transaction(function (tx) { | |
tx.executeSql( | |
query + queryArray.join(','), | |
[], | |
(_tx, results) => { | |
// | |
resolve('success'); | |
getConvesations(); | |
if (results.rowsAffected > 0) { | |
// getChatData(); | |
} else { | |
} | |
}, | |
err => { | |
reject(err); | |
}, | |
); | |
}); | |
}); | |
}; | |
export const saveChatData = data => { | |
// | |
db.transaction(function (tx) { | |
tx.executeSql( | |
'INSERT OR REPLACE INTO Messages (_id, tableId, text, code, image, sender, time, mine, showInfo, emoji, fontSize, isEdit, isDelete, sent, _index,isRead, updatedAt) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', | |
[ | |
data._id, | |
data.tableId, | |
data.text, | |
data.code, | |
data.image, | |
data.sender, | |
data.time, | |
data.mine, | |
data.showInfo, | |
data.emoji, | |
data.fontSize, | |
data.isEdit, | |
data.isDelete, | |
data.sent, | |
data.index, | |
data.isRead, | |
data.updatedAt, | |
], | |
(_tx, results) => { | |
getUnreads(data.tableId); | |
}, | |
); | |
}); | |
}; | |
export const getMoreChatData = ( | |
tableId: string, | |
code: number, | |
index = 0, | |
lastMessageTime: number, | |
): Promise<Message[]> => { | |
let messages: Message[] = []; | |
const t0 = new Date().getTime(); | |
return new Promise((resolve, reject) => { | |
db.transaction(tx => { | |
tx.executeSql( | |
`SELECT * FROM Messages where tableId = '${tableId}' and code = '${code}' AND time < ${lastMessageTime} order by time desc limit 50`, | |
[], | |
async (err: any, results: any) => { | |
for (let i = 0; i < results.rows.length; ++i) { | |
const row = results.rows.item(i); | |
messages.push(row); | |
} | |
// messages = sequenceMessages(messages) | |
const t1 = new Date().getTime(); | |
// | |
// | |
store.dispatch({type: TABLE_SPINNER, payload: false}); | |
store.dispatch({type: ADD_MESSAGE, payload: {messages, index}}); | |
resolve(messages); | |
}, | |
err => { | |
reject([]); | |
}, | |
); | |
}); | |
}); | |
}; | |
export const getUnreads = (tableId: string): Promise<IObjectNumber> => { | |
// | |
let unreads: IObjectNumber = {}; | |
const t0 = new Date().getTime(); | |
return new Promise((resolve, reject) => { | |
db.transaction(tx => { | |
tx.executeSql( | |
`SELECT code,sum(isRead) as unread FROM Messages where tableId = '${tableId}' group by code`, | |
[], | |
async (err: any, results: any) => { | |
for (let i = 0; i < results.rows.length; ++i) { | |
const row = results.rows.item(i); | |
// messages.push(row); | |
unreads[row.code] = row.unread; | |
} | |
// | |
store.dispatch({type: S_UPDATE_UNREADS, payload: {unreads, tableId}}); | |
const t1 = new Date().getTime(); | |
// | |
resolve(unreads); | |
}, | |
err => { | |
reject({}); | |
}, | |
); | |
}); | |
}); | |
}; | |
export const getConvesations = (offset = 0) => { | |
let temp = []; | |
const t0 = new Date().getTime(); | |
db.transaction(tx => { | |
tx.executeSql( | |
`SELECT *,sum(isRead) as unread FROM (SELECT * FROM Messages order by time desc) as m group by tableId, code`, | |
[], | |
async (err, results) => { | |
for (let i = 0; i < results.rows.length; ++i) { | |
const row = results.rows.item(i); | |
temp.push(row); | |
} | |
temp = sequenceMessages(temp); | |
store.dispatch({type: GET_LOCAL_DB_DATA, payload: temp}); | |
}, | |
err => {}, | |
); | |
}); | |
}; | |
export const getLastMessageTime = async (offset = 0) => { | |
try { | |
let messages = []; | |
const t0 = new Date().getTime(); | |
return new Promise((resolve, reject) => { | |
db.transaction(tx => { | |
tx.executeSql( | |
`SELECT updatedAt as time, tableId FROM (SELECT * FROM Messages order by time desc) m group by tableId`, | |
[], | |
(err, results) => { | |
for (let i = 0; i < results.rows.length; ++i) { | |
const row = results.rows.item(i); | |
messages.push(row); | |
} | |
const t1 = new Date().getTime(); | |
// | |
resolve(messages); | |
}, | |
err => { | |
reject([]); | |
}, | |
); | |
}); | |
}); | |
} catch (error) {} | |
}; | |
export const updateChatData = (tableId: any, code: number) => { | |
db.transaction(tx => { | |
tx.executeSql( | |
'UPDATE Messages set isRead=? where tableId=? and code =?', | |
[false, tableId, code], | |
(tx, results) => { | |
if (results.rowsAffected > 0) { | |
getUnreads(tableId); | |
// | |
} else { | |
// | |
} | |
}, | |
); | |
}); | |
}; | |
export const deleteChatData = (tableId: any) => { | |
// | |
db.transaction(tx => { | |
tx.executeSql( | |
'DELETE FROM Messages where tableId=?', | |
[tableId], | |
(tx, results) => { | |
if (results.rowsAffected > 0) { | |
getConvesations(); | |
} else { | |
} | |
}, | |
); | |
}); | |
}; | |
export const createKeysTable = async () => { | |
// create table if not exists | |
db.transaction(function (txn) { | |
txn.executeSql( | |
"SELECT name FROM sqlite_master WHERE type='table' AND name='EncryptionKeys'", | |
[], | |
function (tx, res) { | |
if (res.rows.length == 0) { | |
// | |
// txn.executeSql('DROP TABLE IF EXISTS Messages', []); | |
txn.executeSql( | |
'CREATE TABLE IF NOT EXISTS EncryptionKeys(_id VARCHAR(36) PRIMARY KEY,userId VARCHAR(36),code INTEGER, userSecretKey LONGTEXT,senderPublicKey LONGTEXT)', | |
[], | |
); | |
} | |
}, | |
err => {}, | |
); | |
}); | |
}; | |
export const saveUserKeys = data => { | |
// | |
// db.transaction(tx => { | |
// tx.executeSql( | |
// 'DELETE FROM EncryptionKeys where _id=?', | |
// [data._id], | |
// (tx, results) => { | |
// | |
// if (results.rowsAffected > 0) { | |
// getConvesations(); | |
// | |
// } else { | |
// | |
// } | |
// }, | |
// ); | |
// }); | |
db.transaction(function (tx) { | |
tx.executeSql( | |
'INSERT OR REPLACE INTO EncryptionKeys (_id, userId, code, userSecretKey, senderPublicKey) VALUES (?,?,?,?,?)', | |
[ | |
data._id, | |
data.userId, | |
data.code, | |
data.userSecretKey, | |
data.senderPublicKey, | |
], | |
(_tx, results) => { | |
// getUnreads(data.tableId); | |
}, | |
); | |
}); | |
}; | |
export const getKeys = (tableId: any, code: any, response: any) => { | |
try { | |
let temp: any = []; | |
return new Promise((resolve, reject) => { | |
db.transaction(tx => { | |
tx.executeSql( | |
`SELECT * FROM EncryptionKeys where _id = '${tableId}' and code = '${code}'`, | |
[], | |
(err, results) => { | |
// | |
const row = results.rows.item(0); | |
response(row); | |
// temp.push(row); | |
// for (let i = 0; i < results.rows.length; ++i) { | |
// } | |
resolve(response); | |
}, | |
err => { | |
reject([]); | |
}, | |
); | |
}); | |
}); | |
} catch (error) {} | |
}; | |
export const filterData = (text: any, response: any) => { | |
try { | |
let temp: any = []; | |
return new Promise((resolve, reject) => { | |
db.transaction(tx => { | |
tx.executeSql( | |
`SELECT * FROM Messages where text LIKE '%${text}%'`, | |
[], | |
(err, results) => { | |
for (let i = 0; i < results.rows.length; ++i) { | |
const row = results.rows.item(i); | |
temp.push(row); | |
} | |
// const row = results.rows.item(0); | |
// | |
response(temp); | |
// temp.push(row); | |
// for (let i = 0; i < results.rows.length; ++i) { | |
// } | |
// | |
resolve(temp); | |
}, | |
err => { | |
reject([]); | |
}, | |
); | |
}); | |
}); | |
} catch (error) {} | |
}; | |
export const fetchFilterMessage = async (data: any) => { | |
// | |
const seconds = Math.floor(parseInt(data.time) / 1000); | |
try { | |
return new Promise((resolve, reject) => { | |
db.transaction(tx => { | |
tx.executeSql( | |
`SELECT * | |
FROM ( | |
SELECT * | |
FROM Messages | |
WHERE tableId = '${data.tableId}' | |
AND code = '${data.code}' | |
AND time < '${data.time}' | |
ORDER BY time desc | |
LIMIT 30 | |
) sub1 | |
UNION | |
SELECT * | |
FROM Messages | |
WHERE tableId = '${data.tableId}' | |
AND code = '${data.code}' | |
AND time = '${data.time}' | |
ORDER BY time desc; | |
`, | |
[], | |
(err: any, results: any) => { | |
const messages: Message[] = []; | |
for (let i = 0; i < results.rows.length; ++i) { | |
const row = results.rows.item(i); | |
messages.push(row); | |
} | |
store.dispatch({ | |
type: 'FETCH_FILTER_MESSAGES', | |
payload: {messages: messages, data: data}, | |
}); | |
resolve(messages); | |
}, | |
err => { | |
reject([]); | |
}, | |
); | |
}); | |
}); | |
} catch (error) { | |
console.error(error); | |
} | |
}; | |
export const fetchMoreMessage = async ( | |
tableId: string, | |
code: number, | |
index = 0, | |
lastMessageTime: number, | |
) => { | |
// const seconds = Math.floor(parseInt(selectedMessageTime) / 1000); | |
let messages: Message[] = []; | |
try { | |
return new Promise((resolve, reject) => { | |
db.transaction(tx => { | |
tx.executeSql( | |
`SELECT * FROM Messages where tableId = '${tableId}' and code = '${code}' AND time > ${lastMessageTime} order by time asc limit 1`, | |
[], | |
(err: any, results: any) => { | |
for (let i = 0; i < results.rows.length; ++i) { | |
const row = results.rows.item(i); | |
messages.push(row); | |
} | |
store.dispatch({type: TABLE_SPINNER, payload: false}); | |
if (messages.length > 0) { | |
store.dispatch({ | |
type: 'ADD_BOTTOM_MESSAGE', | |
payload: {messages, index}, | |
}); | |
resolve(messages); | |
} | |
}, | |
err => { | |
reject([]); | |
}, | |
); | |
}); | |
}); | |
} catch (error) { | |
console.error(error); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment