Skip to content

Commit

Permalink
Merge pull request #4 from kantimam/deploy
Browse files Browse the repository at this point in the history
Deploy
  • Loading branch information
kimamov committed Jan 19, 2021
2 parents 2f81e16 + 00570bc commit 8936e1c
Show file tree
Hide file tree
Showing 18 changed files with 572 additions and 365 deletions.
2 changes: 1 addition & 1 deletion client/.eslintcache

Large diffs are not rendered by default.

16 changes: 9 additions & 7 deletions client/node_modules/@material-ui/core/package.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions client/node_modules/@types/react/node_modules/csstype/README.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

589 changes: 330 additions & 259 deletions client/node_modules/@types/react/node_modules/csstype/index.d.ts

Large diffs are not rendered by default.

107 changes: 42 additions & 65 deletions client/node_modules/@types/react/node_modules/csstype/index.js.flow

Large diffs are not rendered by default.

30 changes: 15 additions & 15 deletions client/node_modules/@types/react/node_modules/csstype/package.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.11.2",
"@testing-library/jest-dom": "^5.11.6",
"@testing-library/react": "^11.2.2",
"@testing-library/user-event": "^12.6.0",
Expand Down
3 changes: 2 additions & 1 deletion client/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import LockList from './components/lock/LockList';
import LockCreate from './components/lock/LockCreate';
import BuildingList from './components/building/BuildingList';
import BuildingCreate from './components/building/BuildingCreate';
import Dashboard from './components/dashboard';


const isAdmin=permissions=>{
Expand All @@ -36,7 +37,7 @@ function App() {
</p>
}
return (
<Admin dataProvider={restProvider(serverAdress)} locale="en" authProvider={authProvider}>
<Admin dataProvider={restProvider(serverAdress)} dashboard={Dashboard} locale="en" authProvider={authProvider}>
{permissions=>[
<Resource icon={LocationCity} name="building" list={BuildingList} create={BuildingCreate}/>,
<Resource icon={Lock} name="lock" list={LockList} create={LockCreate} options={{label: 'Locks'}}/>,
Expand Down
17 changes: 12 additions & 5 deletions client/src/components/dashboard/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import { Card, CardContent, CardHeader, Typography } from '@material-ui/core'
import React from 'react'

const index = () => {
const Dashboard = (props) => {
console.log(props)
return (
<div>
<h1>hey</h1>
</div>
<Card>
<CardHeader title="Dashboard"/>
<CardContent>
<Typography>

</Typography>
</CardContent>
</Card>
)
}

export default index
export default Dashboard
8 changes: 5 additions & 3 deletions src/controllers/readerController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Key } from "../entity/Key";
import getList from "../util/getList";
import dateToUnix from "../util/dateToUnix";
import { ReaderKey } from "../entity/ReaderKey";
import { updateDeviceKeys } from "../services/deviceService";



Expand Down Expand Up @@ -96,8 +97,9 @@ export async function editReaderKeys(req: Request, res: Response) {
return res.status(400).send({error: "invalid request an array readerKeys is required"})
}

updateDeviceKeys(readerId, body.readerKeys);
// there has to be a better option then deleting all the relationships before adding new but this should do for now
getRepository(ReaderKey)
await getRepository(ReaderKey)
.createQueryBuilder()
.delete()
.from(ReaderKey)
Expand All @@ -106,7 +108,7 @@ export async function editReaderKeys(req: Request, res: Response) {

// check if reader with that ip exists
const readerRepo=getRepository(Reader)
const readerResult = await readerRepo.findOne(readerId, {relations: ["readerKeys"]})
const readerResult = await readerRepo.findOne(readerId, {relations: ["readerKeys", "readerKeys.key"]})

if (!readerResult) throw "no door found"

Expand All @@ -120,7 +122,7 @@ export async function editReaderKeys(req: Request, res: Response) {
readerResult.acctype5Name=body.acctype5Name || "";
readerResult.acctype6Name=body.acctype6Name || "";

readerResult.readerKeys=body.readerKeys;
readerResult.readerKeys=[...body.readerKeys];

await readerRepo.save(readerResult)

Expand Down
2 changes: 1 addition & 1 deletion src/entity/Key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class Key {
isOneTimeCode: boolean


@OneToMany(()=>ReaderKey, readerKey=>readerKey.key, { onDelete: 'CASCADE', onUpdate: 'CASCADE' })
@OneToMany(()=>ReaderKey, readerKey=>readerKey.key, { /* onDelete: 'CASCADE', onUpdate: 'CASCADE', */ cascade: true })
readerKeys: ReaderKey[];

@ManyToOne(()=>User, user=>user.keys, { onDelete: 'CASCADE', onUpdate: 'CASCADE' })
Expand Down
2 changes: 1 addition & 1 deletion src/entity/Reader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export class Reader {
newKeys: NewKey[];


@OneToMany(()=>ReaderKey, readerKey=>readerKey.reader, { onDelete: 'CASCADE', onUpdate: 'CASCADE' })
@OneToMany(()=>ReaderKey, readerKey=>readerKey.reader, { /* onDelete: 'CASCADE', onUpdate: 'CASCADE', */cascade: true })
readerKeys: ReaderKey[];


Expand Down
2 changes: 1 addition & 1 deletion src/entity/ReaderKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class ReaderKey {

@PrimaryColumn()
readerId: number;
@ManyToOne(() => Reader, reader => reader.readerKeys, {primary: true})
@ManyToOne(() => Reader, reader => reader.readerKeys, {primary: true, persistence: false})
@JoinColumn({name: "readerId", referencedColumnName: "id"})
reader: Reader;

Expand Down
4 changes: 2 additions & 2 deletions src/mqtt/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ async function handleHeartBeat(messageJSON) {
/* if there already is a reader with that name and ip update it */
foundReader.lastPing=lastPingDateTime;
await readerRepo.save(foundReader);
console.log("updated reader");
//console.log("updated reader");
//console.log(result)
}else {
/* otherwise create a new one */
Expand All @@ -80,7 +80,7 @@ async function handleHeartBeat(messageJSON) {
readerName: door
});
await readerRepo.save(reader)
console.log("created new reader")
//console.log("created new reader")
}

} catch (error) {
Expand Down
110 changes: 110 additions & 0 deletions src/services/deviceService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { getRepository } from "typeorm";
import { deleteKey } from "../controllers/keyController";
import { Reader } from "../entity/Reader";
import { ReaderKey } from "../entity/ReaderKey";
import { client } from "../mqtt/connection";
import arrayDifference from "../util/arrayDifference";


export async function updateDeviceKeys(readerId, keys: ReaderKey[]){
const readerResult = await getRepository(Reader).findOne(readerId, {relations: ["readerKeys", "readerKeys.key"]})

const addedKeys=arrayDifference(keys, readerResult.readerKeys, (a, b)=>{
return a?.key?.uid===b?.key?.uid;
}) // items that are in array 1 but not in 2

const removedKeys=arrayDifference(readerResult.readerKeys, keys, (a, b)=>{
return a.keyId===b.keyId;
}) // items that are in array 2 but not in 1

console.log(`keys added`)
console.log(addedKeys);
console.log("keys removed");
console.log(removedKeys);


// delete all keys that were just removed from the DB from the device too
try {
await deleteDeviceKeys(readerResult, removedKeys);
} catch (error) {
console.log(error)
}

}

export function deleteDeviceKeys(reader: Reader, keys: ReaderKey[]): Promise<void>{
return new Promise((resolve, reject)=>{

const deleteUser=(readerKey: ReaderKey)=>{
if(client.connected && readerKey && readerKey.key){
client.publish('devnfc', JSON.stringify({
cmd: "deletuid",
doorip: reader.ip,
doorname: reader.readerName,
uid: readerKey.key.uid
}));
}else {
cleanupAndReject();
}
}
const cleanup=()=>{
clearTimeout(mqttTimeout);
client.off("message", mqttMessageHandler)

}

const cleanupAndResolve=()=>{
cleanup();
resolve();

}
const cleanupAndReject=()=>{
cleanup();
reject();
}

if(!keys.length){ // if there are no keys just resolve
resolve();
}

let mqttTimeout;
const mqttMaxResponseTime: number=4000; // give the device max 4 seconds between messages and otherwise return


const mqttMessageHandler=(topic: string, message: Buffer)=> {
if(topic==="devnfc/devicestate" || topic==="/devnfc/devicestate"){
const messageString = message.toString()
const messageJSON = JSON.parse(messageString)
if(messageJSON.deviceName===reader.readerName){ // make sure message comes from the same controller
if(messageJSON.cmd==="deleteUserState"){
if(keys.length){ // after the delete is comfirmed by the device try to remove the key from the array
const keyIndex=keys.findIndex(item=>item.key.uid===messageJSON.deletedUID); // check if array has key with same uid
if(keyIndex!==-1){ // if key was found remove it
keys.splice(keyIndex, 1);
clearTimeout(mqttTimeout); // only after successfully removing a key restart the early return timer
mqttTimeout=setTimeout(cleanupAndReject, mqttMaxResponseTime);
}

}
// filtering might have failed to we check again if there are keys left
if(keys.length>0){
// if there are still keys left to delete send the next request
deleteUser(keys[0]);
}else {
// otherwise we are done
cleanupAndResolve();
}
console.log(messageJSON);
}
}
}
}

client.on("message", mqttMessageHandler)

deleteUser(keys[0]);

mqttTimeout=setTimeout(cleanupAndReject, mqttMaxResponseTime)
})

}
Loading

0 comments on commit 8936e1c

Please sign in to comment.