Added CSV on linux, mac, windows

This commit is contained in:
Liran Ben gida 2014-09-08 18:54:52 +03:00
parent 4fa27283d9
commit 235354210b
31 changed files with 2811 additions and 2712 deletions

View file

@ -1,61 +1,61 @@
#-------------------------------------------------
#
# Project created by QtCreator 2014-05-31T19:49:42
#
#-------------------------------------------------
QT += core gui network widgets
TARGET = jceGrade
TEMPLATE = app
RC_FILE = appConfigure.rc
CONFIG += qt c++11
CONFIG += console
FORMS += \
main/mainscreen.ui
OTHER_FILES +=
RESOURCES += \
resources/connectionstatus.qrc
HEADERS += \
main/CalendarTab/CalendarManager.h \
main/CourseTab/coursestablemanager.h \
main/LoginTab/loginhandler.h \
main/mainscreen.h \
src/appDatabase/savedata.h \
src/jceConnection/jcesslclient.h \
src/jceData/Calendar/calendarPage.h \
src/jceData/Grades/gradeCourse.h \
src/jceData/Grades/gradePage.h \
src/jceData/course.h \
src/jceData/page.h \
src/jceSettings/jcelogin.h \
src/jceSettings/jceLoginHtmlScripts.h \
src/jceSettings/user.h \
src/jceData/Calendar/calendarCourse.h \
src/jceData/Calendar/calendarSchedule.h \
src/jceData/CSV/csv_exporter.h \
src/appDatabase/simplecrypt.h
SOURCES += \
main/CalendarTab/CalendarManager.cpp \
main/CourseTab/coursestablemanager.cpp \
main/LoginTab/loginhandler.cpp \
main/main.cpp \
main/mainscreen.cpp \
src/appDatabase/savedata.cpp \
src/jceConnection/jcesslclient.cpp \
src/jceData/Calendar/calendarPage.cpp \
src/jceData/Grades/gradeCourse.cpp \
src/jceData/Grades/gradePage.cpp \
src/jceData/page.cpp \
src/jceSettings/jcelogin.cpp \
src/jceSettings/user.cpp \
src/jceData/Calendar/calendarCourse.cpp \
src/jceData/Calendar/calendarSchedule.cpp \
src/jceData/CSV/csv_exporter.cpp \
src/appDatabase/simplecrypt.cpp
#-------------------------------------------------
#
# Project created by QtCreator 2014-05-31T19:49:42
#
#-------------------------------------------------
QT += core gui network widgets
TARGET = jceGrade
TEMPLATE = app
RC_FILE = appConfigure.rc
CONFIG += qt c++11
CONFIG += console
FORMS += \
main/mainscreen.ui
OTHER_FILES +=
RESOURCES += \
resources/connectionstatus.qrc
HEADERS += \
main/CalendarTab/CalendarManager.h \
main/CourseTab/coursestablemanager.h \
main/LoginTab/loginhandler.h \
main/mainscreen.h \
src/appDatabase/savedata.h \
src/jceConnection/jcesslclient.h \
src/jceData/Calendar/calendarPage.h \
src/jceData/Grades/gradeCourse.h \
src/jceData/Grades/gradePage.h \
src/jceData/course.h \
src/jceData/page.h \
src/jceSettings/jcelogin.h \
src/jceSettings/jceLoginHtmlScripts.h \
src/jceSettings/user.h \
src/jceData/Calendar/calendarCourse.h \
src/jceData/Calendar/calendarSchedule.h \
src/jceData/CSV/csv_exporter.h \
src/appDatabase/simplecrypt.h
SOURCES += \
main/CalendarTab/CalendarManager.cpp \
main/CourseTab/coursestablemanager.cpp \
main/LoginTab/loginhandler.cpp \
main/main.cpp \
main/mainscreen.cpp \
src/appDatabase/savedata.cpp \
src/jceConnection/jcesslclient.cpp \
src/jceData/Calendar/calendarPage.cpp \
src/jceData/Grades/gradeCourse.cpp \
src/jceData/Grades/gradePage.cpp \
src/jceData/page.cpp \
src/jceSettings/jcelogin.cpp \
src/jceSettings/user.cpp \
src/jceData/Calendar/calendarCourse.cpp \
src/jceData/Calendar/calendarSchedule.cpp \
src/jceData/CSV/csv_exporter.cpp \
src/appDatabase/simplecrypt.cpp

View file

@ -1,16 +1,30 @@
#include "CalendarManager.h"
CalendarManager::CalendarManager(calendarSchedule *ptr)
{
this->caliSchedPtr = ptr;
}
void CalendarManager::setCalendar(std::string html)
{
caliSchedPtr->setPage(html);
}
calendarSchedule *CalendarManager::getSch()
{
return this->caliSchedPtr;
}
#include "CalendarManager.h"
CalendarManager::CalendarManager(calendarSchedule *ptr)
{
this->caliSchedPtr = ptr;
}
void CalendarManager::setCalendar(std::string html)
{
caliSchedPtr->setPage(html);
}
void CalendarManager::exportCalendarCSV()
{
if(CSV_Exporter::exportCalendar(this->caliSchedPtr))
{
QMessageBox msgBox;
msgBox.setText("<center>Exported Successfuly!<br><b>HaazZaA!!");
msgBox.exec();
}else
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("<center>Something went wrong...<br></center>Maybe: <ul><li>You Canceled</li><li>Unable to save the File - try again</li></ul><br><br>"
"<b><center>In case of a serious problem, please file a bug report.<br>thank you. OpenJCE teem");
msgBox.exec();
}
}

View file

@ -1,24 +1,26 @@
#ifndef CALENDARMANAGER_H
#define CALENDARMANAGER_H
#include "./src/jceData/Calendar/calendarPage.h"
#include "./src/jceData/Calendar/calendarSchedule.h"
#include <iostream>
class CalendarManager
{
public:
CalendarManager(calendarSchedule *ptr);
~CalendarManager()
{
delete caliSchedPtr;
}
void setCalendar(std::string html);
void resetTable() { if (caliSchedPtr != NULL) caliSchedPtr->clearTableItems(); }
calendarSchedule* getSch();
private:
calendarSchedule * caliSchedPtr;
};
#endif // CALENDARMANAGER_H
#ifndef CALENDARMANAGER_H
#define CALENDARMANAGER_H
#include "./src/jceData/Calendar/calendarPage.h"
#include "./src/jceData/Calendar/calendarSchedule.h"
#include "./src/jceData/CSV/csv_exporter.h"
#include <iostream>
#include <QMessageBox>
class CalendarManager
{
public:
CalendarManager(calendarSchedule *ptr);
~CalendarManager()
{
delete caliSchedPtr;
}
void exportCalendarCSV();
void setCalendar(std::string html);
void resetTable() { if (caliSchedPtr != NULL) caliSchedPtr->clearTableItems(); }
private:
calendarSchedule * caliSchedPtr;
};
#endif // CALENDARMANAGER_H

View file

@ -1,251 +1,251 @@
#include "coursestablemanager.h"
coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr)
{
this->gp = NULL;
this->us = usrPtr;
this->courseTBL = ptr;
/*
* Initilizing Table
*/
courseTBL->setRowCount(0);
courseTBL->setColumnCount(COURSE_FIELDS);
QStringList mz;
mz << QObject::tr("Code") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions");
courseTBL->setHorizontalHeaderLabels(mz);
courseTBL->verticalHeader()->setVisible(true);
courseTBL->setSelectionMode(QAbstractItemView::SingleSelection);
courseTBL->setShowGrid(true);
courseTBL->setStyleSheet("QTableView {selection-background-color: red;}");
}
coursesTableManager::~coursesTableManager()
{
courseTBL = NULL;
delete gp;
gp = NULL;
}
/**
* @brief coursesTableManager::insertJceCoursesIntoTable phrasing the course list to rows in table
*/
void coursesTableManager::insertJceCoursesIntoTable()
{
for (gradeCourse *c: *gp->getCourses())
{
if (us->getInfluenceCourseOnly())
{
if (isCourseInfluence(c))
addRow(c);
}
else
addRow(c);
}
}
/**
* @brief coursesTableManager::setCoursesList creating courses list with given html page
* @param html
*/
void coursesTableManager::setCoursesList(std::string &html)
{
gp = new GradePage(html);
}
/**
* @brief coursesTableManager::changes when user changes the table manually it updates it
* @param change string change
* @param row row index
* @param col col index
* @return if change has been done
*/
bool coursesTableManager::changes(QString change, int row, int col)
{
bool isNumFlag = true;
int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt();
for (gradeCourse *c: *gp->getCourses())
{
if (c->getSerialNum() == serialCourse)
{
switch (col)
{
case (gradeCourse::CourseScheme::NAME):
c->setName(change.toStdString());
break;
case (gradeCourse::CourseScheme::TYPE):
c->setType(change.toStdString());
break;
case (gradeCourse::CourseScheme::POINTS):
{
change.toDouble(&isNumFlag);
if (!isNumFlag)
{
courseTBL->item(row,col)->setText(QString::number(c->getPoints()));
}
else
c->setPoints(change.toDouble());
break;
}
case (gradeCourse::CourseScheme::HOURS):
{
change.toDouble(&isNumFlag);
if (!isNumFlag)
{
courseTBL->item(row,col)->setText(QString::number(c->getHours()));
}
else
c->setHours(change.toDouble());
break;
}
case (gradeCourse::CourseScheme::GRADE):
{
change.toDouble(&isNumFlag);
if (!isNumFlag)
{
courseTBL->item(row,col)->setText(QString::number(c->getGrade()));
}
else
{
if ((change.toDouble() >= 0) && (change.toDouble() <= 100))
c->setGrade(change.toDouble());
else
courseTBL->item(row,col)->setText(QString::number(c->getGrade()));
}
break;
}
case (gradeCourse::CourseScheme::ADDITION):
c->setAdditions(change.toStdString());
break;
}
break;
}
}
return isNumFlag;
}
/**
* @brief coursesTableManager::addRow adds row with given information
* @param courseToAdd if exists, add its information to table
*/
void coursesTableManager::addRow(const gradeCourse *courseToAdd)
{
int i,j;
i = courseTBL->rowCount();
j = 0;
QTableWidgetItem *serial,*name,*type,*points,*hours,*grade,*addition;
const gradeCourse * c;
if (courseToAdd != NULL)
{
c = courseToAdd;
if (!isCourseAlreadyInserted(c->getSerialNum()))
{
courseTBL->setRowCount(courseTBL->rowCount()+1);
serial = new QTableWidgetItem(QString::number(c->getSerialNum()));
serial->setFlags(serial->flags() & ~Qt::ItemIsEditable);
points = new QTableWidgetItem(QString::number(c->getPoints()));
points->setFlags(serial->flags() & ~Qt::ItemIsEditable);
hours = new QTableWidgetItem(QString::number(c->getHours()));
hours->setFlags(serial->flags() & ~Qt::ItemIsEditable);
grade = new QTableWidgetItem(QString::number(c->getGrade()));
name = new QTableWidgetItem(QString::fromStdString(c->getName()));
name->setFlags(serial->flags() & ~Qt::ItemIsEditable);
type = new QTableWidgetItem(QString::fromStdString(c->getType()));
type->setFlags(serial->flags() & ~Qt::ItemIsEditable);
addition = new QTableWidgetItem(QString::fromStdString(c->getAddidtions()));
courseTBL->setItem(i,j++,serial);
courseTBL->setItem(i,j++,name);
courseTBL->setItem(i,j++,type);
courseTBL->setItem(i,j++,points);
courseTBL->setItem(i,j++,hours);
courseTBL->setItem(i,j++,grade);
courseTBL->setItem(i,j,addition);
}
}
else
{
}
courseTBL->resizeColumnsToContents();
}
double coursesTableManager::getAvg()
{
if (this->gp != NULL)
return gp->getAvg();
return 0;
}
void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus)
{
if (ignoreCourseStatus)
{
int i = 0;
while (i < courseTBL->rowCount())
{
if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0)
courseTBL->removeRow(i--);
i++;
}
}
else
{
for (gradeCourse *c: *gp->getCourses())
{
if (!(isCourseAlreadyInserted(c->getSerialNum())))
if (c->getPoints() == 0)
addRow(c);
}
}
}
void coursesTableManager::clearTable()
{
if (courseTBL->rowCount() == 0)
return;
int i = 0; //starting point
while (courseTBL->rowCount() > i)
{
gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text().toStdString());
courseTBL->removeRow(i);
}
gp = NULL;
courseTBL->repaint();
}
gradeCourse *coursesTableManager::getCourseByRow(int row)
{
QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text();
for (gradeCourse *c: *gp->getCourses())
{
if (c->getSerialNum() == courseSerial.toDouble())
return c;
}
return NULL;
}
bool coursesTableManager::isCourseAlreadyInserted(double courseID)
{
int i=0;
for (i = 0; i < courseTBL->rowCount(); ++i)
{
QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text();
if (QString::number(courseID) == courseSerial)
return true;
}
return false;
}
bool coursesTableManager::isCourseInfluence(const gradeCourse *courseToCheck)
{
if (courseToCheck->getPoints() > 0)
return true;
return false;
}
#include "coursestablemanager.h"
coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr)
{
this->gp = NULL;
this->us = usrPtr;
this->courseTBL = ptr;
/*
* Initilizing Table
*/
courseTBL->setRowCount(0);
courseTBL->setColumnCount(COURSE_FIELDS);
QStringList mz;
mz << QObject::tr("Code") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions");
courseTBL->setHorizontalHeaderLabels(mz);
courseTBL->verticalHeader()->setVisible(true);
courseTBL->setSelectionMode(QAbstractItemView::SingleSelection);
courseTBL->setShowGrid(true);
courseTBL->setStyleSheet("QTableView {selection-background-color: red;}");
}
coursesTableManager::~coursesTableManager()
{
courseTBL = NULL;
delete gp;
gp = NULL;
}
/**
* @brief coursesTableManager::insertJceCoursesIntoTable phrasing the course list to rows in table
*/
void coursesTableManager::insertJceCoursesIntoTable()
{
for (gradeCourse *c: *gp->getCourses())
{
if (us->getInfluenceCourseOnly())
{
if (isCourseInfluence(c))
addRow(c);
}
else
addRow(c);
}
}
/**
* @brief coursesTableManager::setCoursesList creating courses list with given html page
* @param html
*/
void coursesTableManager::setCoursesList(std::string &html)
{
gp = new GradePage(html);
}
/**
* @brief coursesTableManager::changes when user changes the table manually it updates it
* @param change string change
* @param row row index
* @param col col index
* @return if change has been done
*/
bool coursesTableManager::changes(QString change, int row, int col)
{
bool isNumFlag = true;
int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt();
for (gradeCourse *c: *gp->getCourses())
{
if (c->getSerialNum() == serialCourse)
{
switch (col)
{
case (gradeCourse::CourseScheme::NAME):
c->setName(change.toStdString());
break;
case (gradeCourse::CourseScheme::TYPE):
c->setType(change.toStdString());
break;
case (gradeCourse::CourseScheme::POINTS):
{
change.toDouble(&isNumFlag);
if (!isNumFlag)
{
courseTBL->item(row,col)->setText(QString::number(c->getPoints()));
}
else
c->setPoints(change.toDouble());
break;
}
case (gradeCourse::CourseScheme::HOURS):
{
change.toDouble(&isNumFlag);
if (!isNumFlag)
{
courseTBL->item(row,col)->setText(QString::number(c->getHours()));
}
else
c->setHours(change.toDouble());
break;
}
case (gradeCourse::CourseScheme::GRADE):
{
change.toDouble(&isNumFlag);
if (!isNumFlag)
{
courseTBL->item(row,col)->setText(QString::number(c->getGrade()));
}
else
{
if ((change.toDouble() >= 0) && (change.toDouble() <= 100))
c->setGrade(change.toDouble());
else
courseTBL->item(row,col)->setText(QString::number(c->getGrade()));
}
break;
}
case (gradeCourse::CourseScheme::ADDITION):
c->setAdditions(change.toStdString());
break;
}
break;
}
}
return isNumFlag;
}
/**
* @brief coursesTableManager::addRow adds row with given information
* @param courseToAdd if exists, add its information to table
*/
void coursesTableManager::addRow(const gradeCourse *courseToAdd)
{
int i,j;
i = courseTBL->rowCount();
j = 0;
QTableWidgetItem *serial,*name,*type,*points,*hours,*grade,*addition;
const gradeCourse * c;
if (courseToAdd != NULL)
{
c = courseToAdd;
if (!isCourseAlreadyInserted(c->getSerialNum()))
{
courseTBL->setRowCount(courseTBL->rowCount()+1);
serial = new QTableWidgetItem(QString::number(c->getSerialNum()));
serial->setFlags(serial->flags() & ~Qt::ItemIsEditable);
points = new QTableWidgetItem(QString::number(c->getPoints()));
points->setFlags(serial->flags() & ~Qt::ItemIsEditable);
hours = new QTableWidgetItem(QString::number(c->getHours()));
hours->setFlags(serial->flags() & ~Qt::ItemIsEditable);
grade = new QTableWidgetItem(QString::number(c->getGrade()));
name = new QTableWidgetItem(QString::fromStdString(c->getName()));
name->setFlags(serial->flags() & ~Qt::ItemIsEditable);
type = new QTableWidgetItem(QString::fromStdString(c->getType()));
type->setFlags(serial->flags() & ~Qt::ItemIsEditable);
addition = new QTableWidgetItem(QString::fromStdString(c->getAddidtions()));
courseTBL->setItem(i,j++,serial);
courseTBL->setItem(i,j++,name);
courseTBL->setItem(i,j++,type);
courseTBL->setItem(i,j++,points);
courseTBL->setItem(i,j++,hours);
courseTBL->setItem(i,j++,grade);
courseTBL->setItem(i,j,addition);
}
}
else
{
}
courseTBL->resizeColumnsToContents();
}
double coursesTableManager::getAvg()
{
if (this->gp != NULL)
return gp->getAvg();
return 0;
}
void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus)
{
if (ignoreCourseStatus)
{
int i = 0;
while (i < courseTBL->rowCount())
{
if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0)
courseTBL->removeRow(i--);
i++;
}
}
else
{
for (gradeCourse *c: *gp->getCourses())
{
if (!(isCourseAlreadyInserted(c->getSerialNum())))
if (c->getPoints() == 0)
addRow(c);
}
}
}
void coursesTableManager::clearTable()
{
if (courseTBL->rowCount() == 0)
return;
int i = 0; //starting point
while (courseTBL->rowCount() > i)
{
gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text().toStdString());
courseTBL->removeRow(i);
}
gp = NULL;
courseTBL->repaint();
}
gradeCourse *coursesTableManager::getCourseByRow(int row)
{
QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text();
for (gradeCourse *c: *gp->getCourses())
{
if (c->getSerialNum() == courseSerial.toDouble())
return c;
}
return NULL;
}
bool coursesTableManager::isCourseAlreadyInserted(double courseID)
{
int i=0;
for (i = 0; i < courseTBL->rowCount(); ++i)
{
QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text();
if (QString::number(courseID) == courseSerial)
return true;
}
return false;
}
bool coursesTableManager::isCourseInfluence(const gradeCourse *courseToCheck)
{
if (courseToCheck->getPoints() > 0)
return true;
return false;
}

View file

@ -1,43 +1,43 @@
#ifndef COURSESTABLEMANAGER_H
#define COURSESTABLEMANAGER_H
#include <QApplication>
#include <QDesktopWidget>
#include <QtCore/QCoreApplication>
#include <QHeaderView>
#include <QMessageBox>
#include <QTableWidget>
#include <QString>
#include <QMessageBox>
#include <list>
#include "./src/jceData/Grades/gradePage.h"
#include "./src/jceSettings/user.h"
class coursesTableManager
{
public:
coursesTableManager(QTableWidget *, user *usrPtr);
~coursesTableManager();
void insertJceCoursesIntoTable();
void setCoursesList(std::string &htmlPage);
bool changes(QString change, int row, int col);
void addRow(const gradeCourse * courseToAdd = 0);
double getAvg();
void influnceCourseChanged(bool status);
void clearTable();
private:
QTableWidget *courseTBL;
GradePage *gp;
user *us;
gradeCourse * getCourseByRow(int row);
bool isCourseAlreadyInserted(double courseID);
bool isCourseInfluence(const gradeCourse *courseToCheck);
};
#endif // COURSESTABLEMANAGER_H
#ifndef COURSESTABLEMANAGER_H
#define COURSESTABLEMANAGER_H
#include <QApplication>
#include <QDesktopWidget>
#include <QtCore/QCoreApplication>
#include <QHeaderView>
#include <QMessageBox>
#include <QTableWidget>
#include <QString>
#include <QMessageBox>
#include <list>
#include "./src/jceData/Grades/gradePage.h"
#include "./src/jceSettings/user.h"
class coursesTableManager
{
public:
coursesTableManager(QTableWidget *, user *usrPtr);
~coursesTableManager();
void insertJceCoursesIntoTable();
void setCoursesList(std::string &htmlPage);
bool changes(QString change, int row, int col);
void addRow(const gradeCourse * courseToAdd = 0);
double getAvg();
void influnceCourseChanged(bool status);
void clearTable();
private:
QTableWidget *courseTBL;
GradePage *gp;
user *us;
gradeCourse * getCourseByRow(int row);
bool isCourseAlreadyInserted(double courseID);
bool isCourseInfluence(const gradeCourse *courseToCheck);
};
#endif // COURSESTABLEMANAGER_H

View file

@ -1,141 +1,145 @@
#include "loginhandler.h"
loginHandler::loginHandler(user *ptr): logggedInFlag(false)
{
this->jceLog = new jceLogin(ptr);
}
void loginHandler::setPointers(QLabel *statusLabelPtr,QLineEdit *pswdEditPtr,QLineEdit *usrnmEditPtr)
{
this->statusLabelPtr = statusLabelPtr;
this->pswdEditPtr = pswdEditPtr;
this->usrnmEditPtr = usrnmEditPtr;
}
bool loginHandler::makeConnection()
{
if (this->jceLog == NULL)
return false;
try
{
jceLog->makeConnection();
}
catch (jceLogin::jceStatus &a)
{
int status = (int)a;
switch (status)
{
case jceLogin::JCE_YOU_ARE_IN:
{
logggedInFlag = true;
return logggedInFlag;
break;
}
case jceLogin::ERROR_ON_VALIDATION:
{
popMessage("Please Check Your Username & Password",false);
usrnmEditPtr->setDisabled(false);
pswdEditPtr->setDisabled(false);
pswdEditPtr->selectAll();
pswdEditPtr->setFocus();
return false;
}
case jceLogin::ERROR_ON_VALIDATION_USER_BLOCKED:
{
popMessage("You have been blocked by JCE, please try in a couple of minutes.");
jceLog->closeAll();
return false;
}
case jceLogin::ERROR_ON_OPEN_SOCKET:
{
popMessage("Please Check Your Internet Connection.");
jceLog->closeAll();
return false;
}
case jceLogin::JCE_NOT_CONNECTED:
{
jceLog->reConnect();
/*
* Fix: need to add a prompte window to ask user whether he wants to reconnect or not
*/
break;
}
case jceLogin::ERROR_ON_GETTING_INFO:
{
popMessage("Recieve Request Time Out.");
jceLog->closeAll();
return false;
break;
}
case jceLogin::ERROR_ON_SEND_REQUEST:
{
popMessage("Send Request Time Out.");
jceLog->closeAll();
return false;
break;
}
}
}
return false;
}
bool loginHandler::isLoggedInFlag()
{
return this->logggedInFlag;
}
void loginHandler::setLoginFlag(bool flag)
{
this->logggedInFlag = flag;
}
QString loginHandler::getCurrentPageContect()
{
QTextEdit phrase;
if (isLoggedInFlag())
phrase.setText(QString::fromStdString(jceLog->getPage()));
else
throw jceLogin::ERROR_ON_GETTING_INFO;
return phrase.toPlainText();
}
void loginHandler::makeDisconnectionRequest()
{
jceLog->closeAll();
this->logggedInFlag = false;
}
int loginHandler::makeGradeRequest(int fromYear, int toYear, int fromSemester, int toSemester)
{
if (isLoggedInFlag())
return jceLog->getGrades(fromYear, toYear, fromSemester, toSemester);
else
return jceLogin::JCE_NOT_CONNECTED;
}
int loginHandler::makeCalendarRequest(int year, int semester)
{
if (isLoggedInFlag())
return jceLog->getCalendar(year,semester);
else
return jceLogin::JCE_NOT_CONNECTED;
}
void loginHandler::popMessage(QString message,bool addInfo)
{
if (addInfo)
message.append("\nIf this message appear without reason, please contact me at liranbg@gmail.com");
QMessageBox msgBox;
msgBox.setWindowTitle("Error");
msgBox.setText(message);
msgBox.exec();
msgBox.setFocus();
}
#include "loginhandler.h"
loginHandler::loginHandler(user *ptr): logggedInFlag(false)
{
this->jceLog = new jceLogin(ptr);
}
void loginHandler::setPointers(QLabel *statusLabelPtr,QLineEdit *pswdEditPtr,QLineEdit *usrnmEditPtr)
{
this->statusLabelPtr = statusLabelPtr;
this->pswdEditPtr = pswdEditPtr;
this->usrnmEditPtr = usrnmEditPtr;
}
bool loginHandler::makeConnection()
{
if (this->jceLog == NULL)
return false;
try
{
jceLog->makeConnection();
}
catch (jceLogin::jceStatus &a)
{
int status = (int)a;
switch (status)
{
case jceLogin::JCE_YOU_ARE_IN:
{
logggedInFlag = true;
return logggedInFlag;
break;
}
case jceLogin::ERROR_ON_VALIDATION:
{
popMessage("Please Check Your Username & Password",false);
usrnmEditPtr->setDisabled(false);
pswdEditPtr->setDisabled(false);
pswdEditPtr->selectAll();
pswdEditPtr->setFocus();
return false;
}
case jceLogin::ERROR_ON_VALIDATION_USER_BLOCKED:
{
popMessage("You have been blocked by JCE, please try in a couple of minutes.");
jceLog->closeAll();
return false;
}
case jceLogin::ERROR_ON_OPEN_SOCKET:
{
popMessage("Please Check Your Internet Connection.");
jceLog->closeAll();
return false;
}
case jceLogin::JCE_NOT_CONNECTED:
{
jceLog->reConnect();
/*
* Fix: need to add a prompte window to ask user whether he wants to reconnect or not
*/
break;
}
case jceLogin::ERROR_ON_GETTING_INFO:
{
popMessage("Recieve Request Time Out.");
jceLog->closeAll();
return false;
break;
}
case jceLogin::ERROR_ON_SEND_REQUEST:
{
popMessage("Send Request Time Out.");
jceLog->closeAll();
return false;
break;
}
}
}
return false;
}
bool loginHandler::isLoggedInFlag()
{
if (jceLog->isLoginFlag()) //checking connection and then if logged in
return this->logggedInFlag;
else
this->setLoginFlag(false);
return false;
}
void loginHandler::setLoginFlag(bool flag)
{
this->logggedInFlag = flag;
}
QString loginHandler::getCurrentPageContect()
{
QTextEdit phrase;
if (isLoggedInFlag())
phrase.setText(QString::fromStdString(jceLog->getPage()));
else
throw jceLogin::ERROR_ON_GETTING_INFO;
return phrase.toPlainText();
}
void loginHandler::makeDisconnectionRequest()
{
jceLog->closeAll();
this->logggedInFlag = false;
}
int loginHandler::makeGradeRequest(int fromYear, int toYear, int fromSemester, int toSemester)
{
if (isLoggedInFlag())
return jceLog->getGrades(fromYear, toYear, fromSemester, toSemester);
else
return jceLogin::JCE_NOT_CONNECTED;
}
int loginHandler::makeCalendarRequest(int year, int semester)
{
if (isLoggedInFlag())
return jceLog->getCalendar(year,semester);
else
return jceLogin::JCE_NOT_CONNECTED;
}
void loginHandler::popMessage(QString message,bool addInfo)
{
if (addInfo)
message.append("\nIf this message appear without reason, please contact me at liranbg@gmail.com");
QMessageBox msgBox;
msgBox.setWindowTitle("Error");
msgBox.setText(message);
msgBox.exec();
msgBox.setFocus();
}

View file

@ -1,44 +1,44 @@
#ifndef LOGINHANDLER_H
#define LOGINHANDLER_H
#include <QString>
#include <QLabel>
#include <QLineEdit>
#include <QTextEdit>
#include <QMessageBox>
#include <QPixmap>
#include "./src/jceSettings/jcelogin.h"
#include "./src/appDatabase/savedata.h"
class loginHandler
{
public:
loginHandler(user *ptr);
void setPointers(QLabel *statusLabelPtr,QLineEdit *pswdEditPtr,QLineEdit *usrnmEditPtr);
bool makeConnection();
bool isLoggedInFlag();
void setLoginFlag(bool flag);
QString getCurrentPageContect();
int makeGradeRequest(int fromYear, int toYear, int fromSemester, int toSemester);
int makeCalendarRequest(int year,int semester);
void makeDisconnectionRequest();
private:
void popMessage(QString message, bool addInfo = true);
bool logggedInFlag;
jceLogin *jceLog;
QLabel *statusLabelPtr;
QLineEdit *pswdEditPtr;
QLineEdit *usrnmEditPtr;
};
#endif // LOGINHANDLER_H
#ifndef LOGINHANDLER_H
#define LOGINHANDLER_H
#include <QString>
#include <QLabel>
#include <QLineEdit>
#include <QTextEdit>
#include <QMessageBox>
#include <QPixmap>
#include "./src/jceSettings/jcelogin.h"
#include "./src/appDatabase/savedata.h"
class loginHandler
{
public:
loginHandler(user *ptr);
void setPointers(QLabel *statusLabelPtr,QLineEdit *pswdEditPtr,QLineEdit *usrnmEditPtr);
bool makeConnection();
bool isLoggedInFlag();
void setLoginFlag(bool flag);
QString getCurrentPageContect();
int makeGradeRequest(int fromYear, int toYear, int fromSemester, int toSemester);
int makeCalendarRequest(int year,int semester);
void makeDisconnectionRequest();
private:
void popMessage(QString message, bool addInfo = true);
bool logggedInFlag;
jceLogin *jceLog;
QLabel *statusLabelPtr;
QLineEdit *pswdEditPtr;
QLineEdit *usrnmEditPtr;
};
#endif // LOGINHANDLER_H

View file

@ -13,6 +13,7 @@ MainScreen::MainScreen(QWidget *parent) :QMainWindow(parent), ui(new Ui::MainScr
ui->pswdLineEdit->setEchoMode((QLineEdit::Password));
//Status Bar
ui->actionEnglish->setChecked(true);
ui->statusBar->setStyleSheet("QStatusBar::item { border: 0px solid black };");
ButtomStatusLabel = new QLabel(this);
statusLabel = new QLabel(this);
@ -65,7 +66,7 @@ void MainScreen::on_loginButton_clicked()
uiSetConnectMode();
}
void MainScreen::on_pushButton_clicked()
void MainScreen::on_getCalendarBtn_clicked()
{
int status = 0;
if (loginHandel->isLoggedInFlag())
@ -74,7 +75,7 @@ void MainScreen::on_pushButton_clicked()
{
//Use it for debug. add plain text and change the object name to 'plainTextEdit' so you will get the html request
//ui->plainTextEdit->setPlainText(loginHandel->getCurrentPageContect());
calendar->resetTable();
calendar->resetTable();
calendar->setCalendar(loginHandel->getCurrentPageContect().toStdString());
}
@ -174,7 +175,9 @@ void MainScreen::uiSetDisconnectMode()
loginHandel->makeDisconnectionRequest();
ui->loginButton->setText("&Login");
this->ui->ratesButton->setDisabled(true);
ui->getCalendarBtn->setDisabled(true);
ui->exportToCVSBtn->setDisabled(true);
ui->ratesButton->setDisabled(true);
return;
}
@ -203,8 +206,10 @@ void MainScreen::uiSetConnectMode() //fix before distrbute
{
setLabelConnectionStatus(jceLogin::jceStatus::JCE_YOU_ARE_IN);
ui->loginButton->setText("&Logout");
this->ui->ratesButton->setEnabled(true);
ui->ratesButton->setEnabled(true);
ui->CoursesTab->setEnabled(true);
ui->exportToCVSBtn->setEnabled(true);
ui->getCalendarBtn->setEnabled(true);
}
else
@ -246,10 +251,6 @@ void MainScreen::on_actionCredits_triggered()
"<ul>"
"<li><a href='mailto:liranbg@gmail.com'>"+tr("Liran")+"</a></li>"
"<li><a href='mailto:sagidayan@gmail.com'>"+tr("Sagi")+"</a></li>"
"</ul>"
+tr("Tnks")+ "... :"
"<ul>"
"<li><a href='mailto:nadav2051@gmail.com'>"+tr("Nadav")+"</a></li>"
"</ul>");
}
@ -292,19 +293,64 @@ void MainScreen::on_actionHow_To_triggered()
}
void MainScreen::on_pushButton_2_clicked()
//void MainScreen::on_pushButton_2_clicked()
//{
// if(CSV_Exporter::exportCalendar(this->calendar->getSch()))
// {
// QMessageBox msgBox;
// msgBox.setText("<center>Exported Successfuly!<br><b>HaazZaA!!");
// msgBox.exec();
// }else
// {
// QMessageBox msgBox;
// msgBox.setIcon(QMessageBox::Critical);
// msgBox.setText("<center>Something went wrong...<br></center>Maybe: <ul><li>You Canceled</li><li>Unable to save the File - try again</li></ul><br><br>"
// "<b><center>In case of a serious problem, please file a bug report.<br>thank you. OpenJCE teem");
// msgBox.exec();
// }
//}
void MainScreen::on_exportToCVSBtn_clicked()
{
if(CSV_Exporter::exportCalendar(this->calendar->getSch()))
if (loginHandel->isLoggedInFlag())
this->calendar->exportCalendarCSV();
}
void MainScreen::on_actionHebrew_triggered()
{
if (ui->actionEnglish->isChecked())
{
QMessageBox msgBox;
msgBox.setText("<center>Exported Successfuly!<br><b>HaazZaA!!");
msgBox.exec();
}else
ui->actionEnglish->setChecked(false);
qDebug() << "Changed Language";
}
else
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("<center>Something went wrong...<br></center>Maybe: <ul><li>You Canceled</li><li>Unable to save the File - try again</li></ul><br><br>"
"<b><center>In case of a serious problem, please file a bug report.<br>thank you. OpenJCE teem");
msgBox.exec();
ui->actionHebrew->setChecked(true);
qDebug() << "Set Hebrew Language: ";
}
}
void MainScreen::on_actionEnglish_triggered()
{
if (ui->actionHebrew->isChecked())
{
ui->actionHebrew->setChecked(false);
qDebug() << "Changed Language";
}
else
{
ui->actionEnglish->setChecked(true);
qDebug() << "Set English Language: ";
}
}

View file

@ -13,7 +13,7 @@
#include "./CourseTab/coursestablemanager.h"
#include "./LoginTab/loginhandler.h"
#include "./CalendarTab/CalendarManager.h"
#include "../src/jceData/CSV/csv_exporter.h"
#define StatusIconHeight 35
namespace Ui {
@ -56,11 +56,15 @@ private slots:
void on_actionHow_To_triggered();
void on_pushButton_clicked();
void on_getCalendarBtn_clicked();
void on_checkBoxCoursesInfluence_toggled(bool checked);
void on_pushButton_2_clicked();
void on_exportToCVSBtn_clicked();
void on_actionHebrew_triggered();
void on_actionEnglish_triggered();
private:

View file

@ -582,14 +582,14 @@ font-size: 15px;
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton">
<widget class="QPushButton" name="getCalendarBtn">
<property name="text">
<string>Get Calendar</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_2">
<widget class="QPushButton" name="exportToCVSBtn">
<property name="text">
<string>Export to CSV</string>
</property>
@ -626,14 +626,21 @@ font-size: 15px;
<x>0</x>
<y>0</y>
<width>855</width>
<height>29</height>
<height>22</height>
</rect>
</property>
<widget class="QMenu" name="menuA_about">
<property name="title">
<string>&amp;About</string>
</property>
<addaction name="actionHow_To"/>
<widget class="QMenu" name="menuLanguage">
<property name="title">
<string>Language</string>
</property>
<addaction name="actionHebrew"/>
<addaction name="actionEnglish"/>
</widget>
<addaction name="menuLanguage"/>
<addaction name="actionCredits"/>
<addaction name="actionExit"/>
</widget>
@ -663,9 +670,20 @@ font-size: 15px;
<string>Exit</string>
</property>
</action>
<action name="actionHow_To">
<action name="actionHebrew">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>How-To</string>
<string>hebrew</string>
</property>
</action>
<action name="actionEnglish">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>English</string>
</property>
</action>
</widget>

View file

@ -1,255 +1,255 @@
/*
Copyright (c) 2011, Andre Somers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Rathenau Instituut, Andre Somers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ANDRE SOMERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Fixed By Sagi Dayan
*/
#include "simplecrypt.h"
#include <QByteArray>
#include <QtDebug>
#include <QtGlobal>
#include <QDateTime>
#include <QCryptographicHash>
SimpleCrypt::SimpleCrypt():
m_key(0),
m_compressionMode(CompressionAuto),
m_protectionMode(ProtectionChecksum),
m_lastError(ErrorNoError)
{
qsrand(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF));
}
SimpleCrypt::SimpleCrypt(quint64 key):
m_key(key),
m_compressionMode(CompressionAuto),
m_protectionMode(ProtectionChecksum),
m_lastError(ErrorNoError)
{
qsrand(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF));
splitKey();
}
void SimpleCrypt::setKey(quint64 key)
{
m_key = key;
splitKey();
}
void SimpleCrypt::splitKey()
{
m_keyParts.clear();
m_keyParts.resize(8);
for (int i=0;i<8;i++) {
quint64 part = m_key;
for (int j=i; j>0; j--)
part = part >> 8;
part = part & 0xff;
m_keyParts[i] = static_cast<char>(part);
}
}
QByteArray SimpleCrypt::encryptToByteArray(const QString& plaintext)
{
QByteArray plaintextArray = plaintext.toUtf8();
return encryptToByteArray(plaintextArray);
}
QByteArray SimpleCrypt::encryptToByteArray(QByteArray plaintext)
{
if (m_keyParts.isEmpty()) {
qWarning() << "No key set.";
m_lastError = ErrorNoKeySet;
return QByteArray();
}
QByteArray ba = plaintext;
CryptoFlags flags = CryptoFlagNone;
if (m_compressionMode == CompressionAlways) {
ba = qCompress(ba, 9); //maximum compression
flags |= CryptoFlagCompression;
} else if (m_compressionMode == CompressionAuto) {
QByteArray compressed = qCompress(ba, 9);
if (compressed.count() < ba.count()) {
ba = compressed;
flags |= CryptoFlagCompression;
}
}
QByteArray integrityProtection;
if (m_protectionMode == ProtectionChecksum) {
flags |= CryptoFlagChecksum;
QDataStream s(&integrityProtection, QIODevice::WriteOnly);
s << qChecksum(ba.constData(), ba.length());
} else if (m_protectionMode == ProtectionHash) {
flags |= CryptoFlagHash;
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData(ba);
integrityProtection += hash.result();
}
//prepend a random char to the string
char randomChar = char(qrand() & 0xFF);
ba = randomChar + integrityProtection + ba;
int pos(0);
char lastChar(0);
int cnt = ba.count();
while (pos < cnt) {
ba[pos] = ba.at(pos) ^ m_keyParts.at(pos % 8) ^ lastChar;
lastChar = ba.at(pos);
++pos;
}
QByteArray resultArray;
resultArray.append(char(0x03)); //version for future updates to algorithm
resultArray.append(char(flags)); //encryption flags
resultArray.append(ba);
m_lastError = ErrorNoError;
return resultArray;
}
QString SimpleCrypt::encryptToString(const QString& plaintext)
{
QByteArray plaintextArray = plaintext.toUtf8();
QByteArray cypher = encryptToByteArray(plaintextArray);
QString cypherString = QString(cypher.toBase64());
return cypherString;
}
QString SimpleCrypt::encryptToString(QByteArray plaintext)
{
QByteArray cypher = encryptToByteArray(plaintext);
QString cypherString = QString(cypher.toBase64());
return cypherString;
}
QString SimpleCrypt::decryptToString(const QString &cyphertext)
{
QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toLatin1());
QByteArray plaintextArray = decryptToByteArray(cyphertextArray);
QString plaintext = QString::fromUtf8(plaintextArray, plaintextArray.size());
return plaintext;
}
QString SimpleCrypt::decryptToString(QByteArray cypher)
{
QByteArray ba = decryptToByteArray(cypher);
QString plaintext = QString::fromUtf8(ba, ba.size());
return plaintext;
}
QByteArray SimpleCrypt::decryptToByteArray(const QString& cyphertext)
{
QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toLatin1());
QByteArray ba = decryptToByteArray(cyphertextArray);
return ba;
}
QByteArray SimpleCrypt::decryptToByteArray(QByteArray cypher)
{
if (m_keyParts.isEmpty()) {
qWarning() << "No key set.";
m_lastError = ErrorNoKeySet;
return QByteArray();
}
QByteArray ba = cypher;
if( cypher.count() < 3 )
return QByteArray();
char version = ba.at(0);
if (version !=3) { //we only work with version 3
m_lastError = ErrorUnknownVersion;
qWarning() << "Invalid version or not a cyphertext.";
return QByteArray();
}
CryptoFlags flags = CryptoFlags(ba.at(1));
ba = ba.mid(2);
int pos(0);
int cnt(ba.count());
char lastChar = 0;
while (pos < cnt) {
char currentChar = ba[pos];
ba[pos] = ba.at(pos) ^ lastChar ^ m_keyParts.at(pos % 8);
lastChar = currentChar;
++pos;
}
ba = ba.mid(1); //chop off the random number at the start
bool integrityOk(true);
if (flags.testFlag(CryptoFlagChecksum)) {
if (ba.length() < 2) {
m_lastError = ErrorIntegrityFailed;
return QByteArray();
}
quint16 storedChecksum;
{
QDataStream s(&ba, QIODevice::ReadOnly);
s >> storedChecksum;
}
ba = ba.mid(2);
quint16 checksum = qChecksum(ba.constData(), ba.length());
integrityOk = (checksum == storedChecksum);
} else if (flags.testFlag(CryptoFlagHash)) {
if (ba.length() < 20) {
m_lastError = ErrorIntegrityFailed;
return QByteArray();
}
QByteArray storedHash = ba.left(20);
ba = ba.mid(20);
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData(ba);
integrityOk = (hash.result() == storedHash);
}
if (!integrityOk) {
m_lastError = ErrorIntegrityFailed;
return QByteArray();
}
if (flags.testFlag(CryptoFlagCompression))
ba = qUncompress(ba);
m_lastError = ErrorNoError;
return ba;
}
/*
Copyright (c) 2011, Andre Somers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Rathenau Instituut, Andre Somers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ANDRE SOMERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Fixed By Sagi Dayan
*/
#include "simplecrypt.h"
#include <QByteArray>
#include <QtDebug>
#include <QtGlobal>
#include <QDateTime>
#include <QCryptographicHash>
SimpleCrypt::SimpleCrypt():
m_key(0),
m_compressionMode(CompressionAuto),
m_protectionMode(ProtectionChecksum),
m_lastError(ErrorNoError)
{
qsrand(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF));
}
SimpleCrypt::SimpleCrypt(quint64 key):
m_key(key),
m_compressionMode(CompressionAuto),
m_protectionMode(ProtectionChecksum),
m_lastError(ErrorNoError)
{
qsrand(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF));
splitKey();
}
void SimpleCrypt::setKey(quint64 key)
{
m_key = key;
splitKey();
}
void SimpleCrypt::splitKey()
{
m_keyParts.clear();
m_keyParts.resize(8);
for (int i=0;i<8;i++) {
quint64 part = m_key;
for (int j=i; j>0; j--)
part = part >> 8;
part = part & 0xff;
m_keyParts[i] = static_cast<char>(part);
}
}
QByteArray SimpleCrypt::encryptToByteArray(const QString& plaintext)
{
QByteArray plaintextArray = plaintext.toUtf8();
return encryptToByteArray(plaintextArray);
}
QByteArray SimpleCrypt::encryptToByteArray(QByteArray plaintext)
{
if (m_keyParts.isEmpty()) {
qWarning() << "No key set.";
m_lastError = ErrorNoKeySet;
return QByteArray();
}
QByteArray ba = plaintext;
CryptoFlags flags = CryptoFlagNone;
if (m_compressionMode == CompressionAlways) {
ba = qCompress(ba, 9); //maximum compression
flags |= CryptoFlagCompression;
} else if (m_compressionMode == CompressionAuto) {
QByteArray compressed = qCompress(ba, 9);
if (compressed.count() < ba.count()) {
ba = compressed;
flags |= CryptoFlagCompression;
}
}
QByteArray integrityProtection;
if (m_protectionMode == ProtectionChecksum) {
flags |= CryptoFlagChecksum;
QDataStream s(&integrityProtection, QIODevice::WriteOnly);
s << qChecksum(ba.constData(), ba.length());
} else if (m_protectionMode == ProtectionHash) {
flags |= CryptoFlagHash;
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData(ba);
integrityProtection += hash.result();
}
//prepend a random char to the string
char randomChar = char(qrand() & 0xFF);
ba = randomChar + integrityProtection + ba;
int pos(0);
char lastChar(0);
int cnt = ba.count();
while (pos < cnt) {
ba[pos] = ba.at(pos) ^ m_keyParts.at(pos % 8) ^ lastChar;
lastChar = ba.at(pos);
++pos;
}
QByteArray resultArray;
resultArray.append(char(0x03)); //version for future updates to algorithm
resultArray.append(char(flags)); //encryption flags
resultArray.append(ba);
m_lastError = ErrorNoError;
return resultArray;
}
QString SimpleCrypt::encryptToString(const QString& plaintext)
{
QByteArray plaintextArray = plaintext.toUtf8();
QByteArray cypher = encryptToByteArray(plaintextArray);
QString cypherString = QString(cypher.toBase64());
return cypherString;
}
QString SimpleCrypt::encryptToString(QByteArray plaintext)
{
QByteArray cypher = encryptToByteArray(plaintext);
QString cypherString = QString(cypher.toBase64());
return cypherString;
}
QString SimpleCrypt::decryptToString(const QString &cyphertext)
{
QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toLatin1());
QByteArray plaintextArray = decryptToByteArray(cyphertextArray);
QString plaintext = QString::fromUtf8(plaintextArray, plaintextArray.size());
return plaintext;
}
QString SimpleCrypt::decryptToString(QByteArray cypher)
{
QByteArray ba = decryptToByteArray(cypher);
QString plaintext = QString::fromUtf8(ba, ba.size());
return plaintext;
}
QByteArray SimpleCrypt::decryptToByteArray(const QString& cyphertext)
{
QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toLatin1());
QByteArray ba = decryptToByteArray(cyphertextArray);
return ba;
}
QByteArray SimpleCrypt::decryptToByteArray(QByteArray cypher)
{
if (m_keyParts.isEmpty()) {
qWarning() << "No key set.";
m_lastError = ErrorNoKeySet;
return QByteArray();
}
QByteArray ba = cypher;
if( cypher.count() < 3 )
return QByteArray();
char version = ba.at(0);
if (version !=3) { //we only work with version 3
m_lastError = ErrorUnknownVersion;
qWarning() << "Invalid version or not a cyphertext.";
return QByteArray();
}
CryptoFlags flags = CryptoFlags(ba.at(1));
ba = ba.mid(2);
int pos(0);
int cnt(ba.count());
char lastChar = 0;
while (pos < cnt) {
char currentChar = ba[pos];
ba[pos] = ba.at(pos) ^ lastChar ^ m_keyParts.at(pos % 8);
lastChar = currentChar;
++pos;
}
ba = ba.mid(1); //chop off the random number at the start
bool integrityOk(true);
if (flags.testFlag(CryptoFlagChecksum)) {
if (ba.length() < 2) {
m_lastError = ErrorIntegrityFailed;
return QByteArray();
}
quint16 storedChecksum;
{
QDataStream s(&ba, QIODevice::ReadOnly);
s >> storedChecksum;
}
ba = ba.mid(2);
quint16 checksum = qChecksum(ba.constData(), ba.length());
integrityOk = (checksum == storedChecksum);
} else if (flags.testFlag(CryptoFlagHash)) {
if (ba.length() < 20) {
m_lastError = ErrorIntegrityFailed;
return QByteArray();
}
QByteArray storedHash = ba.left(20);
ba = ba.mid(20);
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData(ba);
integrityOk = (hash.result() == storedHash);
}
if (!integrityOk) {
m_lastError = ErrorIntegrityFailed;
return QByteArray();
}
if (flags.testFlag(CryptoFlagCompression))
ba = qUncompress(ba);
m_lastError = ErrorNoError;
return ba;
}

View file

@ -1,229 +1,229 @@
/*
Copyright (c) 2011, Andre Somers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Rathenau Instituut, Andre Somers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ANDRE SOMERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SIMPLECRYPT_H
#define SIMPLECRYPT_H
#include <QString>
#include <QVector>
#include <QFlags>
/**
@short Simple encryption and decryption of strings and byte arrays
This class provides a simple implementation of encryption and decryption
of strings and byte arrays.
@warning The encryption provided by this class is NOT strong encryption. It may
help to shield things from curious eyes, but it will NOT stand up to someone
determined to break the encryption. Don't say you were not warned.
The class uses a 64 bit key. Simply create an instance of the class, set the key,
and use the encryptToString() method to calculate an encrypted version of the input string.
To decrypt that string again, use an instance of SimpleCrypt initialized with
the same key, and call the decryptToString() method with the encrypted string. If the key
matches, the decrypted version of the string will be returned again.
If you do not provide a key, or if something else is wrong, the encryption and
decryption function will return an empty string or will return a string containing nonsense.
lastError() will return a value indicating if the method was succesful, and if not, why not.
SimpleCrypt is prepared for the case that the encryption and decryption
algorithm is changed in a later version, by prepending a version identifier to the cypertext.
*/
/*
* Fixed By Sagi Dayan
*/
class SimpleCrypt
{
public:
/**
CompressionMode describes if compression will be applied to the data to be
encrypted.
*/
enum CompressionMode {
CompressionAuto, /*!< Only apply compression if that results in a shorter plaintext. */
CompressionAlways, /*!< Always apply compression. Note that for short inputs, a compression may result in longer data */
CompressionNever /*!< Never apply compression. */
};
/**
IntegrityProtectionMode describes measures taken to make it possible to detect problems with the data
or wrong decryption keys.
Measures involve adding a checksum or a cryptograhpic hash to the data to be encrypted. This
increases the length of the resulting cypertext, but makes it possible to check if the plaintext
appears to be valid after decryption.
*/
enum IntegrityProtectionMode {
ProtectionNone, /*!< The integerity of the encrypted data is not protected. It is not really possible to detect a wrong key, for instance. */
ProtectionChecksum,/*!< A simple checksum is used to verify that the data is in order. If not, an empty string is returned. */
ProtectionHash /*!< A cryptographic hash is used to verify the integrity of the data. This method produces a much stronger, but longer check */
};
/**
Error describes the type of error that occured.
*/
enum Error {
ErrorNoError, /*!< No error occurred. */
ErrorNoKeySet, /*!< No key was set. You can not encrypt or decrypt without a valid key. */
ErrorUnknownVersion, /*!< The version of this data is unknown, or the data is otherwise not valid. */
ErrorIntegrityFailed, /*!< The integrity check of the data failed. Perhaps the wrong key was used. */
};
/**
Constructor.
Constructs a SimpleCrypt instance without a valid key set on it.
*/
SimpleCrypt();
/**
Constructor.
Constructs a SimpleCrypt instance and initializes it with the given @arg key.
*/
explicit SimpleCrypt(quint64 key);
/**
(Re-) initializes the key with the given @arg key.
*/
void setKey(quint64 key);
/**
Returns true if SimpleCrypt has been initialized with a key.
*/
bool hasKey() const {return !m_keyParts.isEmpty();}
/**
Sets the compression mode to use when encrypting data. The default mode is Auto.
Note that decryption is not influenced by this mode, as the decryption recognizes
what mode was used when encrypting.
*/
void setCompressionMode(CompressionMode mode) {m_compressionMode = mode;}
/**
Returns the CompressionMode that is currently in use.
*/
CompressionMode compressionMode() const {return m_compressionMode;}
/**
Sets the integrity mode to use when encrypting data. The default mode is Checksum.
Note that decryption is not influenced by this mode, as the decryption recognizes
what mode was used when encrypting.
*/
void setIntegrityProtectionMode(IntegrityProtectionMode mode) {m_protectionMode = mode;}
/**
Returns the IntegrityProtectionMode that is currently in use.
*/
IntegrityProtectionMode integrityProtectionMode() const {return m_protectionMode;}
/**
Returns the last error that occurred.
*/
Error lastError() const {return m_lastError;}
/**
Encrypts the @arg plaintext string with the key the class was initialized with, and returns
a cyphertext the result. The result is a base64 encoded version of the binary array that is the
actual result of the string, so it can be stored easily in a text format.
*/
QString encryptToString(const QString& plaintext) ;
/**
Encrypts the @arg plaintext QByteArray with the key the class was initialized with, and returns
a cyphertext the result. The result is a base64 encoded version of the binary array that is the
actual result of the encryption, so it can be stored easily in a text format.
*/
QString encryptToString(QByteArray plaintext) ;
/**
Encrypts the @arg plaintext string with the key the class was initialized with, and returns
a binary cyphertext in a QByteArray the result.
This method returns a byte array, that is useable for storing a binary format. If you need
a string you can store in a text file, use encryptToString() instead.
*/
QByteArray encryptToByteArray(const QString& plaintext) ;
/**
Encrypts the @arg plaintext QByteArray with the key the class was initialized with, and returns
a binary cyphertext in a QByteArray the result.
This method returns a byte array, that is useable for storing a binary format. If you need
a string you can store in a text file, use encryptToString() instead.
*/
QByteArray encryptToByteArray(QByteArray plaintext) ;
/**
Decrypts a cyphertext string encrypted with this class with the set key back to the
plain text version.
If an error occured, such as non-matching keys between encryption and decryption,
an empty string or a string containing nonsense may be returned.
*/
QString decryptToString(const QString& cyphertext) ;
/**
Decrypts a cyphertext string encrypted with this class with the set key back to the
plain text version.
If an error occured, such as non-matching keys between encryption and decryption,
an empty string or a string containing nonsense may be returned.
*/
QByteArray decryptToByteArray(const QString& cyphertext) ;
/**
Decrypts a cyphertext binary encrypted with this class with the set key back to the
plain text version.
If an error occured, such as non-matching keys between encryption and decryption,
an empty string or a string containing nonsense may be returned.
*/
QString decryptToString(QByteArray cypher) ;
/**
Decrypts a cyphertext binary encrypted with this class with the set key back to the
plain text version.
If an error occured, such as non-matching keys between encryption and decryption,
an empty string or a string containing nonsense may be returned.
*/
QByteArray decryptToByteArray(QByteArray cypher) ;
//enum to describe options that have been used for the encryption. Currently only one, but
//that only leaves room for future extensions like adding a cryptographic hash...
enum CryptoFlag{CryptoFlagNone = 0,
CryptoFlagCompression = 0x01,
CryptoFlagChecksum = 0x02,
CryptoFlagHash = 0x04
};
Q_DECLARE_FLAGS(CryptoFlags, CryptoFlag);
private:
void splitKey();
quint64 m_key;
QVector<char> m_keyParts;
CompressionMode m_compressionMode;
IntegrityProtectionMode m_protectionMode;
Error m_lastError;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(SimpleCrypt::CryptoFlags)
#endif // SimpleCrypt_H
/*
Copyright (c) 2011, Andre Somers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Rathenau Instituut, Andre Somers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ANDRE SOMERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SIMPLECRYPT_H
#define SIMPLECRYPT_H
#include <QString>
#include <QVector>
#include <QFlags>
/**
@short Simple encryption and decryption of strings and byte arrays
This class provides a simple implementation of encryption and decryption
of strings and byte arrays.
@warning The encryption provided by this class is NOT strong encryption. It may
help to shield things from curious eyes, but it will NOT stand up to someone
determined to break the encryption. Don't say you were not warned.
The class uses a 64 bit key. Simply create an instance of the class, set the key,
and use the encryptToString() method to calculate an encrypted version of the input string.
To decrypt that string again, use an instance of SimpleCrypt initialized with
the same key, and call the decryptToString() method with the encrypted string. If the key
matches, the decrypted version of the string will be returned again.
If you do not provide a key, or if something else is wrong, the encryption and
decryption function will return an empty string or will return a string containing nonsense.
lastError() will return a value indicating if the method was succesful, and if not, why not.
SimpleCrypt is prepared for the case that the encryption and decryption
algorithm is changed in a later version, by prepending a version identifier to the cypertext.
*/
/*
* Fixed By Sagi Dayan
*/
class SimpleCrypt
{
public:
/**
CompressionMode describes if compression will be applied to the data to be
encrypted.
*/
enum CompressionMode {
CompressionAuto, /*!< Only apply compression if that results in a shorter plaintext. */
CompressionAlways, /*!< Always apply compression. Note that for short inputs, a compression may result in longer data */
CompressionNever /*!< Never apply compression. */
};
/**
IntegrityProtectionMode describes measures taken to make it possible to detect problems with the data
or wrong decryption keys.
Measures involve adding a checksum or a cryptograhpic hash to the data to be encrypted. This
increases the length of the resulting cypertext, but makes it possible to check if the plaintext
appears to be valid after decryption.
*/
enum IntegrityProtectionMode {
ProtectionNone, /*!< The integerity of the encrypted data is not protected. It is not really possible to detect a wrong key, for instance. */
ProtectionChecksum,/*!< A simple checksum is used to verify that the data is in order. If not, an empty string is returned. */
ProtectionHash /*!< A cryptographic hash is used to verify the integrity of the data. This method produces a much stronger, but longer check */
};
/**
Error describes the type of error that occured.
*/
enum Error {
ErrorNoError, /*!< No error occurred. */
ErrorNoKeySet, /*!< No key was set. You can not encrypt or decrypt without a valid key. */
ErrorUnknownVersion, /*!< The version of this data is unknown, or the data is otherwise not valid. */
ErrorIntegrityFailed, /*!< The integrity check of the data failed. Perhaps the wrong key was used. */
};
/**
Constructor.
Constructs a SimpleCrypt instance without a valid key set on it.
*/
SimpleCrypt();
/**
Constructor.
Constructs a SimpleCrypt instance and initializes it with the given @arg key.
*/
explicit SimpleCrypt(quint64 key);
/**
(Re-) initializes the key with the given @arg key.
*/
void setKey(quint64 key);
/**
Returns true if SimpleCrypt has been initialized with a key.
*/
bool hasKey() const {return !m_keyParts.isEmpty();}
/**
Sets the compression mode to use when encrypting data. The default mode is Auto.
Note that decryption is not influenced by this mode, as the decryption recognizes
what mode was used when encrypting.
*/
void setCompressionMode(CompressionMode mode) {m_compressionMode = mode;}
/**
Returns the CompressionMode that is currently in use.
*/
CompressionMode compressionMode() const {return m_compressionMode;}
/**
Sets the integrity mode to use when encrypting data. The default mode is Checksum.
Note that decryption is not influenced by this mode, as the decryption recognizes
what mode was used when encrypting.
*/
void setIntegrityProtectionMode(IntegrityProtectionMode mode) {m_protectionMode = mode;}
/**
Returns the IntegrityProtectionMode that is currently in use.
*/
IntegrityProtectionMode integrityProtectionMode() const {return m_protectionMode;}
/**
Returns the last error that occurred.
*/
Error lastError() const {return m_lastError;}
/**
Encrypts the @arg plaintext string with the key the class was initialized with, and returns
a cyphertext the result. The result is a base64 encoded version of the binary array that is the
actual result of the string, so it can be stored easily in a text format.
*/
QString encryptToString(const QString& plaintext) ;
/**
Encrypts the @arg plaintext QByteArray with the key the class was initialized with, and returns
a cyphertext the result. The result is a base64 encoded version of the binary array that is the
actual result of the encryption, so it can be stored easily in a text format.
*/
QString encryptToString(QByteArray plaintext) ;
/**
Encrypts the @arg plaintext string with the key the class was initialized with, and returns
a binary cyphertext in a QByteArray the result.
This method returns a byte array, that is useable for storing a binary format. If you need
a string you can store in a text file, use encryptToString() instead.
*/
QByteArray encryptToByteArray(const QString& plaintext) ;
/**
Encrypts the @arg plaintext QByteArray with the key the class was initialized with, and returns
a binary cyphertext in a QByteArray the result.
This method returns a byte array, that is useable for storing a binary format. If you need
a string you can store in a text file, use encryptToString() instead.
*/
QByteArray encryptToByteArray(QByteArray plaintext) ;
/**
Decrypts a cyphertext string encrypted with this class with the set key back to the
plain text version.
If an error occured, such as non-matching keys between encryption and decryption,
an empty string or a string containing nonsense may be returned.
*/
QString decryptToString(const QString& cyphertext) ;
/**
Decrypts a cyphertext string encrypted with this class with the set key back to the
plain text version.
If an error occured, such as non-matching keys between encryption and decryption,
an empty string or a string containing nonsense may be returned.
*/
QByteArray decryptToByteArray(const QString& cyphertext) ;
/**
Decrypts a cyphertext binary encrypted with this class with the set key back to the
plain text version.
If an error occured, such as non-matching keys between encryption and decryption,
an empty string or a string containing nonsense may be returned.
*/
QString decryptToString(QByteArray cypher) ;
/**
Decrypts a cyphertext binary encrypted with this class with the set key back to the
plain text version.
If an error occured, such as non-matching keys between encryption and decryption,
an empty string or a string containing nonsense may be returned.
*/
QByteArray decryptToByteArray(QByteArray cypher) ;
//enum to describe options that have been used for the encryption. Currently only one, but
//that only leaves room for future extensions like adding a cryptographic hash...
enum CryptoFlag{CryptoFlagNone = 0,
CryptoFlagCompression = 0x01,
CryptoFlagChecksum = 0x02,
CryptoFlagHash = 0x04
};
Q_DECLARE_FLAGS(CryptoFlags, CryptoFlag);
private:
void splitKey();
quint64 m_key;
QVector<char> m_keyParts;
CompressionMode m_compressionMode;
IntegrityProtectionMode m_protectionMode;
Error m_lastError;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(SimpleCrypt::CryptoFlags)
#endif // SimpleCrypt_H

View file

@ -1,132 +1,132 @@
#include "jcesslclient.h"
jceSSLClient::jceSSLClient() : flag(false), packet("")
{
connect(this,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(checkErrors(QAbstractSocket::SocketError)));
connect(this,SIGNAL(connected()),this,SLOT(setConnected()));
connect(this,SIGNAL(encrypted()),this,SLOT(setEncrypted()));
connect(this,SIGNAL(disconnected()),this,SLOT(setDisconnected()));
}
bool jceSSLClient::makeConnect(std::string server, int port)
{
QEventLoop loop;
QObject::connect(this, SIGNAL(encrypted()), &loop, SLOT(quit()));
if (isConnected())
abort();
if (isOpen())
abort();
connectToHostEncrypted(server.c_str(), port);
loop.exec();
return isConnected();
}
bool jceSSLClient::makeDiconnect()
{
abort();
if (state() == QAbstractSocket::SocketState::ConnectedState)
{
flag = false;
}
else
flag = true;
return flag;
}
bool jceSSLClient::isConnected()
{
return flag;
}
bool jceSSLClient::sendData(std::string str)
{
if (isConnected()) //if connected
{
write(str.c_str(),str.length());
while (waitForBytesWritten());
return true;
}
return false;
}
/**
* @brief jceSSLClient::recieveData
* @param str this variable will store the recieved data
* @param fast true for LOGIN ONLY, false to retrieve all data
* @return true if recieved data bigger than zero
*/
bool jceSSLClient::recieveData(std::string &str, bool fast)
{
packet = "";
bool sflag = false;
if (fast) //fast connection, good for login only!!
{
QEventLoop loop;
connect(this, SIGNAL(readyRead()), &loop, SLOT(quit()));
connect(this, SIGNAL(readyRead()), this, SLOT(readIt()));
loop.exec();
disconnect(this, SIGNAL(readyRead()), &loop, SLOT(quit()));
disconnect(this, SIGNAL(readyRead()), this, SLOT(readIt()));
}
else
{
QString p;
while (waitForReadyRead(milisTimeOut))
{
do
{
p = readAll();
packet.append(p);
}while (p.size() > 0);
}
}
str = packet.toStdString();
if (str.size() > 0)
sflag = true;
return sflag;
}
void jceSSLClient::readIt()
{
QString p;
do
{
p = readAll();
packet.append(p);
}while (p.size() > 0);
}
void jceSSLClient::setConnected()
{
waitForEncrypted();
}
void jceSSLClient::setEncrypted()
{
setReadBufferSize(10000);
setSocketOption(QAbstractSocket::KeepAliveOption,1);
flag = true;
}
void jceSSLClient::setDisconnected()
{
abort();
flag = false;
}
void jceSSLClient::checkErrors(QAbstractSocket::SocketError)
{
}
#include "jcesslclient.h"
jceSSLClient::jceSSLClient() : flag(false), packet("")
{
connect(this,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(checkErrors(QAbstractSocket::SocketError)));
connect(this,SIGNAL(connected()),this,SLOT(setConnected()));
connect(this,SIGNAL(encrypted()),this,SLOT(setEncrypted()));
connect(this,SIGNAL(disconnected()),this,SLOT(setDisconnected()));
}
bool jceSSLClient::makeConnect(std::string server, int port)
{
QEventLoop loop;
QObject::connect(this, SIGNAL(encrypted()), &loop, SLOT(quit()));
if (isConnected())
abort();
if (isOpen())
abort();
connectToHostEncrypted(server.c_str(), port);
loop.exec();
return isConnected();
}
bool jceSSLClient::makeDiconnect()
{
abort();
if (state() == QAbstractSocket::SocketState::ConnectedState)
{
flag = false;
}
else
flag = true;
return flag;
}
bool jceSSLClient::isConnected()
{
return flag;
}
bool jceSSLClient::sendData(std::string str)
{
if (isConnected()) //if connected
{
write(str.c_str(),str.length());
while (waitForBytesWritten());
return true;
}
return false;
}
/**
* @brief jceSSLClient::recieveData
* @param str this variable will store the recieved data
* @param fast true for LOGIN ONLY, false to retrieve all data
* @return true if recieved data bigger than zero
*/
bool jceSSLClient::recieveData(std::string &str, bool fast)
{
packet = "";
bool sflag = false;
if (fast) //fast connection, good for login only!!
{
QEventLoop loop;
connect(this, SIGNAL(readyRead()), &loop, SLOT(quit()));
connect(this, SIGNAL(readyRead()), this, SLOT(readIt()));
loop.exec();
disconnect(this, SIGNAL(readyRead()), &loop, SLOT(quit()));
disconnect(this, SIGNAL(readyRead()), this, SLOT(readIt()));
}
else
{
QString p;
while (waitForReadyRead(milisTimeOut))
{
do
{
p = readAll();
packet.append(p);
}while (p.size() > 0);
}
}
str = packet.toStdString();
if (str.size() > 0)
sflag = true;
return sflag;
}
void jceSSLClient::readIt()
{
QString p;
do
{
p = readAll();
packet.append(p);
}while (p.size() > 0);
}
void jceSSLClient::setConnected()
{
waitForEncrypted();
}
void jceSSLClient::setEncrypted()
{
setReadBufferSize(10000);
setSocketOption(QAbstractSocket::KeepAliveOption,1);
flag = true;
}
void jceSSLClient::setDisconnected()
{
abort();
flag = false;
}
void jceSSLClient::checkErrors(QAbstractSocket::SocketError)
{
}

View file

@ -1,39 +1,39 @@
#ifndef JCESSLCLIENT_H
#define JCESSLCLIENT_H
#include <QObject>
#include <QSslSocket>
#include <QThread>
#include <QEventLoop>
#include <iostream>
#include <string>
#define milisTimeOut 3500
class jceSSLClient : QSslSocket
{
Q_OBJECT
public:
jceSSLClient();
bool makeConnect(std::string server,int port);
bool isConnected();
bool sendData(std::string str);
bool recieveData(std::string &str, bool fast);
bool makeDiconnect();
private slots:
void checkErrors(QAbstractSocket::SocketError);
void setConnected();
void setEncrypted();
void setDisconnected();
void readIt();
private:
bool flag;
QString packet;
};
#endif // JCESSLCLIENT_H
#ifndef JCESSLCLIENT_H
#define JCESSLCLIENT_H
#include <QObject>
#include <QSslSocket>
#include <QThread>
#include <QEventLoop>
#include <iostream>
#include <string>
#define milisTimeOut 3500
class jceSSLClient : QSslSocket
{
Q_OBJECT
public:
jceSSLClient();
bool makeConnect(std::string server,int port);
bool isConnected();
bool sendData(std::string str);
bool recieveData(std::string &str, bool fast);
bool makeDiconnect();
private slots:
void checkErrors(QAbstractSocket::SocketError);
void setConnected();
void setEncrypted();
void setDisconnected();
void readIt();
private:
bool flag;
QString packet;
};
#endif // JCESSLCLIENT_H

View file

@ -1,145 +1,153 @@
#include "csv_exporter.h"
CSV_Exporter::CSV_Exporter()
{
}
bool CSV_Exporter::exportCalendar(calendarSchedule *calSched)
{
qDebug() << "Getting path for csv file from user...";
QString filePath = getFileFath();
if(filePath == NULL) //User canceled
{
qDebug() << "User pressed Cancel... returning false";
return false;
}
qDebug() << "User Chose: " << filePath;
qDebug() << "Atempting to export the Schedule...";
QFile file(filePath);
if(!file.open(QIODevice::ReadWrite | QIODevice::Text))
{
qDebug() << "unable to open/create the file... maybe permissions error.";
return false;
}//else
QTextStream out(&file);
out << CSV_CALENDAR_HEADER << "\n";
for (calendarCourse *coursePtr: *(calSched->getCourses()))
{
// Subject,Start Date,Start Time,End Date,End Time,Description,Location
int day = coursePtr->getDay();
int startH = coursePtr->getHourBegin();
int startM = coursePtr->getMinutesBegin();
int endH = coursePtr->getHourEnd();
int endM = coursePtr->getMinutesEnd();
QString lecturer = QString(coursePtr->getLecturer().c_str()); //WHY YOU USED STD STRING?!
QString type = QString(coursePtr->getType().c_str());
QString name = QString(coursePtr->getName().c_str());
QString room = QString(coursePtr->getRoom().c_str());
QString line = makeLine(name, day, startH, startM, endH, endM, lecturer, room, type);
if(line != NULL)
out << line << char(0x0A);
}
out.flush();
file.close();
qDebug() << "Saved Successfuly! - HazZaA!";
return true;
}
QString CSV_Exporter::getFileFath()
{
QString fileName = QFileDialog::getSaveFileName();
if(fileName == "")
return NULL;
fileName.append(".csv");
return fileName;
}
QString CSV_Exporter::makeLine(QString name, int day, int startH, int startM, int endH, int endM, QString lecturer, QString room, QString type)
{
//Creating a CSV text line for Google Calendar/iCal/Outlook
// First day for semester 10/26/2014
QString CSV_line = "";
QString subject = "\"";
subject.append(name);
subject.append(" - ");
subject.append(type);
subject.append("\"");
QString date;
switch (day) {
case 1:
date = "10/26/2014";
break;
case 2:
date = "10/27/2014";
break;
case 3:
date = "10/28/2014";
break;
case 4:
date = "10/29/2014";
break;
case 5:
date = "10/30/2014";
break;
case 6:
date = "10/31/2014";
break;
default:
return NULL;
break;
}
QString start;
start.append(QString::number(startH));
start.append(":00");
//start.append(QString::number(startM));
start.append(":00");
QString end;
end.append(QString::number(endH));
end.append(":");
end.append(QString::number(endM));
end.append(":00");
QString description = "\"מרצה ";
description.append(lecturer);
description.append("\n");
description.append(" ב");
description.append(room);
description.append("\"");
//Create the Fucking Line
//Header: Subject,Start Date,Start Time,End Date,End Time,Description,Location
CSV_line.append(subject);
CSV_line.append(",");
CSV_line.append(date);
CSV_line.append(",");
CSV_line.append(start);
CSV_line.append(",");
CSV_line.append(date);
CSV_line.append(",");
CSV_line.append(end);
CSV_line.append(",");
CSV_line.append(description);
CSV_line.append(",");
CSV_line.append("\"JCE Jerusalem\"");
return CSV_line;
}
#include "csv_exporter.h"
CSV_Exporter::CSV_Exporter()
{
}
bool CSV_Exporter::exportCalendar(calendarSchedule *calSched)
{
qDebug() << "Getting path for csv file from user...";
QString filePath = getFileFath();
if(filePath == NULL) //User canceled
{
qDebug() << "User pressed Cancel... returning false";
return false;
}
qDebug() << "User Chose: " << filePath;
qDebug() << "Atempting to export the Schedule...";
QFile file(filePath);
if(!file.open(QIODevice::ReadWrite | QIODevice::Text))
{
qDebug() << "unable to open/create the file... maybe permissions error.";
return false;
}//else
QTextStream out(&file);
out << CSV_CALENDAR_HEADER << "\n";
for (calendarCourse *coursePtr: *(calSched->getCourses()))
{
// Subject,Start Date,Start Time,End Date,End Time,Description,Location
int day = coursePtr->getDay();
int startH = coursePtr->getHourBegin();
int startM = coursePtr->getMinutesBegin();
int endH = coursePtr->getHourEnd();
int endM = coursePtr->getMinutesEnd();
QString lecturer = QString(coursePtr->getLecturer().c_str()); //WHY YOU USED STD STRING?!
QString type = QString(coursePtr->getType().c_str());
QString name = QString(coursePtr->getName().c_str());
QString room = QString(coursePtr->getRoom().c_str());
QString line = makeLine(name, day, startH, startM, endH, endM, lecturer, room, type);
#ifndef _WIN32
if(line != NULL)
out << line << char(0x0D) << " ";
#elif __APPLE__ && __MACH__
if(line != NULL)
out << line << char(0x0D) << " ";
#elif __LINUX__
if(line != NULL)
out << line << char(0x0A);
#endif
}
out.flush();
file.close();
qDebug() << "Saved Successfuly! - HazZaA!";
return true;
}
QString CSV_Exporter::getFileFath()
{
QString fileName = QFileDialog::getSaveFileName();
if(fileName == "")
return NULL;
fileName.append(".csv");
return fileName;
}
QString CSV_Exporter::makeLine(QString name, int day, int startH, int startM, int endH, int endM, QString lecturer, QString room, QString type)
{
//Creating a CSV text line for Google Calendar/iCal/Outlook
// First day for semester 10/26/2014
QString CSV_line = "";
QString subject = "\"";
subject.append(name);
subject.append(" - ");
subject.append(type);
subject.append("\"");
QString date;
switch (day) {
case 1:
date = "10/26/2014";
break;
case 2:
date = "10/27/2014";
break;
case 3:
date = "10/28/2014";
break;
case 4:
date = "10/29/2014";
break;
case 5:
date = "10/30/2014";
break;
case 6:
date = "10/31/2014";
break;
default:
return NULL;
break;
}
QString start;
start.append(QString::number(startH));
start.append(":00");
//start.append(QString::number(startM));
start.append(":00");
QString end;
end.append(QString::number(endH));
end.append(":");
end.append(QString::number(endM));
end.append(":00");
QString description = "\"מרצה ";
description.append(lecturer);
description.append("\n");
description.append(" ב");
description.append(room);
description.append("\"");
//Create the Fucking Line
//Header: Subject,Start Date,Start Time,End Date,End Time,Description,Location
CSV_line.append(subject);
CSV_line.append(",");
CSV_line.append(date);
CSV_line.append(",");
CSV_line.append(start);
CSV_line.append(",");
CSV_line.append(date);
CSV_line.append(",");
CSV_line.append(end);
CSV_line.append(",");
CSV_line.append(description);
CSV_line.append(",");
CSV_line.append("\"JCE Jerusalem\"");
return CSV_line;
}

View file

@ -1,26 +1,26 @@
#ifndef CSV_EXPORTER_H
#define CSV_EXPORTER_H
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QString>
#include <QDebug>
#include "../Calendar/calendarSchedule.h"
#define CSV_CALENDAR_HEADER "Subject,Start Date,Start Time,End Date,End Time,Description,Location"
class CSV_Exporter
{
public:
CSV_Exporter();
static bool exportCalendar(calendarSchedule* calSched);
private:
static QString getFileFath();
static QString makeLine(QString name,int day,int startH,int startM,int endH,int endM,QString lecturer,QString room,QString type);
};
#endif // CSV_EXPORTER_H
#ifndef CSV_EXPORTER_H
#define CSV_EXPORTER_H
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QString>
#include <QDebug>
#include "../Calendar/calendarSchedule.h"
#define CSV_CALENDAR_HEADER "Subject,Start Date,Start Time,End Date,End Time,Description,Location"
class CSV_Exporter
{
public:
CSV_Exporter();
static bool exportCalendar(calendarSchedule* calSched);
private:
static QString getFileFath();
static QString makeLine(QString name,int day,int startH,int startM,int endH,int endM,QString lecturer,QString room,QString type);
};
#endif // CSV_EXPORTER_H

View file

@ -1,156 +1,156 @@
#include "calendarCourse.h"
calendarCourse::calendarCourse(int serial, std::string name, std::string type, std::string lecturer, double points,
double semesterHours, std::string dayAndHour,
std::string room) : Course(serial,name, type,points)
{
this->lecturer = lecturer;
this->semesterHours = semesterHours;
this->room = room;
setDayAndHour(dayAndHour);
}
void calendarCourse::setDayAndHour(std::string phrase)
{
int ctr = 0;
std::string temp = "";
QTime timetemp;
char *tok;
char* textToTok = strdup(phrase.c_str());
tok = strtok(textToTok, " -");
while(tok != NULL)
{
temp = tok;
switch (ctr)
{
case 0:
setDay(temp);
break;
case 1:
timetemp = QTime::fromString(QString::fromStdString(temp),"hh:mm");
setHourBegin(timetemp.hour());
setMinutesBegin(timetemp.minute());
break;
case 2:
timetemp = QTime::fromString(QString::fromStdString(temp),"hh:mm");
setHourEnd(timetemp.hour());
setMinutesEnd(timetemp.minute());
break;
}
ctr++;
tok = strtok(NULL, " -");
}
}
std::string calendarCourse::getLecturer() const
{
return lecturer;
}
void calendarCourse::setLecturer(const std::string &value)
{
lecturer = value;
}
double calendarCourse::getSemesterHours() const
{
return semesterHours;
}
void calendarCourse::setSemesterHours(double value)
{
semesterHours = value;
}
int calendarCourse::getHourBegin() const
{
return hourBegin;
}
void calendarCourse::setHourBegin(int value)
{
hourBegin = value;
}
int calendarCourse::getMinutesBegin() const
{
return minutesBegin;
}
void calendarCourse::setMinutesBegin(int value)
{
minutesBegin = value;
}
int calendarCourse::getHourEnd() const
{
return hourEnd;
}
void calendarCourse::setHourEnd(int value)
{
hourEnd = value;
}
int calendarCourse::getMinutesEnd() const
{
return minutesEnd;
}
void calendarCourse::setMinutesEnd(int value)
{
minutesEnd = value;
}
std::string calendarCourse::courseToString()
{
std::string courseText = "";
courseText += " " + std::to_string(this->getSerialNum());
courseText += " " + this->getName();
courseText += " " + this->getType();
courseText += " " + this->lecturer;
courseText += " " + std::to_string(this->getPoints());
courseText += " " + std::to_string(this->semesterHours);
courseText += " " + this->day;
courseText += " " + std::to_string(this->hourBegin) + ":" + std::to_string(this->minutesBegin) + "-" + std::to_string(this->hourEnd) + ":" + std::to_string(this->minutesEnd);
courseText += " " + this->room;
courseText += "\n";
return courseText;
}
int calendarCourse::getDay() const
{
return day;
}
void calendarCourse::setDay(const std::string &value)
{
std::string dayTemp = value.substr(0,2);
if (dayTemp.compare("\u05D0") == 0) //alef
day = 1;
else if (dayTemp.compare("\u05D1") == 0) //bet
day = 2;
else if (dayTemp.compare("\u05D2") == 0) //gimel
day = 3;
else if (dayTemp.compare("\u05D3") == 0) //dalet
day = 4;
else if (dayTemp.compare("\u05D4") == 0) //hey
day = 5;
else if (dayTemp.compare("\u05D5") == 0) //vav
day = 6;
else
day= -1;
}
std::string calendarCourse::getRoom() const
{
return room;
}
void calendarCourse::setRoom(const std::string &value)
{
room = value;
}
#include "calendarCourse.h"
calendarCourse::calendarCourse(int serial, std::string name, std::string type, std::string lecturer, double points,
double semesterHours, std::string dayAndHour,
std::string room) : Course(serial,name, type,points)
{
this->lecturer = lecturer;
this->semesterHours = semesterHours;
this->room = room;
setDayAndHour(dayAndHour);
}
void calendarCourse::setDayAndHour(std::string phrase)
{
int ctr = 0;
std::string temp = "";
QTime timetemp;
char *tok;
char* textToTok = strdup(phrase.c_str());
tok = strtok(textToTok, " -");
while(tok != NULL)
{
temp = tok;
switch (ctr)
{
case 0:
setDay(temp);
break;
case 1:
timetemp = QTime::fromString(QString::fromStdString(temp),"hh:mm");
setHourBegin(timetemp.hour());
setMinutesBegin(timetemp.minute());
break;
case 2:
timetemp = QTime::fromString(QString::fromStdString(temp),"hh:mm");
setHourEnd(timetemp.hour());
setMinutesEnd(timetemp.minute());
break;
}
ctr++;
tok = strtok(NULL, " -");
}
}
std::string calendarCourse::getLecturer() const
{
return lecturer;
}
void calendarCourse::setLecturer(const std::string &value)
{
lecturer = value;
}
double calendarCourse::getSemesterHours() const
{
return semesterHours;
}
void calendarCourse::setSemesterHours(double value)
{
semesterHours = value;
}
int calendarCourse::getHourBegin() const
{
return hourBegin;
}
void calendarCourse::setHourBegin(int value)
{
hourBegin = value;
}
int calendarCourse::getMinutesBegin() const
{
return minutesBegin;
}
void calendarCourse::setMinutesBegin(int value)
{
minutesBegin = value;
}
int calendarCourse::getHourEnd() const
{
return hourEnd;
}
void calendarCourse::setHourEnd(int value)
{
hourEnd = value;
}
int calendarCourse::getMinutesEnd() const
{
return minutesEnd;
}
void calendarCourse::setMinutesEnd(int value)
{
minutesEnd = value;
}
std::string calendarCourse::courseToString()
{
std::string courseText = "";
courseText += " " + std::to_string(this->getSerialNum());
courseText += " " + this->getName();
courseText += " " + this->getType();
courseText += " " + this->lecturer;
courseText += " " + std::to_string(this->getPoints());
courseText += " " + std::to_string(this->semesterHours);
courseText += " " + std::to_string(this->day);
courseText += " " + std::to_string(this->hourBegin) + ":" + std::to_string(this->minutesBegin) + "-" + std::to_string(this->hourEnd) + ":" + std::to_string(this->minutesEnd);
courseText += " " + this->room;
courseText += "\n";
return courseText;
}
int calendarCourse::getDay() const
{
return day;
}
void calendarCourse::setDay(const std::string &value)
{
std::string dayTemp = value.substr(0,2);
if (dayTemp.compare("\u05D0") == 0) //alef
day = 1;
else if (dayTemp.compare("\u05D1") == 0) //bet
day = 2;
else if (dayTemp.compare("\u05D2") == 0) //gimel
day = 3;
else if (dayTemp.compare("\u05D3") == 0) //dalet
day = 4;
else if (dayTemp.compare("\u05D4") == 0) //hey
day = 5;
else if (dayTemp.compare("\u05D5") == 0) //vav
day = 6;
else
day= -1;
}
std::string calendarCourse::getRoom() const
{
return room;
}
void calendarCourse::setRoom(const std::string &value)
{
room = value;
}

View file

@ -1,86 +1,86 @@
#include "calendarSchedule.h"
calendarSchedule::calendarSchedule()
{
QStringList days,hours;
QTextStream hourString;
QString a;
int startingHour = HOURS_BEGIN;
int endingHour = HOURS_END;
int academicHour = ACADEMIN_HOUR;
hourString.setString(&a);
for (int i = startingHour;i <= endingHour; ++i)
{
if (i < 10)
hourString << "0" << i << ":" << "00" << " - " << "0" << i << ":" << academicHour;
else
hourString << i << ":" << "00" << " - " << i << ":" << academicHour;
hours << QObject::tr(hourString.string()->toStdString().c_str());
a = "";
}
days << QObject::tr("Sunday") << QObject::tr("Monday") << QObject::tr("Tuesday") << QObject::tr("Wednesday") << QObject::tr("Thursday") << QObject::tr("Friday");
setRowCount(endingHour - startingHour + 1);
setColumnCount(6);
setLayoutDirection(Qt::LayoutDirection::RightToLeft);\
setHorizontalHeaderLabels(days);
setVerticalHeaderLabels(hours);
setEditTriggers(QAbstractItemView::NoEditTriggers);
horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}
void calendarSchedule::setPage(std::string html)
{
CalendarPage::setPage(html);
insertCourseIntoTable();
}
void calendarSchedule::clearTableItems()
{
int i,j;
for (i = 0; i < rowCount(); i++)
for (j = 0; j < columnCount(); j++)
if (this->takeItem(i,j) != NULL)
delete this->takeItem(i,j);
horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}
void calendarSchedule::insertCourseIntoTable()
{
QTableWidgetItem *item;
QString courseString;
int currentHour,currentDay,blocksNumer;
int row,col;
for (calendarCourse *coursePtr: *getCourses())
{
courseString = "";
currentHour = coursePtr->getHourBegin();
currentDay = coursePtr->getDay();
blocksNumer = coursePtr->getHourEnd() - coursePtr->getHourBegin();
while (blocksNumer >= 0)
{
row = currentHour % HOURS_BEGIN;
col = currentDay-1;
courseString = (QString::fromStdString(coursePtr->getName() + " \n" + coursePtr->getLecturer() + " \n" + coursePtr->getRoom()));
item = new QTableWidgetItem(courseString);
if (this->takeItem(row,col) != NULL)
delete this->takeItem(row,col);
this->setItem(row,col,item);
currentHour++;
--blocksNumer;
}
}
horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
}
#include "calendarSchedule.h"
calendarSchedule::calendarSchedule()
{
QStringList days,hours;
QTextStream hourString;
QString a;
int startingHour = HOURS_BEGIN;
int endingHour = HOURS_END;
int academicHour = ACADEMIN_HOUR;
hourString.setString(&a);
for (int i = startingHour;i <= endingHour; ++i)
{
if (i < 10)
hourString << "0" << i << ":" << "00" << " - " << "0" << i << ":" << academicHour;
else
hourString << i << ":" << "00" << " - " << i << ":" << academicHour;
hours << QObject::tr(hourString.string()->toStdString().c_str());
a = "";
}
days << QObject::tr("Sunday") << QObject::tr("Monday") << QObject::tr("Tuesday") << QObject::tr("Wednesday") << QObject::tr("Thursday") << QObject::tr("Friday");
setRowCount(endingHour - startingHour + 1);
setColumnCount(6);
setLayoutDirection(Qt::LayoutDirection::RightToLeft);\
setHorizontalHeaderLabels(days);
setVerticalHeaderLabels(hours);
setEditTriggers(QAbstractItemView::NoEditTriggers);
horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}
void calendarSchedule::setPage(std::string html)
{
CalendarPage::setPage(html);
insertCourseIntoTable();
}
void calendarSchedule::clearTableItems()
{
int i,j;
for (i = 0; i < rowCount(); i++)
for (j = 0; j < columnCount(); j++)
if (this->takeItem(i,j) != NULL)
delete this->takeItem(i,j);
horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}
void calendarSchedule::insertCourseIntoTable()
{
QTableWidgetItem *item;
QString courseString;
int currentHour,currentDay,blocksNumer;
int row,col;
for (calendarCourse *coursePtr: *getCourses())
{
courseString = "";
currentHour = coursePtr->getHourBegin();
currentDay = coursePtr->getDay();
blocksNumer = coursePtr->getHourEnd() - coursePtr->getHourBegin();
while (blocksNumer >= 0)
{
row = currentHour % HOURS_BEGIN;
col = currentDay-1;
courseString = (QString::fromStdString(coursePtr->getName() + " \n" + coursePtr->getLecturer() + " \n" + coursePtr->getRoom()));
item = new QTableWidgetItem(courseString);
if (this->takeItem(row,col) != NULL)
delete this->takeItem(row,col);
this->setItem(row,col,item);
currentHour++;
--blocksNumer;
}
}
horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
}

View file

@ -1,34 +1,34 @@
#ifndef CALENDARSCHEDULE_H
#define CALENDARSCHEDULE_H
#include <QTableWidget>
#include <QTextStream>
#include <iostream>
#include "calendarPage.h"
#include <iostream>
#include <QHeaderView>
#define HOURS_BEGIN 8
#define HOURS_END 20
#define ACADEMIN_HOUR 45
class calendarSchedule : public QTableWidget, public CalendarPage
{
Q_OBJECT
public:
calendarSchedule();
~calendarSchedule() { clearTableItems(); }
void setPage(std::string html);
void clearTableItems();
signals:
public slots:
private:
void insertCourseIntoTable();
};
#endif // CALENDARSCHEDULE_H
#ifndef CALENDARSCHEDULE_H
#define CALENDARSCHEDULE_H
#include <QTableWidget>
#include <QTextStream>
#include <iostream>
#include "calendarPage.h"
#include <iostream>
#include <QHeaderView>
#define HOURS_BEGIN 8
#define HOURS_END 20
#define ACADEMIN_HOUR 45
class calendarSchedule : public QTableWidget, public CalendarPage
{
Q_OBJECT
public:
calendarSchedule();
~calendarSchedule() { clearTableItems(); }
void setPage(std::string html);
void clearTableItems();
signals:
public slots:
private:
void insertCourseIntoTable();
};
#endif // CALENDARSCHEDULE_H

View file

@ -1,36 +1,36 @@
#include "gradeCourse.h"
gradeCourse::gradeCourse(int serial,std::string name, std::string type, double points, double hours, double grade, std::string additions) : Course(serial,name,type,points)
{
this->hours = hours;
this->grade = grade;
this->additions = additions;
}
gradeCourse::~gradeCourse()
{
}
double gradeCourse::getGrade() const
{
double noGrade = NO_GRADE_YET;
if (grade == noGrade)
return 0;
else
return this->grade;
}
void gradeCourse::setHours(double hours)
{
this->hours = hours;
}
void gradeCourse::setGrade(double grade)
{
this->grade = grade;
}
void gradeCourse::setAdditions(std::string additions)
{
this->additions = additions;
}
#include "gradeCourse.h"
gradeCourse::gradeCourse(int serial,std::string name, std::string type, double points, double hours, double grade, std::string additions) : Course(serial,name,type,points)
{
this->hours = hours;
this->grade = grade;
this->additions = additions;
}
gradeCourse::~gradeCourse()
{
}
double gradeCourse::getGrade() const
{
double noGrade = NO_GRADE_YET;
if (grade == noGrade)
return 0;
else
return this->grade;
}
void gradeCourse::setHours(double hours)
{
this->hours = hours;
}
void gradeCourse::setGrade(double grade)
{
this->grade = grade;
}
void gradeCourse::setAdditions(std::string additions)
{
this->additions = additions;
}

View file

@ -1,53 +1,53 @@
#ifndef GRADE_COURSE_H
#define GRADE_COURSE_H
/* This Code Made By Sagi Dayan
* SagiDayan@gmail.com
*
* Minor changes has been made by Liran Ben Gida
* LiranBG@gmail.com
*/
#include "../course.h"
#include <string>
#include <iostream>
#include <list>
#define COURSE_FIELDS 7
#define NO_GRADE_YET 101;
class gradeCourse : public Course {
public:
enum CourseScheme
{
SERIAL,
NAME,
TYPE,
POINTS,
HOURS,
GRADE,
ADDITION
};
gradeCourse(int serial, std::string name, std::string type, double points,double hours, double grade, std::string additions);
~gradeCourse();
double getHours() const {return this->hours;}
double getGrade() const ;
std::string getAddidtions() const {return this->additions;}
void setHours(double hours);
void setGrade(double grade);
void setAdditions(std::string additions);
private:
double hours;
double grade;
std::string additions;
};
#endif
#ifndef GRADE_COURSE_H
#define GRADE_COURSE_H
/* This Code Made By Sagi Dayan
* SagiDayan@gmail.com
*
* Minor changes has been made by Liran Ben Gida
* LiranBG@gmail.com
*/
#include "../course.h"
#include <string>
#include <iostream>
#include <list>
#define COURSE_FIELDS 7
#define NO_GRADE_YET 101;
class gradeCourse : public Course {
public:
enum CourseScheme
{
SERIAL,
NAME,
TYPE,
POINTS,
HOURS,
GRADE,
ADDITION
};
gradeCourse(int serial, std::string name, std::string type, double points,double hours, double grade, std::string additions);
~gradeCourse();
double getHours() const {return this->hours;}
double getGrade() const ;
std::string getAddidtions() const {return this->additions;}
void setHours(double hours);
void setGrade(double grade);
void setAdditions(std::string additions);
private:
double hours;
double grade;
std::string additions;
};
#endif

View file

@ -1,172 +1,172 @@
#include "gradePage.h"
GradePage::GradePage(std::string html) : Page()
{
this->courses = new std::list<gradeCourse*>();
this->tempHtml = getString(html);
this->tempHtml = tokenToLines(this->tempHtml);
coursesListInit(this->tempHtml);
}
GradePage::~GradePage()
{
for(Course* c : *courses)
delete c;
delete courses;
}
void GradePage::addCourse(gradeCourse *a)
{
GradePage::courses->push_back(a);
return;
}
void GradePage::removeCourse(std::string courseSerialID)
{
for(gradeCourse* c : *courses)
{
if (c->getSerialNum() == stoi(courseSerialID))
{
courses->remove(c);
delete c;
return;
}
}
}
void GradePage::coursesListInit(std::string& linesTokinzedString)
{
std::list<std::string> stringHolder;
std::string temp;
gradeCourse* cTemp = NULL;
char* tok;
char* textToTok = strdup(linesTokinzedString.c_str());
tok = strtok(textToTok,"\n");
while (tok != NULL)
{
temp = tok;
stringHolder.push_back(temp);
tok = strtok(NULL, "\n");
}
for(std::string temp: stringHolder)
{
cTemp = lineToCourse(temp);
if (cTemp != NULL)
addCourse(cTemp);
}
}
std::string GradePage::tokenToLines(std::string& textToPhrase)
{
int ctr = 0;
std::string temp = "";
char *tok;
char* textToTok = strdup(textToPhrase.c_str());
tok = strtok(textToTok, "\n");
while(tok != NULL)
{
//amount of data before the actual needed data and no empty lines
if (strcmp(tok," \t ") != 0)
{
temp += tok;
temp += "\n";
}
ctr++;
tok = strtok(NULL, "\n");
}
return temp;
}
gradeCourse* GradePage::lineToCourse(std::string line)
{
gradeCourse *tempC = NULL;
std::string templinearray[COURSE_FIELDS];//[serial,name,type,points,hours,grade,additions]
int serial;
double points,hours,grade;
std::string name,type, additions;
std::string tempS = "";
int i = 0;
char* tok;
char* cLine = strdup(line.c_str());
tok = strtok(cLine, "\t");
while(tok != NULL)
{
tempS = tok;
if (i == 1) //skip the tokenizing loop just once
{
tempS = "";
char *tokTemp;
tokTemp = tok;
while (!(isdigit((int)*tokTemp)))
tokTemp++;
while (isdigit((int)*tokTemp))
{
tempS += *tokTemp;
tokTemp++;
}
templinearray[i-1] = tempS;
templinearray[i] = tokTemp;
}
else if (i > 1)
templinearray[i] = tempS;
i++;
tok=strtok(NULL, "\t");
}
if (templinearray[0] == "") //empty phrasing
return NULL;
serial = stoi(templinearray[gradeCourse::CourseScheme::SERIAL]);
name = templinearray[gradeCourse::CourseScheme::NAME];
type = templinearray[gradeCourse::CourseScheme::TYPE];
points = stod(templinearray[gradeCourse::CourseScheme::POINTS]);
hours = stod(templinearray[gradeCourse::CourseScheme::HOURS]);
if (isGradedYet(templinearray[gradeCourse::CourseScheme::GRADE]))
grade = stod(templinearray[gradeCourse::CourseScheme::GRADE]);
else
grade = NO_GRADE_YET;
additions = templinearray[gradeCourse::CourseScheme::ADDITION];
tempC = new gradeCourse(serial,name,type,points,hours,grade,additions);
return tempC;
}
//checking if one of the chars inside grade is not a number
bool GradePage::isGradedYet(std::string grade)
{
if (strlen(grade.c_str()) <= 1)
return false;
for (char c: grade)
{
if (c == '\0')
break;
if (((!isdigit((int)c)) && (!isspace((int)c)))) //48 = 0, 57 = 9
return false;
}
return true;
}
double GradePage::getAvg()
{
double avg = 0;
double points = 0;
for(gradeCourse* c : *courses)
{
if ((c->getGrade() != 0))
{
avg += c->getGrade() * c->getPoints();
points += c->getPoints();
}
}
avg /= points;
return avg;
}
#include "gradePage.h"
GradePage::GradePage(std::string html) : Page()
{
this->courses = new std::list<gradeCourse*>();
this->tempHtml = getString(html);
this->tempHtml = tokenToLines(this->tempHtml);
coursesListInit(this->tempHtml);
}
GradePage::~GradePage()
{
for(Course* c : *courses)
delete c;
delete courses;
}
void GradePage::addCourse(gradeCourse *a)
{
GradePage::courses->push_back(a);
return;
}
void GradePage::removeCourse(std::string courseSerialID)
{
for(gradeCourse* c : *courses)
{
if (c->getSerialNum() == stoi(courseSerialID))
{
courses->remove(c);
delete c;
return;
}
}
}
void GradePage::coursesListInit(std::string& linesTokinzedString)
{
std::list<std::string> stringHolder;
std::string temp;
gradeCourse* cTemp = NULL;
char* tok;
char* textToTok = strdup(linesTokinzedString.c_str());
tok = strtok(textToTok,"\n");
while (tok != NULL)
{
temp = tok;
stringHolder.push_back(temp);
tok = strtok(NULL, "\n");
}
for(std::string temp: stringHolder)
{
cTemp = lineToCourse(temp);
if (cTemp != NULL)
addCourse(cTemp);
}
}
std::string GradePage::tokenToLines(std::string& textToPhrase)
{
int ctr = 0;
std::string temp = "";
char *tok;
char* textToTok = strdup(textToPhrase.c_str());
tok = strtok(textToTok, "\n");
while(tok != NULL)
{
//amount of data before the actual needed data and no empty lines
if (strcmp(tok," \t ") != 0)
{
temp += tok;
temp += "\n";
}
ctr++;
tok = strtok(NULL, "\n");
}
return temp;
}
gradeCourse* GradePage::lineToCourse(std::string line)
{
gradeCourse *tempC = NULL;
std::string templinearray[COURSE_FIELDS];//[serial,name,type,points,hours,grade,additions]
int serial;
double points,hours,grade;
std::string name,type, additions;
std::string tempS = "";
int i = 0;
char* tok;
char* cLine = strdup(line.c_str());
tok = strtok(cLine, "\t");
while(tok != NULL)
{
tempS = tok;
if (i == 1) //skip the tokenizing loop just once
{
tempS = "";
char *tokTemp;
tokTemp = tok;
while (!(isdigit((int)*tokTemp)))
tokTemp++;
while (isdigit((int)*tokTemp))
{
tempS += *tokTemp;
tokTemp++;
}
templinearray[i-1] = tempS;
templinearray[i] = tokTemp;
}
else if (i > 1)
templinearray[i] = tempS;
i++;
tok=strtok(NULL, "\t");
}
if (templinearray[0] == "") //empty phrasing
return NULL;
serial = stoi(templinearray[gradeCourse::CourseScheme::SERIAL]);
name = templinearray[gradeCourse::CourseScheme::NAME];
type = templinearray[gradeCourse::CourseScheme::TYPE];
points = stod(templinearray[gradeCourse::CourseScheme::POINTS]);
hours = stod(templinearray[gradeCourse::CourseScheme::HOURS]);
if (isGradedYet(templinearray[gradeCourse::CourseScheme::GRADE]))
grade = stod(templinearray[gradeCourse::CourseScheme::GRADE]);
else
grade = NO_GRADE_YET;
additions = templinearray[gradeCourse::CourseScheme::ADDITION];
tempC = new gradeCourse(serial,name,type,points,hours,grade,additions);
return tempC;
}
//checking if one of the chars inside grade is not a number
bool GradePage::isGradedYet(std::string grade)
{
if (strlen(grade.c_str()) <= 1)
return false;
for (char c: grade)
{
if (c == '\0')
break;
if (((!isdigit((int)c)) && (!isspace((int)c)))) //48 = 0, 57 = 9
return false;
}
return true;
}
double GradePage::getAvg()
{
double avg = 0;
double points = 0;
for(gradeCourse* c : *courses)
{
if ((c->getGrade() != 0))
{
avg += c->getGrade() * c->getPoints();
points += c->getPoints();
}
}
avg /= points;
return avg;
}

View file

@ -1,45 +1,45 @@
#ifndef GRADE_PAGE_H
#define GRADE_PAGE_H
/* This Code Made By Sagi Dayan
* SagiDayan@gmail.com
*
* Minor changes has been made by Liran Ben Gida
* LiranBG@gmail.com
*/
#include "../page.h"
#include "../Grades/gradeCourse.h"
#include <list>
#include <string.h> //strlen and strtok to phrase the html file
#include <ctype.h> //checks if character is numeric
class GradePage : public Page
{
public:
GradePage(std::string html);
~GradePage();
void addCourse(gradeCourse *);
void removeCourse(std::string courseSerialID);
double getAvg();
std::list<gradeCourse*>* getCourses() { return courses; }
private:
std::string tokenToLines(std::string& textToPhrase);
void coursesListInit(std::string& linesTokinzedString);
gradeCourse* lineToCourse(std::string line);
bool isGradedYet(std::string grade);
std::list<gradeCourse*>* courses;
std::string tempHtml;
};
#endif
#ifndef GRADE_PAGE_H
#define GRADE_PAGE_H
/* This Code Made By Sagi Dayan
* SagiDayan@gmail.com
*
* Minor changes has been made by Liran Ben Gida
* LiranBG@gmail.com
*/
#include "../page.h"
#include "../Grades/gradeCourse.h"
#include <list>
#include <string.h> //strlen and strtok to phrase the html file
#include <ctype.h> //checks if character is numeric
class GradePage : public Page
{
public:
GradePage(std::string html);
~GradePage();
void addCourse(gradeCourse *);
void removeCourse(std::string courseSerialID);
double getAvg();
std::list<gradeCourse*>* getCourses() { return courses; }
private:
std::string tokenToLines(std::string& textToPhrase);
void coursesListInit(std::string& linesTokinzedString);
gradeCourse* lineToCourse(std::string line);
bool isGradedYet(std::string grade);
std::list<gradeCourse*>* courses;
std::string tempHtml;
};
#endif

View file

@ -1,49 +1,49 @@
#ifndef COURSE_H
#define COURSE_H
/* This Code Made By Sagi Dayan
* SagiDayan@gmail.com
*
* minor changes by Liran Ben Gida
* LiranBG@gmail.com
*/
#include <string>
#include <iostream>
#include <list>
class Course {
public:
Course(int serial,std::string name, std::string type, double points) {
this->serialNum = serial;
this->name = name;
this->type = type;
this->points = points;
}
virtual ~Course() { }
int getSerialNum() const {return this->serialNum;}
virtual std::string getName() const {return this->name;}
virtual std::string getType() const {return this->type;}
virtual double getPoints() const {return this->points;}
virtual void setName(std::string name) { this->name = name;}
virtual void setType(std::string type){ this->type = type;}
virtual void setPoints(double points){ this->points = points;}
private:
int serialNum;
std::string name;
std::string type;
double points;
};
#endif
#ifndef COURSE_H
#define COURSE_H
/* This Code Made By Sagi Dayan
* SagiDayan@gmail.com
*
* minor changes by Liran Ben Gida
* LiranBG@gmail.com
*/
#include <string>
#include <iostream>
#include <list>
class Course {
public:
Course(int serial,std::string name, std::string type, double points) {
this->serialNum = serial;
this->name = name;
this->type = type;
this->points = points;
}
virtual ~Course() { }
int getSerialNum() const {return this->serialNum;}
virtual std::string getName() const {return this->name;}
virtual std::string getType() const {return this->type;}
virtual double getPoints() const {return this->points;}
virtual void setName(std::string name) { this->name = name;}
virtual void setType(std::string type){ this->type = type;}
virtual void setPoints(double points){ this->points = points;}
private:
int serialNum;
std::string name;
std::string type;
double points;
};
#endif

View file

@ -1,144 +1,144 @@
#include "page.h"
Page::Page()
{
}
std::string Page::getString(std::string& htmlToPhrased)
{
makeText(htmlToPhrased);
return this->text;
}
void Page::makeText(std::string& html)
{
int index = 0;
index = runToActualText(html, index); //set index into the actual place where the data is
manageTableContent(html, index);
}
int Page::runToActualText(std::string& from, int index)
{
while (index < (int)from.length())
{
if (from[index] == '<')
{
if (from.substr(index,7) == "<tbody>")
return index+7;
}
index++;
}
// while(index < (int)from.length())
// {
// if(from[index] == '<')
// {
// index++;
// if(from[index] == '!')
// {
// //!--FileName
// std::string bodyTag = from.substr(index, 11); //!--FileName
// if(bodyTag == "!--FileName") //check if the tag is body tag
// {
// while(from[index] != '>')
// index++;
// return index;
// }
// }
// }
// index++;
//}
return -1;
}
void Page::manageTableContent(std::string& html, int index)
{
std::string temp;
for (int i = index; i < (int)html.length(); i++)
{
if(html[i] == '<')
{
//<tr> / <td> / <th>
std::string endofTable = "</tbody>";
std::string tableTag = html.substr(i, 4); //legth of "tr/td"
if(tableTag == "<tr>")
{
temp += "\n"; //new row -> new line
i = stitchText(html, temp, i+4);
if(i == -1) //EOF
break;
}
else if(tableTag == "<td>" || tableTag == "<th>")
{
temp += "\t"; // new cell -> tab between data
if (html.substr(i, 6) == "<td><a") //link to lecturer portal, need to be deleted
{
i += 6;
while (html.at(++i) != '>');
i = stitchText(html, temp, i+1);
}
else
i = stitchText(html, temp, i+4);
if (i == -1) //EOF
break;
}
else if(tableTag == "<td ") // a Year title (in grades table)
{
temp += "\t";
while(html[i] != '>')
i++;
i = stitchText(html, temp, i+1);
}
else if (html.substr(i,(endofTable).length()) == endofTable) //is end of table
{
break;
}
}
}
this->text = temp;
}
int Page::stitchText(std::string& from, std::string& to, int index)
{
if (from[index] == '<')
{
std::string bTag = from.substr(index, 3);
if (bTag != "<b>")
return index-1; //go back one step - for the main function to inc i
index += 3;
}
while (from[index] != '<' && index < (int)from.length())
{
if (from[index] == '&')
{
//&nbsp;
std::string nbspChr = from.substr(index, 6);
if (nbspChr == "&nbsp;")
{
index += 5;
from.at(index) = ' ';
}
}
if (endOfString(index,(int) from.length()))
return -1; //EOF
else if (from[index] == '<')
return index - 1; //go back one step - for the main function to inc i
if (from[index] != '\n') //check the actuall data before continue
to += from[index];
index++;
}
return index-1;
}
bool Page::endOfString(int index, int length)
{
if(index < length)
return false;
return true;
}
#include "page.h"
Page::Page()
{
}
std::string Page::getString(std::string& htmlToPhrased)
{
makeText(htmlToPhrased);
return this->text;
}
void Page::makeText(std::string& html)
{
int index = 0;
index = runToActualText(html, index); //set index into the actual place where the data is
manageTableContent(html, index);
}
int Page::runToActualText(std::string& from, int index)
{
while (index < (int)from.length())
{
if (from[index] == '<')
{
if (from.substr(index,7) == "<tbody>")
return index+7;
}
index++;
}
// while(index < (int)from.length())
// {
// if(from[index] == '<')
// {
// index++;
// if(from[index] == '!')
// {
// //!--FileName
// std::string bodyTag = from.substr(index, 11); //!--FileName
// if(bodyTag == "!--FileName") //check if the tag is body tag
// {
// while(from[index] != '>')
// index++;
// return index;
// }
// }
// }
// index++;
//}
return -1;
}
void Page::manageTableContent(std::string& html, int index)
{
std::string temp;
for (int i = index; i < (int)html.length(); i++)
{
if(html[i] == '<')
{
//<tr> / <td> / <th>
std::string endofTable = "</tbody>";
std::string tableTag = html.substr(i, 4); //legth of "tr/td"
if(tableTag == "<tr>")
{
temp += "\n"; //new row -> new line
i = stitchText(html, temp, i+4);
if(i == -1) //EOF
break;
}
else if(tableTag == "<td>" || tableTag == "<th>")
{
temp += "\t"; // new cell -> tab between data
if (html.substr(i, 6) == "<td><a") //link to lecturer portal, need to be deleted
{
i += 6;
while (html.at(++i) != '>');
i = stitchText(html, temp, i+1);
}
else
i = stitchText(html, temp, i+4);
if (i == -1) //EOF
break;
}
else if(tableTag == "<td ") // a Year title (in grades table)
{
temp += "\t";
while(html[i] != '>')
i++;
i = stitchText(html, temp, i+1);
}
else if (html.substr(i,(endofTable).length()) == endofTable) //is end of table
{
break;
}
}
}
this->text = temp;
}
int Page::stitchText(std::string& from, std::string& to, int index)
{
if (from[index] == '<')
{
std::string bTag = from.substr(index, 3);
if (bTag != "<b>")
return index-1; //go back one step - for the main function to inc i
index += 3;
}
while (from[index] != '<' && index < (int)from.length())
{
if (from[index] == '&')
{
//&nbsp;
std::string nbspChr = from.substr(index, 6);
if (nbspChr == "&nbsp;")
{
index += 5;
from.at(index) = ' ';
}
}
if (endOfString(index,(int) from.length()))
return -1; //EOF
else if (from[index] == '<')
return index - 1; //go back one step - for the main function to inc i
if (from[index] != '\n') //check the actuall data before continue
to += from[index];
index++;
}
return index-1;
}
bool Page::endOfString(int index, int length)
{
if(index < length)
return false;
return true;
}

View file

@ -1,39 +1,39 @@
#ifndef PAGE_H
#define PAGE_H
/* This Code Made By Sagi Dayan
* SagiDayan@gmail.com
*
* Minor changes has been made by Liran Ben Gida
* LiranBG@gmail.com
*/
#include <iostream>
#include <string>
class Page
{
public:
~Page() {}
protected:
Page();
std::string getString(std::string& htmlToPhrased);
void makeText(std::string& html);
private:
int runToActualText(std::string& from, int index);
void manageTableContent(std::string& html, int index);
int stitchText(std::string& from, std::string& to, int index);
bool endOfString(int index, int length);
std::string text;
std::string title;
};
#endif
#ifndef PAGE_H
#define PAGE_H
/* This Code Made By Sagi Dayan
* SagiDayan@gmail.com
*
* Minor changes has been made by Liran Ben Gida
* LiranBG@gmail.com
*/
#include <iostream>
#include <string>
class Page
{
public:
~Page() {}
protected:
Page();
std::string getString(std::string& htmlToPhrased);
void makeText(std::string& html);
private:
int runToActualText(std::string& from, int index);
void manageTableContent(std::string& html, int index);
int stitchText(std::string& from, std::string& to, int index);
bool endOfString(int index, int length);
std::string text;
std::string title;
};
#endif

View file

@ -1,87 +1,87 @@
#ifndef JCELOGINHTMLSCRIPTS_H
#define JCELOGINHTMLSCRIPTS_H
#include <string>
#define dst_host "yedion.jce.ac.il"
#define dst_port 443
#include "./src/jceSettings/user.h"
class jceLoginHtmlScripts
{
private:
jceLoginHtmlScripts();
public:
static std::string makeRequest(std::string parameters)
{
std::string msg;
msg = "POST /yedion/fireflyweb.aspx HTTP/1.1\r\n";
msg += "Host: " + std::string(dst_host) + "\r\n";
msg += "Content-Type: application/x-www-form-urlencoded\r\n";
msg += "Content-Length: " + to_string(parameters.length()) + "\r\n";
msg += "Proxy-Connection: Keep-Alive\r\n";
msg += "Accept-Charset: UTF-8";
msg += "Accept: text/plain\r\n";
msg += "Connection: Keep-Alive\r\n";
msg += "\r\n";
msg += parameters;
return msg;
}
const static std::string getFirstValidationStep(const user &usr)
{
std::string parameters = "?appname=BSHITA&prgname=LoginValidation&arguments=-N";
parameters += usr.getUsername();
parameters += ",-N";
parameters += usr.getPassword();
return parameters;
}
const static std::string getSecondValidationStep(const user &usr)
{
std::string parameters;
parameters = "prgname=LoginValidtion1&Arguments=-N";
parameters += usr.getUserID();
parameters += ",-A,-N";
parameters += usr.getHashedPassword();
parameters += ",-A,-A";
return parameters;
}
const static std::string getGradesPath(const user &usr,
int fromYear,
int toYear,
int fromSemester,
int toSemester)
{
std::string parameters;
parameters = "PRGNAME=HADPASAT_MISMAHIM_LETALMID&ARGUMENTS=TZ,-N4,R1C2,R1C4,R1C1,R1C3,-A,-A,R1C5,-A,UNIQ&";
parameters += "TZ=" + usr.getUserID() + "&";
parameters += "UNIQ=" + usr.getHashedPassword() + "&";
parameters += "R1C2=" + std::to_string(fromYear) + "&";
parameters += "R1C1=" + std::to_string(toYear) + "&";
parameters += "R1C3=" + std::to_string(toSemester) + "&";
parameters += "R1C4=" + std::to_string(fromSemester) + "&";
parameters += "R1C5=0";
return parameters;
}
const static std::string getCalendar(const user &usr,int year, int semester)
{
std::string parameters;
parameters = "PRGNAME=Bitsua_maarechet_shaot&ARGUMENTS=TZ,UNIQ,MisparSheilta,R1C1,R1C2&";
parameters += "TZ=" + usr.getUserID() + "&";
parameters += "UNIQ=" + usr.getHashedPassword() + "&";
parameters += "MisparSheilta=3&";
parameters += "R1C1=" + std::to_string(year) + "&";
parameters += "R1C2=" + std::to_string(semester) + "&";
return parameters;
}
};
#endif // JCELOGINHTMLSCRIPTS_H
#ifndef JCELOGINHTMLSCRIPTS_H
#define JCELOGINHTMLSCRIPTS_H
#include <string>
#define dst_host "yedion.jce.ac.il"
#define dst_port 443
#include "./src/jceSettings/user.h"
class jceLoginHtmlScripts
{
private:
jceLoginHtmlScripts();
public:
static std::string makeRequest(std::string parameters)
{
std::string msg;
msg = "POST /yedion/fireflyweb.aspx HTTP/1.1\r\n";
msg += "Host: " + std::string(dst_host) + "\r\n";
msg += "Content-Type: application/x-www-form-urlencoded\r\n";
msg += "Content-Length: " + to_string(parameters.length()) + "\r\n";
msg += "Proxy-Connection: Keep-Alive\r\n";
msg += "Accept-Charset: UTF-8";
msg += "Accept: text/plain\r\n";
msg += "Connection: Keep-Alive\r\n";
msg += "\r\n";
msg += parameters;
return msg;
}
const static std::string getFirstValidationStep(const user &usr)
{
std::string parameters = "?appname=BSHITA&prgname=LoginValidation&arguments=-N";
parameters += usr.getUsername();
parameters += ",-N";
parameters += usr.getPassword();
return parameters;
}
const static std::string getSecondValidationStep(const user &usr)
{
std::string parameters;
parameters = "prgname=LoginValidtion1&Arguments=-N";
parameters += usr.getUserID();
parameters += ",-A,-N";
parameters += usr.getHashedPassword();
parameters += ",-A,-A";
return parameters;
}
const static std::string getGradesPath(const user &usr,
int fromYear,
int toYear,
int fromSemester,
int toSemester)
{
std::string parameters;
parameters = "PRGNAME=HADPASAT_MISMAHIM_LETALMID&ARGUMENTS=TZ,-N4,R1C2,R1C4,R1C1,R1C3,-A,-A,R1C5,-A,UNIQ&";
parameters += "TZ=" + usr.getUserID() + "&";
parameters += "UNIQ=" + usr.getHashedPassword() + "&";
parameters += "R1C2=" + std::to_string(fromYear) + "&";
parameters += "R1C1=" + std::to_string(toYear) + "&";
parameters += "R1C3=" + std::to_string(toSemester) + "&";
parameters += "R1C4=" + std::to_string(fromSemester) + "&";
parameters += "R1C5=0";
return parameters;
}
const static std::string getCalendar(const user &usr,int year, int semester)
{
std::string parameters;
parameters = "PRGNAME=Bitsua_maarechet_shaot&ARGUMENTS=TZ,UNIQ,MisparSheilta,R1C1,R1C2&";
parameters += "TZ=" + usr.getUserID() + "&";
parameters += "UNIQ=" + usr.getHashedPassword() + "&";
parameters += "MisparSheilta=3&";
parameters += "R1C1=" + std::to_string(year) + "&";
parameters += "R1C2=" + std::to_string(semester) + "&";
return parameters;
}
};
#endif // JCELOGINHTMLSCRIPTS_H

View file

@ -1,229 +1,232 @@
#include "jcelogin.h"
jceLogin::jceLogin(user * username)
{
this->recieverPage = new std::string();
this->jceA = username;
this->JceConnector = new jceSSLClient();
}
jceLogin::~jceLogin()
{
this->jceA = NULL;
delete recieverPage;
delete JceConnector;
JceConnector = NULL;
recieverPage = NULL;
}
/**
* @brief jceLogin::makeConnection Connecting to JCE student web site with JceA (username object) and validate it.
* throws error upon the given error from JCE website or Socket error
*/
void jceLogin::makeConnection() throw (jceStatus)
{
if (this->recieverPage == NULL)
this->recieverPage = new std::string();
if (JceConnector->makeConnect(dst_host,dst_port) == false)
throw jceStatus::ERROR_ON_OPEN_SOCKET;
int returnMode;
jceStatus status = jceStatus::JCE_NOT_CONNECTED;
returnMode = checkConnection();
if (returnMode == true) //connected to host
{
returnMode = makeFirstVisit();
if (returnMode == true) //requst and send first validation
{
status = jceStatus::JCE_START_VALIDATING_PROGRESS;
returnMode = checkValidation();
if (returnMode == true) //check if username and password are matching
{
status = jceStatus::JCE_VALIDATION_PASSED;
returnMode = makeSecondVisit();
if (returnMode == true) //siging in the website
{
status = jceStatus::JCE_YOU_ARE_IN;
setLoginFlag(true);
}
else if (returnMode == jceLogin::ERROR_ON_GETTING_INFO)
{
status = jceLogin::ERROR_ON_GETTING_INFO;
}
else if (returnMode == jceLogin::ERROR_ON_SEND_REQUEST)
{
status = jceLogin::ERROR_ON_SEND_REQUEST;
}
else
status = jceStatus::ERROR_ON_VALIDATION;
}
else
status = jceStatus::ERROR_ON_VALIDATION;
}
else if (returnMode == jceLogin::ERROR_ON_GETTING_INFO)
{
status = jceLogin::ERROR_ON_GETTING_INFO;
}
else if (returnMode == jceLogin::ERROR_ON_SEND_REQUEST)
{
status = jceLogin::ERROR_ON_SEND_REQUEST;
}
else
status = jceStatus::ERROR_ON_VALIDATION_USER_BLOCKED;
}
else
status = jceStatus::JCE_NOT_CONNECTED;
//we throw status even if we are IN!
throw status;
}
bool jceLogin::checkConnection()
{
if (JceConnector->isConnected())
return true;
return false;
}
void jceLogin::reConnect() throw (jceStatus)
{
closeAll();
if (this->JceConnector != NULL)
delete JceConnector;
this->recieverPage = new std::string();
this->JceConnector = new jceSSLClient();
try
{
makeConnection();
}
catch (jceLogin::jceStatus &a)
{
throw a;
}
}
void jceLogin::closeAll()
{
JceConnector->makeDiconnect();
delete recieverPage;
recieverPage = NULL;
loginFlag = false;
}
int jceLogin::makeFirstVisit()
{
std::string usr = jceA->getUsername();
std::string psw = jceA->getPassword();
if (JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getFirstValidationStep(*jceA))))
{
if (!JceConnector->recieveData(*recieverPage,true))
return jceLogin::ERROR_ON_GETTING_INFO;
}
else
return jceLogin::ERROR_ON_SEND_REQUEST;
return true;
}
int jceLogin::makeSecondVisit()
{
std::string usrid=jceA->getUserID();
std::string pswid=jceA->getHashedPassword();
if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getSecondValidationStep(*jceA)))))
{
if (!(JceConnector->recieveData(*recieverPage,true)))
return jceLogin::ERROR_ON_GETTING_INFO;
return true;
}
else
return jceLogin::ERROR_ON_SEND_REQUEST;
return true;
}
int jceLogin::getCalendar(int year, int semester)
{
if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getCalendar(*jceA,year,semester)))))
{
if (!(JceConnector->recieveData(*recieverPage,false)))
return jceLogin::ERROR_ON_GETTING_GRADES;
else
return jceLogin::JCE_GRADE_PAGE_PASSED;
}
else
return jceLogin::ERROR_ON_SEND_REQUEST;
return true;
}
int jceLogin::getGrades(int fromYear, int toYear, int fromSemester, int toSemester)
{
std::cout << fromYear << " " << toYear << " " << fromSemester << " " << toSemester << std::endl;
if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getGradesPath(*jceA,fromYear, toYear, fromSemester, toSemester)))))
{
if (!(JceConnector->recieveData(*recieverPage,false)))
return jceLogin::ERROR_ON_GETTING_GRADES;
else
return jceLogin::JCE_GRADE_PAGE_PASSED;
}
else
return jceLogin::ERROR_ON_SEND_REQUEST;
return true;
}
void jceLogin::setLoginFlag(bool x)
{
this->loginFlag = x;
}
bool jceLogin::isLoginFlag() const
{
return this->loginFlag;
}
std::string jceLogin::getPage()
{
return *recieverPage;
}
/**
* @brief jceLogin::checkValidation Made by Nadav Luzzato
* @return true if second validation step is right
*/
bool jceLogin::checkValidation()
{
//finds the hashed password
std::size_t hasspass_position1,hasspass_position2;
if ((hasspass_position1 = recieverPage->find("-A,-N")) == string::npos)
return false;
hasspass_position1 += 5;
if ((hasspass_position2 = recieverPage->find(",-A,-A", hasspass_position1)) == string::npos)
return false;
std::string hasspass = recieverPage->substr(hasspass_position1,hasspass_position2-hasspass_position1);
jceA->setHashedPassword(hasspass);
//finds the user id
std::size_t id_position1 = recieverPage->find("value=\"-N", 0);
id_position1 += 9;
std::size_t id_position2 = recieverPage->find(",-A", id_position1);
if ((id_position2 != std::string::npos) && (id_position1 != std::string::npos))
{
std::string hassid = recieverPage->substr(id_position1,id_position2-id_position1);
jceA->setUserID(hassid);
}
if (((jceA->getUserID()).empty()) || ((jceA->getHashedPassword()).empty()))
return false;
return true;
}
#include "jcelogin.h"
jceLogin::jceLogin(user * username)
{
this->recieverPage = new std::string();
this->jceA = username;
this->JceConnector = new jceSSLClient();
}
jceLogin::~jceLogin()
{
this->jceA = NULL;
delete recieverPage;
delete JceConnector;
JceConnector = NULL;
recieverPage = NULL;
}
/**
* @brief jceLogin::makeConnection Connecting to JCE student web site with JceA (username object) and validate it.
* throws error upon the given error from JCE website or Socket error
*/
void jceLogin::makeConnection() throw (jceStatus)
{
if (this->recieverPage == NULL)
this->recieverPage = new std::string();
if (JceConnector->makeConnect(dst_host,dst_port) == false)
throw jceStatus::ERROR_ON_OPEN_SOCKET;
int returnMode;
jceStatus status = jceStatus::JCE_NOT_CONNECTED;
returnMode = checkConnection();
if (returnMode == true) //connected to host
{
returnMode = makeFirstVisit();
if (returnMode == true) //requst and send first validation
{
status = jceStatus::JCE_START_VALIDATING_PROGRESS;
returnMode = checkValidation();
if (returnMode == true) //check if username and password are matching
{
status = jceStatus::JCE_VALIDATION_PASSED;
returnMode = makeSecondVisit();
if (returnMode == true) //siging in the website
{
status = jceStatus::JCE_YOU_ARE_IN;
setLoginFlag(true);
}
else if (returnMode == jceLogin::ERROR_ON_GETTING_INFO)
{
status = jceLogin::ERROR_ON_GETTING_INFO;
}
else if (returnMode == jceLogin::ERROR_ON_SEND_REQUEST)
{
status = jceLogin::ERROR_ON_SEND_REQUEST;
}
else
status = jceStatus::ERROR_ON_VALIDATION;
}
else
status = jceStatus::ERROR_ON_VALIDATION;
}
else if (returnMode == jceLogin::ERROR_ON_GETTING_INFO)
{
status = jceLogin::ERROR_ON_GETTING_INFO;
}
else if (returnMode == jceLogin::ERROR_ON_SEND_REQUEST)
{
status = jceLogin::ERROR_ON_SEND_REQUEST;
}
else
status = jceStatus::ERROR_ON_VALIDATION_USER_BLOCKED;
}
else
status = jceStatus::JCE_NOT_CONNECTED;
//we throw status even if we are IN!
throw status;
}
bool jceLogin::checkConnection() const
{
if (JceConnector->isConnected())
return true;
return false;
}
void jceLogin::reConnect() throw (jceStatus)
{
closeAll();
if (this->JceConnector != NULL)
delete JceConnector;
this->recieverPage = new std::string();
this->JceConnector = new jceSSLClient();
try
{
makeConnection();
}
catch (jceLogin::jceStatus &a)
{
throw a;
}
}
void jceLogin::closeAll()
{
JceConnector->makeDiconnect();
delete recieverPage;
recieverPage = NULL;
loginFlag = false;
}
int jceLogin::makeFirstVisit()
{
std::string usr = jceA->getUsername();
std::string psw = jceA->getPassword();
if (JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getFirstValidationStep(*jceA))))
{
if (!JceConnector->recieveData(*recieverPage,true))
return jceLogin::ERROR_ON_GETTING_INFO;
}
else
return jceLogin::ERROR_ON_SEND_REQUEST;
return true;
}
int jceLogin::makeSecondVisit()
{
std::string usrid=jceA->getUserID();
std::string pswid=jceA->getHashedPassword();
if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getSecondValidationStep(*jceA)))))
{
if (!(JceConnector->recieveData(*recieverPage,true)))
return jceLogin::ERROR_ON_GETTING_INFO;
return true;
}
else
return jceLogin::ERROR_ON_SEND_REQUEST;
return true;
}
int jceLogin::getCalendar(int year, int semester)
{
if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getCalendar(*jceA,year,semester)))))
{
if (!(JceConnector->recieveData(*recieverPage,false)))
return jceLogin::ERROR_ON_GETTING_GRADES;
else
return jceLogin::JCE_GRADE_PAGE_PASSED;
}
else
return jceLogin::ERROR_ON_SEND_REQUEST;
return true;
}
int jceLogin::getGrades(int fromYear, int toYear, int fromSemester, int toSemester)
{
std::cout << fromYear << " " << toYear << " " << fromSemester << " " << toSemester << std::endl;
if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getGradesPath(*jceA,fromYear, toYear, fromSemester, toSemester)))))
{
if (!(JceConnector->recieveData(*recieverPage,false)))
return jceLogin::ERROR_ON_GETTING_GRADES;
else
return jceLogin::JCE_GRADE_PAGE_PASSED;
}
else
return jceLogin::ERROR_ON_SEND_REQUEST;
return true;
}
void jceLogin::setLoginFlag(bool x)
{
this->loginFlag = x;
}
bool jceLogin::isLoginFlag() const
{
if (checkConnection())
return this->loginFlag;
return false;
}
std::string jceLogin::getPage()
{
return *recieverPage;
}
/**
* @brief jceLogin::checkValidation Made by Nadav Luzzato
* @return true if second validation step is right
*/
bool jceLogin::checkValidation()
{
//finds the hashed password
std::size_t hasspass_position1,hasspass_position2;
if ((hasspass_position1 = recieverPage->find("-A,-N")) == string::npos)
return false;
hasspass_position1 += 5;
if ((hasspass_position2 = recieverPage->find(",-A,-A", hasspass_position1)) == string::npos)
return false;
std::string hasspass = recieverPage->substr(hasspass_position1,hasspass_position2-hasspass_position1);
jceA->setHashedPassword(hasspass);
//finds the user id
std::size_t id_position1 = recieverPage->find("value=\"-N", 0);
id_position1 += 9;
std::size_t id_position2 = recieverPage->find(",-A", id_position1);
if ((id_position2 != std::string::npos) && (id_position1 != std::string::npos))
{
std::string hassid = recieverPage->substr(id_position1,id_position2-id_position1);
jceA->setUserID(hassid);
}
if (((jceA->getUserID()).empty()) || ((jceA->getHashedPassword()).empty()))
return false;
return true;
}

View file

@ -1,60 +1,60 @@
#ifndef JCELOGIN_H
#define JCELOGIN_H
#include <string>
#include <fstream>
#include "./src/jceConnection/jcesslclient.h"
#include "./src/jceSettings/user.h"
#include "jceLoginHtmlScripts.h"
class jceLogin
{
public:
enum jceStatus {
JCE_NOT_CONNECTED,
ERROR_ON_VALIDATION,
ERROR_ON_VALIDATION_USER_BLOCKED,
ERROR_ON_OPEN_SOCKET,
ERROR_ON_SEND_REQUEST,
ERROR_ON_GETTING_INFO,
ERROR_ON_GETTING_GRADES,
JCE_START_VALIDATING_PROGRESS,
JCE_VALIDATION_PASSED,
JCE_YOU_ARE_IN,
JCE_GRADE_PAGE_PASSED
};
jceLogin(user* username);
~jceLogin();
void makeConnection() throw (jceStatus);
bool checkConnection();
void reConnect() throw (jceStatus);
void closeAll();
int getCalendar(int year, int semester);
int getGrades(int fromYear, int toYear, int fromSemester, int toSemester);
bool isLoginFlag() const;
std::string getPage();
private:
int makeFirstVisit();
bool checkValidation();
int makeSecondVisit();
void setLoginFlag(bool x);
bool loginFlag;
std::string * recieverPage;
user * jceA;
jceSSLClient * JceConnector;
};
#endif // JCELOGIN_H
#ifndef JCELOGIN_H
#define JCELOGIN_H
#include <string>
#include <fstream>
#include "./src/jceConnection/jcesslclient.h"
#include "./src/jceSettings/user.h"
#include "jceLoginHtmlScripts.h"
class jceLogin
{
public:
enum jceStatus {
JCE_NOT_CONNECTED,
ERROR_ON_VALIDATION,
ERROR_ON_VALIDATION_USER_BLOCKED,
ERROR_ON_OPEN_SOCKET,
ERROR_ON_SEND_REQUEST,
ERROR_ON_GETTING_INFO,
ERROR_ON_GETTING_GRADES,
JCE_START_VALIDATING_PROGRESS,
JCE_VALIDATION_PASSED,
JCE_YOU_ARE_IN,
JCE_GRADE_PAGE_PASSED
};
jceLogin(user* username);
~jceLogin();
void makeConnection() throw (jceStatus);
bool checkConnection() const;
void reConnect() throw (jceStatus);
void closeAll();
int getCalendar(int year, int semester);
int getGrades(int fromYear, int toYear, int fromSemester, int toSemester);
bool isLoginFlag() const;
std::string getPage();
private:
int makeFirstVisit();
bool checkValidation();
int makeSecondVisit();
void setLoginFlag(bool x);
bool loginFlag;
std::string * recieverPage;
user * jceA;
jceSSLClient * JceConnector;
};
#endif // JCELOGIN_H

View file

@ -1,45 +1,45 @@
#include "user.h"
user::user(string username,string password) : hashedPassword(""),userID(""), influenceCourseOnly(false)
{
this->username = username;
this->password = password;
}
user::~user()
{
}
void user::setInfluenceCourseOnly(bool status)
{
this->influenceCourseOnly = status;
}
bool user::getInfluenceCourseOnly() const
{
return this->influenceCourseOnly;
}
void user::setUsername(string& username) {
this->username=username;
}
void user::setPassword(string& password) {
this->password=password;
}
void user::setUserID(string& ID)
{
this->userID = ID;
}
void user::setHashedPassword(string& hashpass)
{
this->hashedPassword = hashpass;
}
string user::getPassword() const { return password; }
string user::getUsername() const { return username; }
string user::getUserID() const { return userID; }
string user::getHashedPassword() const { return hashedPassword; }
#include "user.h"
user::user(string username,string password) : hashedPassword(""),userID(""), influenceCourseOnly(false)
{
this->username = username;
this->password = password;
}
user::~user()
{
}
void user::setInfluenceCourseOnly(bool status)
{
this->influenceCourseOnly = status;
}
bool user::getInfluenceCourseOnly() const
{
return this->influenceCourseOnly;
}
void user::setUsername(string& username) {
this->username=username;
}
void user::setPassword(string& password) {
this->password=password;
}
void user::setUserID(string& ID)
{
this->userID = ID;
}
void user::setHashedPassword(string& hashpass)
{
this->hashedPassword = hashpass;
}
string user::getPassword() const { return password; }
string user::getUsername() const { return username; }
string user::getUserID() const { return userID; }
string user::getHashedPassword() const { return hashedPassword; }

View file

@ -1,43 +1,43 @@
#ifndef user_H
#define user_H
#include <string>
#include <iostream>
using namespace std;
class user
{
public:
user(string username,string password);
~user();
void setUsername(string& username);
void setPassword(string& password);
string getPassword() const;
string getUsername() const;
void setUserID(string& ID);
void setHashedPassword(string& hashpass);
string getUserID() const;
string getHashedPassword() const;
void setInfluenceCourseOnly(bool status);
bool getInfluenceCourseOnly() const;
private:
string username;
string password;
string hashedPassword;
string userID;
bool influenceCourseOnly;
};
#endif
#ifndef user_H
#define user_H
#include <string>
#include <iostream>
using namespace std;
class user
{
public:
user(string username,string password);
~user();
void setUsername(string& username);
void setPassword(string& password);
string getPassword() const;
string getUsername() const;
void setUserID(string& ID);
void setHashedPassword(string& hashpass);
string getUserID() const;
string getHashedPassword() const;
void setInfluenceCourseOnly(bool status);
bool getInfluenceCourseOnly() const;
private:
string username;
string password;
string hashedPassword;
string userID;
bool influenceCourseOnly;
};
#endif