<|start_filename|>senz-client-samples/java/Image_Utils.java<|end_filename|>
import java.io.*;
import java.util.*;

public class Image_Utils {
  private static String encodedFile = null;
  
  public String imageToString(String filePath) {
    File file = new File(filePath);
    try {
      FileInputStream fis = new FileInputStream(file);
      byte[] bytes = new byte[(int)file.length()];
      fis.read(bytes);
      encodedFile = Base64.getEncoder().encodeToString(bytes);
      fis.close();
    }
    catch(FileNotFoundException e) {
      e.printStackTrace();
    }
    catch(IOException e) {
      e.printStackTrace();
    }

    return encodedFile;
  }

  public void stringToImage(String encodedFile, String filePath) {
    byte[] bytes = Base64.getDecoder().decode(encodedFile);
    
    try {
      OutputStream stream = new FileOutputStream(filePath);
      stream.write(bytes);
      stream.close();
    }
    catch(Exception e) {
			System.out.println(e);
    }
	}
}


<|start_filename|>senz-web/frontend/src/components/layout/Search.js<|end_filename|>
import React from "react";
import { withStyles } from "@material-ui/core/styles";
import _, { debounce } from 'lodash';
import { connect } from "react-redux";
import { Redirect, Link } from 'react-router-dom'
import PropTypes from "prop-types";
import FormControl from '@material-ui/core/FormControl';
import FilledInput from '@material-ui/core/FilledInput';
import SnackbarContent from '@material-ui/core/SnackbarContent';
import Chip from '@material-ui/core/Chip';
import { setProjectAction } from '../../_actions/project'

const styles = theme => ({
    search: {
        width: '40vw',
        height: '3rem',
        marginLeft: '5vw'
    },
    list: {
        position: 'absolute',
        marginLeft: '5vw',
        width: '40vw',
        marginTop: '0.5rem',
    },
    project: {
        marginBottom: '0.05rem',
        background: '#00a8cc',
        color: 'black'
    },
    device: {
        marginBottom: '0.05rem',
        background: '#18b0b0',
        color: 'black'
    }
});

class Search extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            originalArray: [],
            filtered: [],
            showlist: false
        }
        this.handleChange = this.handleChange.bind(this);
    }
    componentDidMount() {
        document.addEventListener('mousedown', this.handleClickOutside);
    }

    componentWillUnmount() {
        document.removeEventListener('mousedown', this.handleClickOutside);
    }

    handleChange(e) {
        this.setState({
            showlist: true,
        })
        // Variable to hold the original version of the list
        let currentList = [];
        // Variable to hold the filtered list before putting into state
        let newList = [];
        // If the search bar isn't empty
        if (e.target.value !== "") {
            // Assign the original list to currentList
            currentList = this.state.originalArray

            // Use .filter() to determine which items should be displayed
            // based on the search terms
            newList = currentList.filter(item => {
                // change current item to lowercase
                const lc = item.name.toLowerCase();
                // change search term to lowercase
                const filter = e.target.value.toLowerCase();
                // check to see if the current list item includes the search term
                // If it does, it will be added to newList. Using lowercase eliminates
                // issues with capitalization in search terms and search content
                return lc.includes(filter);
            });
        } else {
            // If the search bar is empty, set newList to original task list
            newList = this.state.originalArray;
            this.setState({
                showlist: false,
            })
        }
        // Set the filtered state based on what our rules added to newList
        this.setState({
            filtered: newList
        });
    }
    componentWillReceiveProps(nextProps) {
        const devices = nextProps.devices.map(function (e) {
            var obj = Object.assign({}, e);
            obj.type = "device";
            return obj;
        })
        const projects = nextProps.projects.map(function (e) {
            var obj = Object.assign({}, e);
            obj.type = "project";
            return obj;
        })
        this.setState({
            originalArray: [...projects, ...devices]
        });
    }

    setWrapperRef = (node) => {
        this.wrapperRef = node;
    }

    /**
     * Alert if clicked on outside of element
     */
    handleClickOutside = (event) => {
        if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
            this.setState({
                showlist: false
            })
        }
    }

    render() {
        const { classes } = this.props;
        const list = this.state.filtered
        const { token } = this.props.user
        return (
            <div ref={this.setWrapperRef}>
                <FormControl fullWidth variant="filled" className={classes.search}>
                    <FilledInput
                        id="outlined-adornment-amount"
                        value={this.state.query}
                        onChange={this.handleChange}
                        placeholder="Search by project or device"
                    />
                </FormControl>
                {
                    this.state.showlist ? <div className={classes.list}>
                        {
                            list.map((item) =>
                                item.type === 'project' ?
                                    <SnackbarContent
                                        message={
                                            item.name
                                        }
                                        onClick={() => {
                                            this.props.setProjectAction(item._id, token);
                                            return window.location.href = process.env.API_HOST + process.env.REACT_APP_PORT + `/home`
                                        }}
                                        className={classes.project}
                                        action={<Chip label={item.type} />}
                                    >

                                    </SnackbarContent> :
                                    <SnackbarContent
                                        message={
                                            item.name
                                        }
                                        onClick={() => {
                                            return window.location.href = process.env.API_HOST + process.env.REACT_APP_PORT + `/allDevice`
                                        }}
                                        className={classes.device}
                                        action={<Chip label={item.type} />}
                                    >
                                    </SnackbarContent>

                            )
                        }
                    </div> : null}
            </div>
        )
    }
}
const styledSearch = withStyles(styles, { withTheme: true })(Search);

Search.propTypes = {
    projects: PropTypes.array,
    devices: PropTypes.array,
    user: PropTypes.array
};

export default connect(
    null,
    { setProjectAction }
)(styledSearch);




<|start_filename|>senz-web/frontend/src/components/project/Settings/Form.js<|end_filename|>
import React, { Component } from "react";
import {
  Container,
  Paper,
  TextField,
  Button,
  Typography,
  Divider,
  CssBaseline,
  Switch,
  FormGroup,
  FormControlLabel,
  Grid,
  Dialog,
  DialogActions,
  DialogTitle
} from "@material-ui/core";
import {
  updateProjectInfoAction,
  addDeviceToProjectAction,
  deleteProjectAction,
  switchProjectStatus
} from "../../../_actions/project";
import { withStyles } from "@material-ui/core/styles";
import ReactLoading from 'react-loading';
import { connect } from "react-redux";
import { reduxForm, Field } from "redux-form";
import Notifier from "../../Notifier";

const IOSSwitch = withStyles(theme => ({
  root: {
    width: 42,
    height: 26,
    padding: 0,
    margin: theme.spacing(1)
  },
  switchBase: {
    padding: 1,
    "&$checked": {
      transform: "translateX(16px)",
      color: theme.palette.common.white,
      "& + $track": {
        backgroundColor: "#2196F3",
        opacity: 1,
        border: "none"
      }
    },
    "&$focusVisible $thumb": {
      color: "#2196F3",
      border: "6px solid #fff"
    }
  },
  thumb: {
    width: 24,
    height: 24
  },
  track: {
    borderRadius: 26 / 2,
    border: `1px solid ${theme.palette.grey[400]}`,
    backgroundColor: theme.palette.grey[50],
    opacity: 1,
    transition: theme.transitions.create(["background-color", "border"])
  },
  loader: {
    marginLeft: "42%"
  },
  checked: {},
  focusVisible: {}
}))(({ classes, ...props }) => {
  return (
    <Switch
      focusVisibleClassName={classes.focusVisible}
      disableRipple
      classes={{
        root: classes.root,
        switchBase: classes.switchBase,
        thumb: classes.thumb,
        track: classes.track,
        checked: classes.checked
      }}
      {...props}
    />
  );
});

const styles = theme => ({
  main: {},
  subSection: {
    padding: 20
  },
  subHead: {
    border: "1px solid #9e9e9e",
    padding: 15,
    justifyContent: "space-between"
  },
  subHeadDelete: {
    border: "1px solid red",
    padding: 15,
    justifyContent: "space-between"
  }
});

class Form extends Component {
  state = {
    checkedB: true,
    name: this.props.project.name,
    description: this.props.project.description,
    added: false,
    updated: false,
    switch: false,
    openModal: false
  };

  openModal = () => {
    this.setState({ openModal: true });
  };

  handleClose = name => event => {
    this.setState({ [name]: false });
  };
  handleChange = name => event => {
    this.props.project.status = !this.props.project.status;
    this.props.switchProjectStatus(
      this.props.project._id,
      this.props.project.status,
      this.props.user.token
    );
    this.setState({ switch: true });
  };
  handleChangeInfo = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };
  handleClickInfo = () => {
    const { name, description } = this.state;
    this.setState({ updated: true });
    this.props.updateProjectInfoAction(
      this.props.project._id,
      this.props.user.token,
      name,
      description
    );
  };
  renderInputError = ({ error, touched, active }) => {
    if (error && touched) return { error: true, message: error };
    if (error && active) return { error: true, message: error };
    else return { error: false, message: "" };
  };
  renderPublicKeyInput = ({ input, label, variant, margin, type, meta }) => {
    const { error, message } = this.renderInputError(meta);
    if (error) {
      return (
        <TextField
          {...input}
          label={message}
          variant={variant}
          margin={margin}
          type={type}
          error
        />
      );
    } else {
      return (
        <TextField
          {...input}
          label={label}
          variant={variant}
          margin={margin}
          required
          type={type}
        />
      );
    }
  };
  handlePubKeySubmit = ({ pubkey }) => {
    this.props.addDeviceToProjectAction(
      this.props.project._id,
      this.props.user.token,
      pubkey
    );
    this.setState({ added: true });
  };
  handleDelete = () => {
    const { project, user } = this.props;
    this.props.deleteProjectAction(project._id, user.id, user.token);
  };
  render() {
    const { classes } = this.props;
    return (
      <Container>
        <CssBaseline />
        <Paper>
          <div className={classes.main} data-test="ProjectDetailSection">
            <div className={classes.subSection}>
              <Typography variant="h6">Project Details</Typography>
              <Divider />
              <div className={classes.subHead}>
                {this.props.updateloading ?
                  <ReactLoading type={'spinningBubbles'} color={'black'} height={40} width={40} className={classes.loader} />
                  :
                  <>
                    <TextField
                      name="name"
                      variant="outlined"
                      label="Name"
                      margin="normal"
                      value={this.state.name}
                      onChange={this.handleChangeInfo}
                    />
                    <TextField
                      name="description"
                      variant="outlined"
                      label="Description"
                      margin="normal"
                      value={this.state.description}
                      onChange={this.handleChangeInfo}
                      fullWidth
                    />
                    <br />
                    <Button
                      color="primary"
                      variant="outlined"
                      onClick={this.handleClickInfo}
                      disabled={this.state.updated}
                    >
                      Update
                </Button>
                  </>}
              </div>
            </div>
            <div className={classes.subSection}>
              <Typography variant="h6">Devices Detail</Typography>
              <Divider />
              <div className={classes.subHead}>
                <form
                  onSubmit={this.props.handleSubmit(this.handlePubKeySubmit)}
                >
                  <Field
                    name="pubkey"
                    variant="outlined"
                    label="Public Key"
                    margin="normal"
                    component={this.renderPublicKeyInput}
                    type="text"
                  />
                  <br />

                  <Button
                    color="primary"
                    disabled={this.state.added}
                    variant="outlined"
                    type="submit"
                  >
                    Add Device
                  </Button>
                </form>
              </div>
            </div>
            <div className={classes.subSection}>
              <Typography variant="h6">Danger Zone</Typography>
              <Divider />
              <div
                className={classes.subHeadDelete}
                data-test="ProjectSettingsSection"
              >
                <Typography variant="body1">Project Switch</Typography>
                {this.props.switchloading?
                 <ReactLoading type={'spinningBubbles'} color={'black'} height={40} width={40} className={classes.loader} />
                 :
                <FormGroup>
                  <Grid
                    component="label"
                    container
                    alignItems="center"
                    spacing={1}
                  >
                    <Grid item>Off</Grid>
                    <Grid item>
                      <FormControlLabel
                        control={
                          <IOSSwitch
                            checked={this.props.project.status}
                            onChange={this.handleChange("checkedB")}
                            value="checkedB"
                          />
                        }
                      />
                    </Grid>
                    <Grid item>On</Grid>
                  </Grid>
                </FormGroup>}
                <Button
                  size="small"
                  color="secondary"
                  variant="outlined"
                  onClick={this.openModal}
                >
                  Delete Project
                </Button>
              </div>
            </div>
          </div>
        </Paper>
        <Notifier
          message="Device Added"
          done={this.state.added}
          handleClose={this.handleClose("added")}
        />
        <Notifier
          message="Details Updated"
          done={this.state.updated}
          handleClose={this.handleClose("updated")}
        />
        <Notifier
          message="Project Switched"
          done={this.state.switch}
          handleClose={this.handleClose("switch")}
        />
        
        {/* modal to ask for delete confimation from user*/}
        <Dialog
        open={this.state.openModal}
        onClose={this.handleClose}
        aria-labelledby="responsive-dialog-title"
      >
        <DialogTitle>
            Are you sure you want to delete this project?
          </DialogTitle>
        <DialogActions>
          <Button autoFocus onClick={this.handleClose("openModal")} 
            color="primary">
            Cancel
          </Button>
          <Button onClick={this.handleDelete} color="secondary" autoFocus>
            Delete
          </Button>
        </DialogActions>
      </Dialog>
      </Container>
    );
  }
}

const MapStateToProp = state => {
  return {
    project: state.project.SelectedProject,
    devices: state.device.AllDevices,
    user: state.auth.user,
    updateloading: state.project.loading,
    switchloading:state.project.switchloading
  };
};
const validate = ({ pubkey }, props) => {
  const errors = {};
  const projectDevices = props.project.devices.map(device => {
    return device.pubkey;
  });
  const allDeviceKey = props.devices.map(device => {
    return device.pubkey;
  });
  if (projectDevices.indexOf(pubkey) !== -1) errors.pubkey = "Already Added";
  if (allDeviceKey.indexOf(pubkey) === -1) errors.pubkey = "Not found";
  return errors;
};

const updatedComponent = reduxForm({
  form: "addDevice",
  validate: validate
})(withStyles(styles, { withTheme: true })(Form));

export default connect(
  MapStateToProp,
  {
    updateProjectInfoAction,
    addDeviceToProjectAction,
    deleteProjectAction,
    switchProjectStatus
  }
)(updatedComponent);


<|start_filename|>senz-client-samples/java/Sender.java<|end_filename|>
import java.util.Scanner;

public class Sender {
  static String deviceName = "dev1";
  static String sharedKey =  "<KEY>";
  static String imagePathToSend = "sample.jpg";

  public static void main(String args[]) {
    Client client = new Client();
    Image_Utils imageUtils = new Image_Utils();
    AES_Utils aesUtils;
    Scanner sc = new Scanner(System.in);

    // Register device
    System.out.println("Registering device...");
    String msg = "SHARE #pubkey key @senz #time "+client.getTimeStamp()+" ^"+deviceName+" signature";
    client.sendMessage(msg);

    // Convert image to byte string
    String byteString = imageUtils.imageToString(imagePathToSend);

    // Encrypt using AES Crypto
    aesUtils = new AES_Utils(sharedKey);
    byteString = aesUtils.encrypt(byteString);

    // Send the message
    System.out.println("Press enter to send the image...");
    sc.nextLine();

    msg = "DATA $image " + byteString +" @dev2 #time " + client.getTimeStamp() + " ^dev1 signature";
    client.sendMessage(msg);

    // Unregister device
    System.out.println("Unregistering device...");
    msg = "UNSHARE #pubkey key @senz #time " + client.getTimeStamp() +" ^"+ deviceName +" signature";
    client.sendMessage(msg);
    sc.close();
  }
}


<|start_filename|>senz-client-samples/react-native/sender/components/sender.js<|end_filename|>
import React, { Component } from "react";
import { View, TextInput, Button } from "react-native";
import io from 'socket.io-client';

const styles = StyleSheet.create({
  button: { 
    margin: 5, 
    padding: 5 
  }
});

class Send extends Component {
  state = {
    receiverDeviceId: "",
    message: ""
  };
  componentDidMount(){
    console.log('sender client')
    this.socket = io('http://61000127.ngrok.io');
    this.socket.on("connect", () => {
      console.log("sender connected: ",this.socket.connected);
    });
  }
  onDeviceIdChange = value => {
    this.setState({ 
      receiverDeviceId: value 
    });
  };
  onMessageChange = value => {
    this.setState({ 
      message: value 
    });
  };
  sendMessage =()=>{
    const { deviceId:senderDeviceId, publicKey:senderPublicKey, signature } = this.props.route.params;
    const messageData = {senderDeviceId,signature,senderPublicKey,receiverDeviceId:this.state.receiverDeviceId,message:this.state.message}
    this.socket.emit("send data", messageData);
  }
  render() {
    return (
      <View>
        <View>
          <TextInput
            autoCapitalize="none"
            placeholder="Receivers Device Id"
            value={this.state.receiverDeviceId}
            onChangeText={text => {
              this.onDeviceIdChange(text);
            }}
          />
          <TextInput
            autoCapitalize="none"
            placeholder="Message"
            value={this.state.message}
            onChangeText={text => {
              this.onMessageChange(text);
            }}
          />
        </View>
        <View style={styles.button}>
          <Button title="Send" onPress={()=>this.sendMessage()} />
        </View>
      </View>
    );
  }
}

export default Send;

<|start_filename|>senz-web/frontend/src/__tests__/authReducers.test.js<|end_filename|>
import { AUTHENTICATED, UNAUTHENTICATED } from "../_actions/types/index";
import authReducers from "../_reducers/authReducers";
describe("Authentication Reducers", () => {
  it("Should return the default state", () => {
    const newState = authReducers(undefined, {});
    expect(newState).toEqual({});
  });
  it("Should authenticate the user", () => {
    const mockPayload = { name: "Test" };
    const newState = authReducers(undefined, {
      type: AUTHENTICATED,
      payload: mockPayload
    });
    expect(newState).toEqual({ authenticated: true, user: mockPayload, loading:false });
  });
  it("Should unauthenticate the user", () => {
    const newState = authReducers(undefined, {
      type: UNAUTHENTICATED
    });
    expect(newState).toEqual({ user: {}, authenticated: false, loading:false });
  });
});


<|start_filename|>senz-client-samples/react-native/sender/components/main.js<|end_filename|>
import React, {Component} from 'react'
import {View, TextInput, Button} from 'react-native';

const styles = StyleSheet.create({
  button: { 
    margin: 5, 
    padding: 5 
  }
});

class Main extends Component {
  state = {
    deviceId: "",
    signature: "",
    publicKey: ""
  };
  onDeviceIdChange = value => {
    this.setState({ deviceId: value });
  };
  onSignatureChange = value => {
    this.setState({ signature: value });
  };
  onPublicKeyChange = value => {
    this.setState({ publicKey: value });
  };
  render() {
    return (
      <View>
        <View>
          <TextInput
            autoCapitalize="none"
            placeholder="Sender device Id"
            value={this.state.deviceId}
            onChangeText={text => {
              this.onDeviceIdChange(text);
            }}
          />
          <TextInput
            autoCapitalize="none"
            placeholder="Sender public key"
            value={this.state.publicKey}
            onChangeText={text => {
              this.onPublicKeyChange(text);
            }}
          />
          <TextInput
            autoCapitalize="none"
            placeholder="signature"
            value={this.state.signature}
            onChangeText={text => {
              this.onSignatureChange(text);
            }}
          />
        </View>
        <View style={styles.button}>
          <Button
            title="Send"
            onPress={() =>
              this.props.navigation.navigate("Send", {deviceId: this.state.deviceId,signature: this.state.signature,publicKey: this.state.publicKey})
            }
          />
        </View>
      </View>
    );
  }
}

export default Main;

<|start_filename|>senz-client-samples/java/AES_Utils.java<|end_filename|>
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AES_Utils {

  private static SecretKeySpec secretKey;
  private static int bs;

  public AES_Utils(String myKey) {
    MessageDigest sha = null;
    bs = 32;
    try {
      byte[] key = myKey.getBytes("UTF-8");
      sha = MessageDigest.getInstance("SHA-256");
      key = sha.digest(key);
      key = Arrays.copyOf(key, 16);
      secretKey = new SecretKeySpec(key, "AES");
    }
    catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
  }

  public static String pad(String str) {
    String res="";
    int num = bs-str.length()%bs;
    for(int i=0;i<num;i++) {
      res+=(char)num;
    }
    return str+res;
  }

  public static String unpad(String str) {
    int len = str.length();
    return str.substring(0, len-(int)str.charAt(len-1));
  }

  public String encrypt(String strToEncrypt) {
    try {
      strToEncrypt = pad(strToEncrypt);
      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.ENCRYPT_MODE, secretKey);
      return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
    }
    catch (Exception e) {
      System.out.println("Error while encrypting: " + e.toString());
    }
    return null;
  }

  public String decrypt(String strToDecrypt) {
    try {
      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.DECRYPT_MODE, secretKey);
      return unpad(new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))));
    }
    catch (Exception e) {
      System.out.println("Error while decrypting: " + e.toString());
    }
    return null;
  }
}


<|start_filename|>senz-client-samples/java/Receiver.java<|end_filename|>
public class Receiver {
  static String deviceName = "dev2";
  static String sharedKey = "<KEY>";
  static String imagePathToStore = "received.jpg";

  public static void main(String args[]) {
    Client client = new Client();
    Image_Utils imageUtils = new Image_Utils();
    AES_Utils aesUtils;

    // Register device
    System.out.println("Registering...");
    String msg = "SHARE #pubkey key @senz #time "+client.getTimeStamp()+" ^"+deviceName+" signature";
    client.sendMessage(msg);

    // Receive message
    System.out.println("Ready to receive image");
    String reply = client.receiveMessage();
    String byteString = reply.split(" ")[2];
    System.out.println("Image received...");

    // Decode using aes crypto
    aesUtils = new AES_Utils(sharedKey);
    byteString = aesUtils.decrypt(byteString);

    // Save Image
    imageUtils.stringToImage(byteString, imagePathToStore);
    System.out.printf("Image saved (%s)\n", imagePathToStore);

    // Unregister device
    System.out.println("Unregistering...");
    msg = "UNSHARE #pubkey key @senz #time "+client.getTimeStamp()+" ^"+deviceName+" signature";
    client.sendMessage(msg);
  }
}


<|start_filename|>senz-client-samples/react-native/backend/sender.js<|end_filename|>
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io").listen(server);
const port = 3003;
const {registeringSender} = require("./senderController");



io.on("connection", socket=>{
  console.log("sender server connected");
  socket.on("send data",  msg => {
    registeringSender(msg);
  });
});

server.listen(port, 
  function(){console.log("sender server running on port "+ port)});

<|start_filename|>senz-web/frontend/src/_reducers/deviceReducers.js<|end_filename|>
import {
  ADD_DEVICE,
  EDIT_DEVICE,
  FETCH_DEVICES,
  REMOVE_PROJECT_DEVICE,
  REMOVE_DEVICES,
  SWITCH_DEVICE,
  CLEAR_ALL,
  TOGGLE_IS_EDITING_DEVICE,
  ADD_DEVICE_ERROR,
  ADD_DEVICE_REQUEST,
  FETCH_DEVICES_REQUEST,
  SWITCH_DEVICES_REQUEST,
  REMOVE_DEVICE_FROM_PROJECT_REQUEST
} from "../_actions/types";

export const deviceReducers = (
  state = { AllDevices: [], SelectedDevice: {}, isEditingDevice: false, loading: false },
  action
) => {
  switch (action.type) {
    case ADD_DEVICE:
      return {
        ...state,
        AllDevices: [...state.AllDevices, action.payload],
        SelectedDevice: state.SelectedDevice,
        loading: false
      };
    case EDIT_DEVICE: {
      return {
        ...state,
        AllDevices: action.payload,
        SelectedDevice: {}
      };
    };
    case ADD_DEVICE_ERROR:
      return { ...state, error: action.payload };
    case ADD_DEVICE_REQUEST:
      return { ...state, loading: true }
    case FETCH_DEVICES:
      return {
        ...state,
        AllDevices: action.payload,
        SelectedDevice: state.SelectedDevice,
        loading: false
      };
    case FETCH_DEVICES_REQUEST:
      return { ...state, loading: true }
    case CLEAR_ALL:
      return {
        ...state,
        AllDevices: [],
        SelectedDevice: {},
        loading: false
      };
    case REMOVE_PROJECT_DEVICE:
      const modifiedDevices = state.AllDevices.map(device => {
        if (action.payload.devices.includes(device._id)) {
          device.projects = device.projects.filter(projectId => {
            return projectId !== action.payload.projectId;
          });
        }
        return device;
      });
      return {
        ...state,
        AllDevices: modifiedDevices,
        SelectedDevice: state.SelectedDevice,
        loading: false
      };
    case REMOVE_DEVICES: {
      const devices = action.payload;
      const modDevices = state.AllDevices.filter(device => {
        return !devices.includes(device._id);
      });
      return {
        ...state,
        AllDevices: modDevices,
        SelectedDevice: {},
      };
    }
    case REMOVE_DEVICE_FROM_PROJECT_REQUEST:
      return { ...state, loading: true }
    case SWITCH_DEVICE:
      const switchedDevices = state.AllDevices.map(device => {
        if (action.payload._id === device._id) {
          device = action.payload;
        }
        return device;
      });
      return {
        ...state,
        AllDevices: switchedDevices,
        SelectedDevice: {},
        loading: false
      };
    case TOGGLE_IS_EDITING_DEVICE: {
      const toggleValue = action.payload;
      return { ...state, isEditingDevice: toggleValue };
    }
    case SWITCH_DEVICES_REQUEST:
      return { ...state, loading: true }
    default:
      return state;
  }
};


<|start_filename|>senz-web/frontend/src/components/project/Devices/Devices.js<|end_filename|>
import React, { Component } from "react";
import Intro from "../Intro";
import DevicesList from "./DevicesList";
import { Grid, Container, Button } from "@material-ui/core";
import { withStyles } from "@material-ui/core/styles";
import { connect } from "react-redux";
import ReactLoading from 'react-loading';
import { toggleHeadingAction } from "../../../_actions/heading";
import { removeProjectDevices } from "../../../_actions/project";

const useStyles = theme => ({
  loader: {
    marginLeft: "42%"
  }
})

class Devices extends Component {
  state = {
    done: false,
    devices: [] //This should have id of devices to be removed
  };
  componentWillMount = () => {
    this.props.toggleHeadingAction({ heading: "Devices" });
  };
  handleCheck = id => {
    var remDevices = [];
    if (this.state.devices.includes(id)) {
      remDevices = this.state.devices.filter(stateId => {
        return id !== stateId;
      });
      this.setState({ devices: remDevices });
    } else {
      remDevices = [...this.state.devices, id];
      this.setState({ devices: remDevices });
    }
  };
  handleRemove = () => {
    this.props.removeProjectDevices(
      this.props.project._id,
      this.state.devices,
      this.props.user.token
    );
  };
  render() {
    const { classes } = this.props;
    return (
      <div>
        <Grid item xs={12}>
          <Intro
            heading="Devices"
            description="This contains the list of devices contained in the selected project. You can select multiple devices and can remove them from the project."
          />
        </Grid>
        {
          this.props.devicesLoading ?
        <ReactLoading type={'spinningBubbles'} color={'black'} height={40} width={40} className={classes.loader}/>
            : 
        <Container maxWidth="lg">
          <Grid container spacing={1}>
            <Grid item xs={6}>
              <Button
                variant="outlined"
                color="secondary"
                onClick={this.handleRemove}
              >
                Remove
              </Button>
            </Grid>
            <Grid item xs={12} style={{ padding: 30 }}>
              <DevicesList handleCheck={this.handleCheck} />
            </Grid>
          </Grid>
        </Container>
        }
      </div>
    );
  }
}

const MapStateToProp = state => {
  return {
    devices: state.project.SelectedProject.devices,
    project: state.project.SelectedProject,
    user: state.auth.user,
    devicesLoading: state.device.loading
  };
};

export default connect(
  MapStateToProp,
  { toggleHeadingAction, removeProjectDevices }
)(withStyles(useStyles, { withTheme: true })(Devices));


<|start_filename|>senz-client-samples/java/Client.java<|end_filename|>
import java.net.*;
import java.io.*;
import java.time.*;
import java.time.format.DateTimeFormatter;

public class Client {
  private Socket socket = null;
  private PrintWriter out = null;
  
  public Client() {
    try {
      socket = new Socket("localhost", 2552);
    }
    catch(UnknownHostException e)
		{
			System.out.println(e);
		}
		catch(IOException e)
		{
			System.out.println(e);
		}
  }

  public String getTimeStamp() {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");  
		LocalDateTime now = LocalDateTime.now();
    return dtf.format(now);
  }

  public String receiveMessage() {
    try {
      InputStreamReader isr = new InputStreamReader(socket.getInputStream());
      BufferedReader br = new BufferedReader(isr);
      return br.readLine();
    }
    catch(Exception e) {
      System.out.println(e);
      return null;
    }
  }

  public void sendMessage(String message) {
    try {
      out = new PrintWriter(socket.getOutputStream());
      byte bytes[] = message.getBytes();
      String msg = new String(bytes, "UTF-8");
      out.print(msg);
      out.flush();
      String res = receiveMessage();
      System.out.println("Server: "+res);
    }
    catch(Exception e) {
      System.out.println(e);
    }
  }
}


<|start_filename|>senz-client-samples/react-native/backend/receiverController.js<|end_filename|>
const net = require("net");
const socket = new net.Socket();
const AESUtils = require("./AESutils");
const logger = require('./winstonConfig')
const sharedKey = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
const aes = new AESUtils(sharedKey);  


socket.connect(2552, "localhost", () => {
  console.log(`Receiver Connected to the server on port ${2552}`);
});
const time = Date.now();

const sendMessage = function(msg) {
  return new Promise(function(resolve) {
    socket.write(msg);
    socket.on("data", function(data) {
      data = data.toString("utf8");
      resolve(data);
    });
    socket.on("error", function(e) {
      console.log(`Error Message: ${e}`);
    });
  });
};

const getResponse = function () {
  return new Promise(function (resolve) {
    socket.on("data", function (data) {
      data = data.toString("utf8").split(" ")[2];
      let chunk = "";
      for (let i = 0; i < data.length; i++) {
        chunk += data[i];
      }
      resolve(chunk);
    });
  });
};

const receiveMessage = async function () {
  let data = await getResponse();
  return data;
};

const receiveImage = function (messagedata) {
  const { signature, receiverPublicKey, receiverDeviceId } = messagedata;
  const data = receiveMessage().then(function (encImg) {
    const decrptedBase64 = aes.decrypt(encImg);
    sendMessage(`UNSHARE #pubkey ${receiverPublicKey} @senz #time ${time} ^${receiverDeviceId} ${signature}`).then(function () {
      console.log("receiver unRegistered")
    });
    return decrptedBase64;
  });
  return  data;
};

const registerReceiver = function(messagedata) {
  const { signature, receiverPublicKey, receiverDeviceId } = messagedata;
  var shareQuery = `SHARE #pubkey ${receiverPublicKey} @senz #time ${time} ^${receiverDeviceId} ${signature}`;
  return sendMessage(shareQuery).then(function(shareQuery) {
      console.log("Ready to receive message ");
      return receiveImage(messagedata).then(data => data).catch(err=> {throw err;})
  });
};
module.exports = {registerReceiver};

<|start_filename|>senz-client-samples/react-native/backend/receiver.js<|end_filename|>
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io").listen(server);
const port = 3001;
const {registerReceiver} = require("./receiverController.js");


io.on("connection", socket=>{
  console.log("receiver server connected");
  socket.on("receive data",async msg => {
    registerReceiver(msg).then(data =>{
      io.emit('receive data', data);
    })
  });
});

server.listen(port,
  function(){console.log("receiver server running on port "+ port)});

<|start_filename|>senz-web/frontend/src/components/devices/DeviceList.js<|end_filename|>
import React, { Component, Fragment } from "react";
import PropTypes from "prop-types";
import clsx from "clsx";
import { withStyles } from "@material-ui/core/styles";
import TableCell from "@material-ui/core/TableCell";
import Paper from "@material-ui/core/Paper";
import EditIcon from '@material-ui/icons/Edit';
import EditDevice from './EditDevice';
import Switch from '@material-ui/core/Switch';
import { AutoSizer, Column, Table } from "react-virtualized";
import { switchDevice } from "../../_actions/device";
import { connect } from "react-redux";
import { toggleIsEditingDevice } from "../../_actions/device";
import { toggleHeadingAction } from "../../_actions/heading";
import ReactLoading from 'react-loading';

const styles = theme => ({
  flexContainer: {
    display: "flex",
    alignItems: "center",
    boxSizing: "border-box"
  },
  tableRow: {
    cursor: "pointer"
  },
  tableRowHover: {
    "&:hover": {
      backgroundColor: theme.palette.grey[200]
    }
  },
  tableCell: {
    flex: 1
  },
  noClick: {
    cursor: "initial"
  },
  header: {
    backgroundColor: "#23344e",
    color: "#fafafa"
  },
  selectedRow: {
    backgroundColor: "#a2d8f5"
  }
});

class MuiVirtualizedTable extends React.PureComponent {
  static defaultProps = {
    headerHeight: 48,
    rowHeight: 48
  };
  state = {
    devices: [],
    status: [],
  };
  componentDidMount() {
    // console.log(this.props);
    const status = this.props.devices.map((device)=> {
      return device.status;
    })
    this.setState({ status });
  }
  getRowClassName = ({ index }) => {
    const { classes, onRowClick } = this.props;

    return clsx(classes.tableRow, classes.flexContainer, {
      [classes.tableRowHover]: index !== -1 && onRowClick != null,
      [classes.selectedRow]: this.state.devices.includes(index)
    });
  };
  handleChange = (event) => {
    const newStatus = this.state.status.map((val, index) => {
      return event.target.value === index ? !val : val
    })
    this.setState({
      status: newStatus
    })
    const status = this.state.status[event.target.value] ? true : false;
    this.props.switchDevice(event.target.name, !status, this.props.user.token);
  };
  cellRenderer = ({ cellData, columnIndex, rowData }) => {
    const deviceIndex = this.props.devices.map(a => a._id)
    const { columns, classes, rowHeight, onRowClick } = this.props;
    return (
      <TableCell
        component="div"
        className={clsx(classes.tableCell, classes.flexContainer, {
          [classes.noClick]: onRowClick == null
        })}
        variant="body"
        style={{ height: rowHeight }}
        align={
          (columnIndex != null && columns[columnIndex].numeric) || false
            ? "right"
            : "left"
        }
      >
        {columnIndex === 5 ? <Switch
          checked={cellData}
          name={rowData._id}
          onChange={this.handleChange}
          value={deviceIndex.indexOf(rowData._id)}
          inputProps={{ 'aria-label': 'secondary checkbox' }}
          color="primary"
        /> : <span>{cellData}</span>}
      </TableCell>
    );
  };

  headerRenderer = ({ label, columnIndex }) => {
    const { headerHeight, columns, classes } = this.props;

    return (
      <TableCell
        component="div"
        className={clsx(
          classes.tableCell,
          classes.flexContainer,
          classes.noClick,
          classes.header
        )}
        variant="head"
        style={{ height: headerHeight }}
        align={columns[columnIndex].numeric || false ? "right" : "left"}
      >
        <span>{label}</span>
      </TableCell>
    );
  };
  render() {
    const { classes, columns, ...tableProps } = this.props;
    return (
      <AutoSizer>
        {({ height, width }) => (
          <Table
            height={height}
            width={width}
            {...tableProps}
            rowClassName={this.getRowClassName}
          >
            {columns.map(({ dataKey, ...other }, index) => {
              return (
                <Column
                  key={dataKey}
                  headerRenderer={headerProps =>
                    this.headerRenderer({
                      ...headerProps,
                      columnIndex: index
                    })
                  }
                  className={classes.flexContainer}
                  cellRenderer={this.cellRenderer}
                  dataKey={dataKey}
                  {...other}
                />
              );
            })}
          </Table>
        )}
      </AutoSizer>
    );
  }
}

MuiVirtualizedTable.propTypes = {
  classes: PropTypes.object.isRequired,
  columns: PropTypes.arrayOf(PropTypes.object).isRequired,
  headerHeight: PropTypes.number,
  onRowClick: PropTypes.func,
  rowHeight: PropTypes.number,
  devicestatus: PropTypes.array,
  user: PropTypes.object,
  devices: PropTypes.array,
  switchDevice: PropTypes.func
};

const VirtualizedTable = withStyles(styles)(MuiVirtualizedTable);

class ReactVirtualizedTable extends Component {
  state = {
    deviceId: null,
    name: null,
    pubkey: null
  }
  async componentDidMount() {
    this.props.toggleIsEditingDevice(false);
    this.props.toggleHeadingAction({ heading: "All Devices" });
  }
  onEditIconClick = async (event, device) => {
    event.stopPropagation();
    const { _id, name, pubkey } = device;
    await this.setState({ deviceId: _id, name, pubkey });
    this.props.toggleIsEditingDevice(true);
  }
  render() {
    const rows = this.props.devices.map(device => {
      const editIcon = <EditIcon onClick={(event) => this.onEditIconClick(event, device)} />
      if (device.status)
        return { ...device, date: device.date.substr(0, 10), active: true, edit: editIcon };
      else return { ...device, date: device.date.substr(0, 10), active: false, edit: editIcon };
    });
    if (rows.length === 0) return null;
    return (<Fragment>
      {
          this.props.isEditingDevice ?
        <EditDevice
            name={this.state.name}
            pubkey={this.state.pubkey}
            deviceId={this.state.deviceId}
          />
          :
          <>
            {
              this.props.switchloading ?
                <ReactLoading type={'spinningBubbles'} color={'black'} height={40} width={40} />
                :
                <Paper
                  style={{ height: 400, width: 800 }}
                  data-test="DeviceListComponent"
                >
                  <VirtualizedTable
                    rowCount={rows.length}
                    rowGetter={({ index }) => rows[index]}
                    handleCheck={this.props.handleCheck}
                    data-test="TableComponent"
                    devices={this.props.devices}
                    user={this.props.user}
                    switchDevice={this.props.switchDevice}
                    columns={[
                      {
                        width: 150,
                        label: "Name",
                        dataKey: "name"
                      },
                      {
                        width: 150,
                        label: "Number of Sents",
                        dataKey: "sent",
                        numeric: true
                      },
                      {
                        width: 150,
                        label: "Number of Receives",
                        dataKey: "received",
                        numeric: true
                      },
                      {
                        width: 200,
                        label: "Public Key",
                        dataKey: "pubkey",
                        numeric: true
                      },
                      {
                        width: 200,
                        label: "Created On",
                        dataKey: "date"
                      },
                      {
                        width: 100,
                        label: "Status",
                        dataKey: "active"
                      },
                      {
                        width: 50,
                        dataKey: "edit"
                      }
                    ]}
                  />
                </Paper>
            }
          </>
      }
    </Fragment>);
  }
}

const MapStateToProp = state => {
  return {
    devices: state.device.AllDevices,
    isEditingDevice: state.device.isEditingDevice,
    switchloading: state.device.loading,
    user: state.auth.user
  };
};
export default connect(MapStateToProp, { toggleIsEditingDevice, toggleHeadingAction, switchDevice })(ReactVirtualizedTable);


<|start_filename|>senz-web/frontend/src/_actions/types/index.js<|end_filename|>
export const NAV_HEADING = "NAV_HEADING";
export const AUTHENTICATED = "authenticated_user";
export const AUTHENTICATION_REQUEST = 'authentication_request'
export const UNAUTHENTICATED = "unauthenticated_user";
export const LOGOUT_REQUEST = "logout_request"
export const AUTHENTICATION_ERROR = "authentication_error";
export const PASSWORD_RESETTED = "password_<PASSWORD>";
export const PASSWORD_RESET_ERROR = "password_reset_error";
export const RESET_PASSWORD_TOKEN_VERIFIED = "reset_password_token_verified";
export const RESET_PASSWORD_TOKEN_VERIFICATION_ERROR = "reset_password_token_verification_error";
export const PASSWORD_UPDATED = "<PASSWORD>";
export const PASSWORD_UPDATION_ERROR = "password_updation_error";
export const UPDATE_REQUEST = "update_user";
export const ADD_PROJECT = "add_project";
export const ADD_PROJECT_ERROR = "add_project_error";
export const FETCH_PROJECTS = "fetch_projects";
export const SET_PROJECT = "set_project";
export const DELETE_PROJECT = "delete_project";
export const UPDATE_PROJECT_INFO = "update_project_info";
export const ADD_DEVICE_PROJECT = "add_device_to_project";
export const HANDLE_SWITCH = "handle_switch";
export const REMOVE_DEVICE_PROJECT = "remove_device_project";
export const REMOVE_PROJECT_DEVICE = "remove_project_device";
export const UPDATE_USER = "update_user_info";
export const ADD_DEVICE = "add_device";
export const EDIT_DEVICE = "edit_device";
export const TOGGLE_IS_EDITING_DEVICE = "toggle_is_editing_device";
export const REMOVE_DEVICES = "remove_devices";
export const ADD_DEVICE_ERROR = "add_device_error";
export const ADD_DEVICE_REQUEST = "add_device_request"
export const FETCH_DEVICES = "fetch_devices";
export const FETCH_DEVICES_REQUEST = "fetch_devices_request"
export const SWITCH_DEVICE = "switch_device";
export const SWITCH_DEVICES_REQUEST = "switch_device_request"
export const CLEAR_ALL = "clear_all";
export const FETCH_LOG_PROJECT = "fetch_log_project";
export const FETCH_ALL_LOG = "fetch_all_log";
export const FETCH_PROJECT_REQUEST = "fetch_project_request";
export const SWITCH_PROJECT_REQUEST = "switch_project_request";
export const REMOVE_DEVICE_FROM_PROJECT_REQUEST = "remove_device_from_project_request";
export const ADD_PROJECT_REQUEST = "add_project_request";
export const DELETE_PROJECT_REQUEST = "delete_project_request";
export const UPDATE_PROJECT_REQUEST = "update_project_request";
export const SET_PROJECT_REQUEST = "set_project_request"
export const ADD_DEVICE_TO_PROJECT_REQUEST = "add_device_to_project_request"


<|start_filename|>senz-web/frontend/src/_actions/device.js<|end_filename|>
import {
  ADD_DEVICE,
  ADD_DEVICE_ERROR,
  ADD_DEVICE_REQUEST,
  EDIT_DEVICE,
  FETCH_DEVICES,
  FETCH_DEVICES_REQUEST,
  SWITCH_DEVICE,
  SWITCH_DEVICES_REQUEST,
  REMOVE_DEVICES,
  TOGGLE_IS_EDITING_DEVICE
} from "./types/index";

import axios from "axios";

const URL = "http://localhost:8080/device";

export const addDeviceAction = (name, pubkey, token, userId) => {
  return async dispatch => {
    dispatch(request())
    try {
      const response = await axios.post(
        `${URL}/${userId}/new`,
        {
          name,
          pubkey
        },
        {
          headers: {
            Authorization: token
          }
        }
      );
      dispatch({ type: ADD_DEVICE, payload: response.data });
    }
    catch (err) {
      dispatch({
        type: ADD_DEVICE_ERROR,
        payload: "Invalid"
      });
    }
  }
  function request() {
    return { type: ADD_DEVICE_REQUEST }
  }
};

//Edit device action
export const editDeviceAction = (name, pubkey, deviceId, token, userId) => {
  return async dispatch => {
    const response = await axios.put(
      `${URL}/${userId}/edit`,
      {
        name,
        pubkey,
        deviceId
      },
      {
        headers: {
          Authorization: token
        }
      }
    );
    dispatch({ type: EDIT_DEVICE, payload: response.data });
  };
};

//All devices action
export const fetchAllDeviceAction = (userId, token) => {
  return async dispatch => {
    dispatch(request())
    const response = await axios.get(`${URL}/${userId}/all`, {
      headers: {
        Authorization: token
      }
    });
    dispatch({ type: FETCH_DEVICES, payload: response.data });
  };
  function request() {
    return { type: FETCH_DEVICES_REQUEST }
  }
};

//Remove devices from all device menu.
export const removeDevices = (userId, devices, token) => {
  return async dispatch => {
    const response = await axios.delete(`${URL}/${userId}/delete`, {
      headers: {
        Authorization: token
      },
      data: devices
    });
    console.log(response.data);
    dispatch({ type: REMOVE_DEVICES, payload: devices });
  };
};
//Switch device
export const switchDevice = (device, status, token) => {
  return async dispatch => {
    dispatch(request())
    const response = await axios.put(
      `${URL}/switch`,
      {
        device,
        status
      },
      {
        headers: {
          Authorization: token
        }
      }
    );
    dispatch({ type: SWITCH_DEVICE, payload: response.data });
  };
  function request() {
    return { type: SWITCH_DEVICES_REQUEST }
  }
};

export const toggleIsEditingDevice = toggleValue => {
  return { type: TOGGLE_IS_EDITING_DEVICE, payload: toggleValue };
};


<|start_filename|>senz-web/frontend/src/components/layout/NavBar.js<|end_filename|>
import React from "react";
import { withStyles } from "@material-ui/core/styles";
import CssBaseline from "@material-ui/core/CssBaseline";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import Logout from "./Logout";
import { fetchAllDeviceAction } from '../../_actions/device'
import { fetchProjectAction } from '../../_actions/project'
import { connect } from "react-redux";
import NavDropDown from "./NavDropDown";
import Search from './Search'
import PropTypes from "prop-types";

const drawerWidth = 240;

const styles = theme => ({
  root: {
    display: "flex"
  },
  appBar: {
    width: `calc(100% - ${drawerWidth}px)`,
    marginLeft: drawerWidth,
    backgroundColor: "#2196F3"
  },
  logoutButton: {
    marginLeft: "auto",
    marginRight: 25
  },
  navDrop: {
    marginLeft: "auto",
    marginRight: -600
  }
});

class NavBar extends React.Component {
  render() {
    const { classes } = this.props;
    const devices = this.props.devices ? this.props.devices : null
    const projects = this.props.projects ? this.props.projects : null
    const user = this.props.user ? this.props.user : null
    return (
      <div className={classes.root} data-test="NavBarComponent">
        <CssBaseline />
        <AppBar
          position="fixed"
          className={classes.appBar}
          data-test="AppBarComponent"
        >
          <Toolbar>
            <Typography variant="h6" noWrap>
              {this.props.heading}
            </Typography>
            <Search projects={projects} devices={devices} user={user} />
            <div className={classes.navDrop}>
              <NavDropDown />
            </div>
            <div className={classes.logoutButton}>
              <Logout />
            </div>
          </Toolbar>
        </AppBar>
      </div>
    );
  }
}
const styledNavBar = withStyles(styles, { withTheme: true })(NavBar);

const MapStateToProp = state => {
  return {
    heading: state.heading.heading,
    projects: state.project.AllProject,
    devices: state.device.AllDevices,
    user: state.auth.user,
  };
};

NavBar.propTypes = {
  heading: PropTypes.string,
  projects: PropTypes.array,
  devices: PropTypes.array,
  user: PropTypes.array
};

export default connect(
  MapStateToProp,
  { fetchProjectAction, fetchAllDeviceAction }
)(styledNavBar);


<|start_filename|>senz-client-samples/react-native/backend/senderController.js<|end_filename|>
const net = require("net");
const socket = new net.Socket();
const AESUtils = require("./AESutils");
const logger = require('./winstonConfig')

socket.connect(2552, "localhost", function() {
  console.log("Sender Connected to server on port 2552");
});

const time = Date.now();
const sharedKey = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
const aes = new AESUtils(sharedKey);

const sendMessage = function(msg) {
  return new Promise(function(resolve) {
    socket.write(msg);
    socket.on("data", function(data) {
      data = data.toString("utf8");
      resolve(data);
    });
    socket.on("error", function(e) {
      logger.error(`Error Message: ${e}`);
    });
  });
};

const sendingMessage = function(messageData) {
  const {senderDeviceId,senderPublicKey,signature,receiverDeviceId,message} = messageData;
  const encryptedData = aes.encrypt(message);
  const newQuery = `DATA $image ${encryptedData} @${receiverDeviceId} #time ${time} ^${senderDeviceId} ${signature}`;
  sendMessage(newQuery).then(function(senData) {
    console.log(senData);
    sendMessage(
      `UNSHARE #pubkey ${senderPublicKey} @senz #time ${time} ^${senderDeviceId} ${signature}`
    ).then(function(registered) {
      console.log(registered);
    });
  });
};

const registeringDevice = function(messageData) {
   const {senderDeviceId,senderPublicKey,signature,receiverDeviceId,message} = messageData;
   var shareQuery = `SHARE #pubkey ${senderPublicKey} @senz #time ${time} ^${senderDeviceId} ${signature}`;
  sendMessage(shareQuery).then(function(registered) {
    console.log(registered);
  });
  sendingMessage(messageData);
};

module.exports = {registeringSender};