Пример #1
0
void scenesIdFn(WcFnRequestHandler *handler, String requestUri, HTTPMethod method) {
  String sceneId = handler->getWildCard(1);
  LightGroup *scene = findScene(sceneId);
  switch (method) {
    case HTTP_GET:
      if (scene) {
        sendJson(scene->getSceneJson());
      } else {
        sendError(3, "/scenes/"+sceneId, "Cannot retrieve scene that does not exist");
      }
      break;
    case HTTP_PUT:
      // validate body, delete old group, create new group
      sceneCreationHandler(sceneId);
      // XXX not a valid response according to API
      sendUpdated();
      break;
    case HTTP_DELETE:
      if (scene) {
        updateSceneSlot(findSceneIndex(sceneId), sceneId, "");
      } else {
        sendError(3, requestUri, "Cannot delete scene that does not exist");
      }
      sendSuccess(requestUri+" deleted");
      break;
    default:
      sendError(4, requestUri, "Scene method not supported");
      break;
  }
}
Пример #2
0
void ChatUDPSocket::readyRead (){
    QByteArray buffer;
    buffer.resize(mUdpSocket->pendingDatagramSize());

    QHostAddress sender;
    quint16 senderPort;
    mUdpSocket->readDatagram(buffer.data(), buffer.size(), &sender, &senderPort);

    qDebug() << "message from : " << sender.toString();
    qDebug() << "message port : " << senderPort;
    qDebug() << "message : " << buffer;

    QList<QByteArray> packList = buffer.split(':');

    QString pType(packList[0].trimmed().toLower());
    QUuid pUuid(packList[1]);
    QString pContent(packList[2]);

    qDebug() << pType;

    if(pType == "request") { // request message
        QByteArray data;
        data.append("response:");
        data.append(pUuid.toString()).append(":");
        data.append("accepted");
        mUdpSocket->writeDatagram(data, sender, ChatPort);
        mUdpSocket->flush();
        emit receiveSuccess(pContent);
    } else if (pType == "response") { // response message
        if(pContent.trimmed().toLower() == "accepted") {
            emit sendSuccess(pUuid);
        }
    }
}
Пример #3
0
void Dialog::dropEvent(QDropEvent *event)
{
    qDebug() << "drop enter event";
    if (event->mimeData()->hasUrls())
    {
//        //qDebug() << event->mimeData()->urls();
        QMessageBox msgBox;

//        if (m_isInNode)
//        {
//            QString str;
//            Device dev;
//            str = dev.getDetailPropertyContent(DP_IP);
//            //node2Device(m_currentNodeIndex,&dev);
//            msgBox.setText(str);
//            msgBox.exec();


            m_urls = event->mimeData()->urls();

            if (!m_urls.empty())
            {
                QString strFile;
                foreach(QUrl url, m_urls)
                {
                    strFile = url.toLocalFile();
                }

                qint64 iSize = countSize(strFile);
                if (m_bFolder)
                {
                    //mSendFile = new sendfile("192.168.9.15", strFile, m_fileList ,iSize);
                    mSendFile = new sendfile("127.0.0.1", strFile, m_fileList ,m_emptyFolderList, iSize);

                }
                else
                {
                     //mSendFile = new sendfile("192.168.9.15", strFile);
                    mSendFile = new sendfile("127.0.0.1", strFile);
                }

                connect(mSendFile,SIGNAL(sendSuccess()),this,SLOT(onSendSuccess()));
                mSendFile->startThread();
                m_urls.erase(m_urls.begin());
            }
Пример #4
0
void lightsFn(WcFnRequestHandler *handler, String requestUri, HTTPMethod method) {
  switch (method) {
    case HTTP_GET: {
      // dump existing lights
      aJsonObject *lights = aJson.createObject();
      addLightsJson(lights);
      sendJson(lights);
      break;
    }
    case HTTP_POST:
      // "start" a "search" for "new" lights
      sendSuccess("/lights", "Searching for new devices");
      break;
    default:
      sendError(4, requestUri, "Light method not supported");
      break;
  }
}
Пример #5
0
void groupsIdFn(WcFnRequestHandler *handler, String requestUri, HTTPMethod method) {
  String groupNumText = handler->getWildCard(1);
  int groupNum = atoi(groupNumText.c_str()) - 1;
  if ((groupNum == -1 && groupNumText != "0") || groupNum >= 16 || (groupNum >= 0 && !lightGroups[groupNum])) {
    // error, invalid group number
    sendError(3, requestUri, "Invalid group number");
    return;
  }

  switch (method) {
    case HTTP_GET:
      if (groupNum != -1) {
        sendJson(lightGroups[groupNum]->getJson());
      } else {
        aJsonObject *object = aJson.createObject();
        aJson.addStringToObject(object, "name", "0");
        aJsonObject *lightsArray = aJson.createArray();
        aJson.addItemToObject(object, "lights", lightsArray);
        for (int i = 0; i < MAX_LIGHT_HANDLERS; i++) {
          if (!lightHandlers[i]) {
            continue;
          }
          // add light to list
          String lightNum = "";
          lightNum += (i + 1);
          aJson.addItemToArray(lightsArray, aJson.createItem(lightNum.c_str()));
        }
        sendJson(object);
      }
      break;
    case HTTP_PUT:
      // validate body, delete old group, create new group
      updateGroupSlot(groupNum, HTTP->arg("plain"));
      sendUpdated();
      break;
    case HTTP_DELETE:
      updateGroupSlot(groupNum, "");
      sendSuccess(requestUri+" deleted");
      break;
    default:
      sendError(4, requestUri, "Group method not supported");
      break;
  }
}
Пример #6
0
void sceneCreationHandler(String id) {
  int sceneIndex = findSceneIndex(id);
  // handle scene creation
  // find first available scene slot
  if (sceneIndex == -1) {
    // throw error no new scenes allowed
    sendError(301, "scenes", "Scenes table full");
    return;
  }
  // updateSceneSlot sends failure messages
  if (!updateSceneSlot(sceneIndex, id, HTTP->arg("plain"))) {
    if (id == "") {
      id = String(sceneIndex);
    }
    lightScenes[sceneIndex]->id = id;
    sendSuccess("id", id);
    return;
  }
}
Пример #7
0
void groupCreationHandler() {
  // handle group creation
  // find first available group slot
  int availableSlot = -1;
  for (int i = 0; i < 16; i++) {
    if (!lightGroups[i]) {
      availableSlot = i;
      break;
    }
  }
  if (availableSlot == -1) {
    // throw error no new groups allowed
    sendError(301, "groups", "Groups table full");
    return;
  }
  if (!updateGroupSlot(availableSlot, HTTP->arg("plain"))) {
    String slot = "";
    slot += (availableSlot + 1);
    sendSuccess("id", slot);
  }
}
Пример #8
0
void ChatService::listen(){
    connect(mUdpService, SIGNAL(receiveError(QString)), this, SIGNAL(receiveError(QString)));
    connect(mUdpService, SIGNAL(receiveSuccess(QHostAddress,quint16,ChatMessage)), this, SIGNAL(receiveSuccess(QHostAddress,quint16,ChatMessage)));
    connect(mUdpService, SIGNAL(sendError(QUuid,QString)), this, SIGNAL(sendError(QUuid,QString)));
    connect(mUdpService, SIGNAL(sendSuccess(QUuid)), this, SIGNAL(sendSuccess(QUuid)));
}
Пример #9
0
void *processConn(int connfd){
  char *buf=NULL,*holder;
  int offset = 0;
  char *file;
  ssize_t rcount;
  /*
    "getp" is where in the "Working buffer" the "GET" string is found. 
    Case sensitive.
    "http" is where in the "Working buffer" the "HTTP/1.1" string is found. 
    Case insensitive.
    "host" is where in the "Working buffer" the "HOST" string is found.
    Case insensitive.
    "eomp" is where in the "Holding buffer" the "\r\n\r\n" string is found.
   */
  char *getp=NULL, *http=NULL, *host=NULL, *eomp=NULL, *ptr;
  
  int i = 0;
  int *filesize=&i;
  FILE *fp=NULL;
  
  /* Holder is the "Holding buffer" where the input from the connection
     is read into until the end of message "\r\n\r\n" is found. 
  */
  holder = (char*) malloc(sizeof(char)*(512+1));
  holder = memset(holder,'\0',512);
  
 read:
  /* While the connection has more to give, or when the connection has
     nothing left to give but the "Holding buffer" still has content. 
     Offset is the current offset into the "Holding Buffer" after every read.
  */
  while(((rcount = read(connfd,holder+offset,512))>0)||((rcount==0)&&(strlen(holder)>0))){
    offset = offset + rcount;
    /* Null terminate what we have just read in */
    *(holder+offset)='\0';
#ifdef SERVER_DEBUG
    fprintf(stderr,"Characters Read: %zu\n",rcount);
    fprintf(stderr,"Holding Buffer: %s\n",holder);
#endif
    eomp = strcasestr(holder,"\r\n\r\n");
    if(eomp!=NULL){ 
      /*
	We have found a finished header! Move this into the "Working Buffer". 
	The "Working Buffer" is "buf".
      */
      *eomp='\0';
      buf = (char *) malloc(eomp-holder);
      buf = memcpy(buf,holder,eomp-holder);
      /*
	Slide the rest of the "Holding Buffer" after where the end of the header
	was found to the beginning of the header with the null terminator still on
	the end.
      */
      *holder='\0';
      holder = memmove(holder,(eomp+4), (holder+offset)-(eomp+3));
      offset = strlen(holder);
#ifdef SERVER_DEBUG
      fprintf(stderr,"FOUND HEADER\n------------\nBUFFER: %s\nHOLDER: %s\nOFFSET: %d\n\n",buf,holder,offset);
#endif
      break;
    }
    /* 
       if nothing was read, but the "Holding Buffer" still had contents and the 
       "Holding Buffer" did not contain the end of message then send a bad
       request.
    */
    else if(rcount==0) goto badReq;
    /*
      End of message has not yet been found, expand the buffer and continue trying
      to read.
     */
    holder = realloc(holder,(strlen(holder)+513)*sizeof(char));
  }
  /*
    Connection was established and then closed, so no read. Close the connection
  */
  if(buf==NULL) goto end;
  
  /*
    Check if the required contents are present
  */
  getp = strstr(buf,"GET");
  http = strcasestr(buf,"HTTP/1.1");
  host = strcasestr(buf,"Host:");
  
  /*
    Get the current working directory and add on the requested file name
   */
  file=malloc(sizeof(char)*180);
  if((file=getcwd(file,180)) != NULL){
#ifdef SERVER_DEBUG
    fprintf(stdout,"CWD: %s:%zu\n",file,strlen(file));
#endif
  }
  if((file=realloc(file,(strlen(file)+(http-(getp+4))*sizeof(char))))!=NULL){
    *(--http)='\0';
    file=strcat(file,(getp+4));
  }
  
#ifdef SERVER_DEBUG
  fprintf(stdout,"BUF: %s\n",buf);
  fprintf(stdout,"GETP:%c HTTP:%c HOST:%c EOMP:%c\n",*getp,*http,*host,*eomp);
  fprintf(stdout,"FILE:%s :%zu\n",file,strlen(file));
#endif
  
  /* If this is a valid start line */
  if(getp!=NULL&&http!=NULL&&host!=NULL){

    fp = getFile(host+6,file,filesize);
    
    if(fp==NULL){
      /* File does not exist */
      if(send404(connfd)==-1) perror("Unable to send 404");
    }
    else{
      /* File exists, attempt to send it and then close the file */
      if((ptr=strstr(file,".htm"))!=NULL){
	if(!sendSuccess(connfd,fp,"text/html",filesize)){
	  fprintf(stderr,"Failed to send %s\n",file);
	}
	fclose(fp);
      }
      else if ((ptr=strstr(file,".txt"))!=NULL){
	if(!sendSuccess(connfd,fp,"text/plain",filesize)){
	  fprintf(stderr,"Failed to send %s\n",file);
	}
	fclose(fp);
      }
      else if ((ptr=strstr(file,".jpeg"))||(ptr=strstr(file,".jpg"))!=NULL){
	if(!sendSuccess(connfd,fp,"image/jpeg",filesize)){
	  fprintf(stderr,"Failed to send %s\n",file);
	}
	fclose(fp);
      }
      else if ((ptr=strstr(file,".gif"))!=NULL){
	if(!sendSuccess(connfd,fp,"image/gif",filesize)){
	  fprintf(stderr,"Failed to send %s\n",file);
	}
	fclose(fp);
      }
      else{
	if(!sendSuccess(connfd,fp,"application/octet-stream",filesize)){
	  fprintf(stderr,"Failed to send %s\n",file);
	}
	fclose(fp);
      }
    }
  } 
  else{
  badReq:
    if(send400(connfd)==-1) perror("Failed to send 404");
    goto end;
  }
  free(file);
  free(buf);
  file = buf = NULL;
  /* If there is still contents in the "Holding Buffer" */
  if(strlen(holder)!=0) goto read;
 end:
  close(connfd);
#ifdef SERVER_DEBUG
  printf("Connection Closed\n");
#endif
  return NULL;
}
Пример #10
0
void recethread::run()
{  
    if (m_iFolder == 0)
    {
        //udt = new CUDT();
        //connect(udt,SIGNAL(sendProgress(qint64,qint64)),this,SLOT(onSendProgress(qint64,qint64)));

       // get size information

        int iContent = 3;
        char content[iContent+1];
        if (UDT::ERROR == UDT::recv(m_handle, content, iContent, 0))
        {
           qDebug() << "recv: " << UDT::getlasterror().getErrorMessage() << endl;
           return ;
        }
        else
        {
              qDebug()<< "receive file or directory request success";
             content[iContent] = '\0';

            char *strContent = new char[iContent+1];
            memset(strContent,0,iContent+1);
            memcpy(strContent, content, iContent);

            if (0 == strcmp(strContent, "FCS"))
            {
                qDebug() << "receive FCS";
            }
            else
            {
                return;
            }

        }


         if (UDT::ERROR == UDT::recv(m_handle, (char*)&size, sizeof(uint64_t), 0))
         {
             qDebug() << "handle: " << m_handle;
             qDebug() << "send: " << UDT::getlasterror().getErrorMessage() << endl;
             //qDebug() << "receive file size success";
             return;
         }

         if (size < 0)
         {
            return;
         }

         qDebug() << "receive file size : " << size;


        std::fstream ofs(m_strFileName.toStdString().c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
        int64_t recvsize;
        int64_t offset = 0;

        CUDT *udt = CUDT::getUdt(m_handle);
        udt->setFolderSize(size);
        connect(udt,SIGNAL(sendProgress(qint64,double)),this,SLOT(onSendProgress(qint64,double)));

        if (UDT::ERROR == (recvsize = udt->recvfile(ofs, offset, size)))
        {
            QString str = UDT::getlasterror().getErrorMessage();
            //cout << "recvfile: " << UDT::getlasterror().getErrorMessage() << endl;
            //return -1;
        }

        emit sendSuccess();

        UDT::close(m_handle);

        ofs.close();
    }
Пример #11
0
void
CClientProxyUnknown::handleReady(const CEvent&, void*)
{
	sendSuccess();
}
Пример #12
0
void authFn(WcFnRequestHandler *handler, String requestUri, HTTPMethod method) {
  // On the real bridge, the link button on the bridge must have been recently pressed for the command to execute successfully.
  // We try to execute successfully regardless of a button for now.
  sendSuccess("username", "api");
}
Пример #13
0
ChatForm::ChatForm(User *receiver, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ChatForm),
    receiver(receiver),
    sender(UserService::getService()->getMyself()),
    mChatRecords(ChatRecordService::getService()->getChatRecordsByUserUuid(receiver->getUuid(), ChatRecord::NotRead)),
    mIconService(IconService::getService()),
    mScreenshotsWidget(new ScreenshotsWidget)
{
    ui->setupUi(this);

    /* recent friends */
    UserService::getService()->insertRecentFriend(*receiver);
    /* end of recent friends */

    setAttribute(Qt::WA_DeleteOnClose);
    this->mChatService = ChatService::getService();
    this->mFileMsgService = FileMessageService::getService();

    ui->userIcon->setIcon(this->receiver->getIcon());
    ui->userIcon->setIconSize(QSize(40, 40));

    ui->usernameLabel->setText(this->receiver->getName());
    ui->signatrueLabel->setText(this->receiver->getInfo());

    setStyleSheet("#ChatForm {background-color:#ffdbf8}");

    connect(mChatService, SIGNAL(receiveSuccess(QHostAddress,quint16,ChatMessage)), this, SLOT(receiveSuccess(QHostAddress,quint16,ChatMessage)));
    connect(mChatService, SIGNAL(sendError(QUuid, QString)), this, SLOT(sendError(QUuid, QString)));
    connect(mChatService, SIGNAL(sendSuccess(QUuid)), this, SLOT(sendSuccess(QUuid)));
    connect(mFileMsgService, SIGNAL(received(QHostAddress,quint16,ChatMessage)), this, SLOT(fileMsgReceived(QHostAddress,quint16,ChatMessage)));

    updateChatRecordView();
    loadSetting();

    sendFileModel = new QStandardItemModel;
    receiveFileModel = new QStandardItemModel;

    QStringList heads;
    heads << "filename" << "progress" << "size" << "type" << "url" << "uuid";
    sendFileModel->setHorizontalHeaderLabels(heads);
    receiveFileModel->setHorizontalHeaderLabels(heads);

    ui->sendFileTableView->setModel(sendFileModel);
    ui->receiveFileTableView->setModel(receiveFileModel);

    mFileSender = 0;
    mFileReceiver = 0;
    mFileMessage = 0;

    fileSendRow = 0;
    fileReceiveRow = 0;

    mShakeTimer = new QTimer(this);
    mShakeTimer->setInterval(30);
    mShakePosition = 0;
    shakeMaxLimitTimes = 12;
    shakeMaxLimitSpace = 5;
    connect(mShakeTimer, SIGNAL(timeout()),this, SLOT(shakeTimeOut()));

    connect(mScreenshotsWidget, SIGNAL(finishPixmap(QPixmap)), this, SLOT(screenshotsFinish(QPixmap)));

    connect(&mFacesDialog, SIGNAL(clicked(Image)), this, SLOT(facesClicked(Image)));
}
Пример #14
0
//  Loop the client thread here
void *wallyClientThread(void *argPtr){
   slog(DEBUG,DEBUG,"WallyClient Thread started. Waiting for plugins to get ready.");
   pthread_mutex_init(&commandMutex,0);
   while(ph->pluginLoaderDone == false){
      usleep(100);
   }
   slog(DEBUG,FULLDEBUG,"WallyClient Thread started. Plugins ready.");
   commandMap = malloc(sizeof(hash_table));
   ht_init(commandMap, HT_KEY_CONST | HT_VALUE_CONST, 0.05);
   tempMap = malloc(sizeof(hash_table));
   ht_init(tempMap, HT_KEY_CONST | HT_VALUE_CONST, 0.05);

   int startDelay = 1;
   int ret=0;
   char *startDelayString = NULL;

   clientThreadRunning = true;

   while(clientThreadRunning == true) {
       switch(clientState)
           {
              case DISCOVERY:
                  //ssdpDiscovery(1);
                  //    Both plugins (ssdp and cloudConnector) 
                  //    set ph->location and return once they registered
                  //    Cloud connector needs additional handling after
                asprintf(&startDelayString,"%d",startDelay);
                if(ph->ssdp) {
                      call("ssdp::discovery",&ret,startDelayString);
                } else if(ph->cloud) {
                      call("cloud::connect",&ret,startDelayString);
                }
                free(startDelayString);
                if(ph->location) {
                     if(run_callback){
                        slog(DEBUG,DEBUG,"Executing JS Callback for client discovery");
#ifndef WITH_SEADUK
                        duv_push_ref(ctx, finishCallback);
                        duk_push_string(ctx, ph->location);
                        duk_call(ctx, 1);
                        duk_to_int(ctx, -1);
#endif
                     }
                     saveLocation(FLAGFILE);
                  }
                  startDelay = 1;
                  slog(DEBUG,DEBUG,"Change state from discovery to register");
                  clientState = REGISTER;
                  break;
              case REGISTER:
                  if(ph->location){
                     if(registerClient(ph->location)){
                        slog(DEBUG,DEBUG,"Starting longpoll."); 
                        url_longpoll(commandURL,60,LONGPOLL_INIT,NULL);
                        clientState = COMMAND;
                     } else {
                        slog(DEBUG,DEBUG,"Registration failed."); 
                     }
                  } else {
                     slog(LVL_INFO,WARN,"Register was called without a valid location");
                  }
                  break;
              case COMMAND:
                  slog(DEBUG,DEBUG,"Requesting next core command from %s",commandURL);
                  int ret = getCommand(commandURL,60);
                  if(ret == true && ht_get_simple(commandMap,"command")){
                     int commandValid = false;
                     slog(DEBUG,DEBUG,"Command : %s",ht_get_simple(commandMap,"command"));
                     // Handle the commands which are supported by the wallyd here
                     if(ht_compare(commandMap,"command","config")){
                           commandValid = true;
                           slog(DEBUG,DEBUG,"Preparing to persist config");
                           if(persistConfig(registerMap)){
                              sendSuccess(ht_get_simple(commandMap,"id"));
                           }
                     }
                     if(ht_compare(commandMap,"command","reboot")){
                           commandValid = true;
                           sendSuccess(ht_get_simple(commandMap,"id"));
                           slog(DEBUG,DEBUG,"Preparing to reboot");
                           system(BIN_REBOOT);
                     }
                     if(ht_compare(commandMap,"command","firmwareUpdate")){
                           commandValid = true;
                           sendSuccess(ht_get_simple(commandMap,"id"));
                           slog(DEBUG,DEBUG,"Preparing to update firmware");
                           system(BIN_UPDATEFW);
                     }
                     if(ht_compare(commandMap,"command","getlog")){
                           commandValid = true;
                           slog(DEBUG,DEBUG,"Preparing to send log to server");
                           //sendSuccess(ht_get_simple(commandMap,"id"));
                           //persistConfig(registerMap);
                     }
                     if(commandValid == false){
                           slog(DEBUG,DEBUG,"Command %s not valid. Ingoring.",ht_get_simple(commandMap,"command"));
                           sendFailed(ht_get_simple(commandMap,"id"),"unknown.command");
                     }
                  } else {
                     slog(LVL_INFO,WARN,"getCommand failed.");
                  }
                  pthread_mutex_unlock(&commandMutex);
                  break;
              case QUIT:
                  slog(DEBUG,DEBUG,"Thread is quiting.");
                  break;
           }
       sleep(threadDelay);
   }
   return 0;
}