Commit e39c1c30 by Pablo Molina

Solved #386, organizados eventos websocket

- Añadido hook "rooms" a sails
- Añadido hook "events" a sails
- Actualizado StudentController.link_supervisor para que use los nuevos hooks
- Añadido uso de sails responses (badRequest(), ok()...) para las
  peticiones
- Creado servicio IOService para manejar websockets en angular
- Añadidas urls /sup/subscribe y /sup/unsubscribe para crear salas de
  supervisores
parent 07f44854
Showing with 1025 additions and 773 deletions
# EditorConfig is awesome: http://EditorConfig.org
root = true
[*]
end_of_line = lf
charset = utf-8
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
insert_final_newline = true
[android/**]
indent_size = 4
......@@ -44,3 +44,18 @@ todo el repositorio, organizadas en 3 categorías:
- Estado:
- `in-progress`: incidencias en proceso de desarrollo
- `critical`: elementos importantes que deben tener prioridad
# Aspecto del código
- En el fichero [.editorconfig](./.editorconfig) se encuentra el estilo
utilizado en el código (en cuento a espacios, codificación y demás). Existen
numerosos plugins que pueden encontrarse en
[editorconfig.org](http://EditorConfig.org).
- En el fichero [/sails/src/.eslintrc](./sails/src/eslintrc) se encuentran los
estilos referentes a los ficheros de javascript. Tanto `eslint` como las
configuraciones necesarias se encuentran en el fichero
[/sails/src/package.json](./sails/src/package.json), y se instalarán como
dependencias de desarrollo.
> Puede configurarse eslint en el editor usado o ejecutando
> `eslint [ficheros]` desde el directorio [/sails/src](./sails/src).
......@@ -9,7 +9,7 @@ android {
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.yottacode.pictogram"
minSdkVersion 19
minSdkVersion 21
targetSdkVersion 21
versionCode 1
versionName "1.0"
......
......@@ -35,7 +35,7 @@ import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
public class PanelAdapter extends ArrayAdapter {
public class PictoGridAdapter extends ArrayAdapter {
private LinkedList<Picto> lPictos;
int color;
......@@ -45,7 +45,7 @@ public class PanelAdapter extends ArrayAdapter {
// String constant for logs
private final String LOG_TAG = this.getClass().getSimpleName(); // Or .getCanonicalName()
public PanelAdapter(LinkedList<Picto> ll){
public PictoGridAdapter(LinkedList<Picto> ll){
super(PCBcontext.getContext(), R.layout.list_item_img ,ll);
//mContext = c;
lPictos = ll;
......@@ -117,7 +117,7 @@ public class PanelAdapter extends ArrayAdapter {
/*
try{
imageView.setBackgroundColor(lPictos.get(position).get_darkner_color());
//Log.d("PanelAdapter", "Position: " + position);
//Log.d("PictoGridAdapter", "Position: " + position);
} catch (java.lang.IllegalArgumentException e){
e.printStackTrace();
//imageView.setBackgroundColor(PCBcontext.getContext().getResources().getColor(R.color.blue));
......
......@@ -2,61 +2,92 @@
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:orientation="horizontal"
android:background="#BDBDBD"
android:keepScreenOn="true"
android:id="@+id/pictogramLayout"
tools:context=".PictogramActivity">
tools:context=".PictogramActivity"
android:padding="8dp">
<!-- android:keepScreenOn - To keep the screen bright as long as the app is visible (also forever) -->
<GridView
android:id="@+id/tape_grid_view"
android:layout_width="850dp"
android:layout_height="85dp"
android:layout_width="wrap_content"
android:layout_height="64dp"
android:padding="8dp"
android:gravity="center"
android:numColumns="@integer/columns"
android:accessibilityLiveRegion="none"
android:background="@android:color/holo_red_light"
android:clickable="false"
android:layout_alignParentTop="true">
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:paddingRight="192dp">
</GridView>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="850dp"
android:paddingTop="20dp"
android:src="@drawable/back64"
android:background="@null"
android:layout_width="96dp"
android:layout_height="64dp"
android:src="@drawable/ic_backspace_white_48dp"
android:id="@+id/button_delete"
android:layout_alignParentTop="true"/>
android:layout_alignParentTop="true"
android:layout_toLeftOf="@+id/button_tts"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:clickable="true"
android:background="@null" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:paddingTop="20dp"
android:src="@drawable/play64"
android:layout_width="96dp"
android:layout_height="64dp"
android:src="@drawable/ic_play_circle_filled_white_48dp"
android:background="@null"
android:id="@+id/button_tts"
android:layout_toRightOf="@+id/tape_grid_view"
android:adjustViewBounds="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"/>
android:layout_alignParentEnd="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:clickable="true" />
<ImageButton
android:layout_width="96dp"
android:layout_height="match_parent"
android:id="@+id/showPictoCategoriesViewButton"
android:layout_alignParentStart="true"
android:src="@drawable/back64"
android:background="#DDDDDD"
android:layout_below="@+id/tape_grid_view" />
<GridView
android:id="@+id/picto_grid_view"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_below="@+id/tape_grid_view"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:numColumns="10"
android:gravity="center_vertical|center|center_horizontal"
android:paddingTop="32dp"
android:verticalSpacing="24dp"
android:background="@color/common_signin_btn_default_background"
android:layout_toEndOf="@+id/showPictoCategoriesViewButton">
</GridView>
<GridView
android:id="@+id/panel_grid_view"
android:id="@+id/picto_categories_grid_view"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:paddingTop="20dp"
android:columnWidth="100dp"
android:verticalSpacing="1dp"
android:horizontalSpacing="15dp"
android:stretchMode="columnWidth"
android:layout_below="@+id/tape_grid_view">
android:layout_below="@+id/tape_grid_view"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:numColumns="10"
android:gravity="center_vertical|center|center_horizontal"
android:paddingTop="32dp"
android:verticalSpacing="24dp"
android:background="#DDDDDD">
</GridView>
</RelativeLayout>
\ No newline at end of file
......@@ -11,6 +11,7 @@ en el directorio [conf](./conf).
- Nodejs >= 0.10.37
- Npm >= 3.8.5
- Bower >= 1.4.1
- Sails 0.12.3
## Instalación del servidor y el cliente web
......
......@@ -9,7 +9,7 @@ sudo apt-get install -y nodejs
sudo npm install -g npm
# Sails install
sudo npm install -g sails
sudo npm install -g sails@0.12.3
# Sails log file
mkdir -p ./src/logs
......
{
"extends": "airbnb",
"rules": {
"comma-dangle": 0,
"func-names": 0,
"jsx-a11y/valid-aria-role": 0,
"jsx-a11y/img-uses-alt": 0,
"jsx-a11y/redundant-alt": 0,
"no-param-reassign": 0,
"no-var": 0,
"object-shorthand": 0,
"prefer-arrow-callback": 0,
"prefer-template": 0,
"strict": 0
}
}
/* global Student, PictoCoreCat, VStuLastInstruction, StuPicto, StuSup, sailsTokenAuth, sails */
/**
/* StudentController
*
......@@ -12,40 +14,39 @@ module.exports = {
// expected params in post body: username, password
//
login: function (req, res) {
var bcrypt = require('bcrypt-nodejs');
var username = req.body.username;
var password = req.body.password;
// no credentials
if (!username || !password)
return res.json(401, {error: 'No credentials sent'});
if (!username || !password) {
return res.json(401, { error: 'No credentials sent' });
}
// search user by username
Student.findOneByUsername(username).exec(function (err, stu) {
if (err)
if (err) {
return res.json(500, { error: 'DB error' });
}
if (!stu)
return res.json(401, {error: 'User not found'});
if (!stu) {
return res.json(401, { error: 'User not found' });
}
// if found, check password in encrypted form
bcrypt.compare(password, stu.password, function (err, match) {
if (err)
if (err) {
return res.json(500, { error: 'Server error' });
}
if (match) { // password match
// all supervisor information is passed as payload to the token
stu.isStudent = true;
return res.json({
user: stu,
token: sailsTokenAuth.issueToken(stu, sails.config.jwt.expiresInMinutes),
server_time: (new Date()).getTime()
});
} else {
return res.json(401, { error: 'Invalid password' });
}
......@@ -57,27 +58,30 @@ module.exports = {
// Get a student with the given id, population also the office and the last method/instruction
//
getInfo: function(req, res) {
if (!req.params.id_stu)
return res.json(500, {err: 'no id_stu'});
if (!req.params.id_stu) {
return res.json(500, { err: 'no id_stu' });
}
Student.findOne(req.params.id_stu).populate('office').populate('stuSup').exec(function(err, student){
Student.findOne(req.params.id_stu).populate('office').populate('stuSup')
.exec(function(err, student){
if (err) {
sails.log.debug(err);
console.log(JSON.stringify(err));
return res.json(500, err);
}
if (!student)
if (!student) {
return res(500, {err: JSON.stringify(err)});
}
// get student last method/instruction
VStuLastInstruction.findOne({ student : student.id }).exec(function(err, row) {
VStuLastInstruction.findOne({ student : student.id })
.exec(function(err, row) {
if (err) {
sails.log.debug(err);
console.log(JSON.stringify(err));
return res.json(500, err);
}
if (!row || row.length == 0) {
if (!row || row.length === 0) {
student.current_method = 'no_method';
student.current_instruction = 'no_instruction';
} else {
......@@ -99,7 +103,6 @@ module.exports = {
if (err) {
sails.log.debug(err);
console.log(JSON.stringify(err));
return res.json(500, err);
}
if (created) {
......@@ -107,7 +110,6 @@ module.exports = {
// Assign the initial collection of pictos to the student
PictoCoreCat.find().exec(function(err, pictoCoreCat) {
if (err || !pictoCoreCat || pictoCoreCat.length == 0){
sails.log.debug("PictoCoreCat: " + err);
return;
......@@ -116,11 +118,9 @@ module.exports = {
sails.log.debug("PictoCoreCat Length: " + pictoCoreCat.length);
sails.log.debug(pictoCoreCat);
// Every picto from 'picto_core_cat' is going to be created
// in 'stu_picto'
for (var i = 0; i < pictoCoreCat.length; i++) {
sails.log.debug("Loop: " + i);
sails.log.debug("Picto Category: " + pictoCoreCat[i].category);
sails.log.debug("User id: " + created.id);
......@@ -136,14 +136,17 @@ module.exports = {
color: pictoCoreCat[i].color
}
}).exec(function(err, added){
if(err) sails.log.debug("StuPicto.create: " + err);
if(added) sails.log.debug("Picto " + added.picto + " added to student " + created.id + " with attributes: " + JSON.stringify(added.attributes));
if(err) sails.log.debug('StuPicto.create: ' + err);
if(added) {
sails.log.debug(
'Picto ' + added.picto +
' added to student ' + created.id +
' with attributes: ' + JSON.stringify(added.attributes));
}
});
}
});
return res.json({student: created});
return res.json({ student: created });
}
});
},
......@@ -223,21 +226,55 @@ module.exports = {
});
},
// Add action
// Create a relation between supervisor and student (stu_sup)
//
/**
* Creates a relation between the student and a given supervisor.
* It broadcasts the even linkSupervisorToStudent to both the student room
* and the supervisor room.
*/
link_supervisor: function(req, res) {
var params = req.allParams();
console.log(JSON.stringify(params));
StuSup.create({student: params.id_stu, supervisor: params.id_sup}).exec(function (err, created) {
StuSup.create({
student: params.id_stu,
supervisor: params.id_sup
}).exec(function (err, created) {
var response;
var socketToOmit;
var linkSupervisorToStudentEvent;
if (err) {
console.log(err);
return res.json(500, {error: 'Relation student/supervisor NO created'});
response = res.serverError(
'Relation student/supervisor not created: ' + err
);
}
if (created) {
console.log("Relation student/supervisor created" );
return res.json(created);
socketToOmit = (req.isSocket) ? req.socket : undefined;
linkSupervisorToStudentEvent = sails.hooks.events.linkSupervisorToStudent(
params.id_sup,
params.id_stu
);
sails.hooks.events.broadcastEvent(
sails.hooks.rooms.supervisor(params.id_sup),
linkSupervisorToStudentEvent,
socketToOmit
);
sails.hooks.events.broadcastEvent(
sails.hooks.rooms.student(params.id_stu),
linkSupervisorToStudentEvent,
socketToOmit
);
response = res.ok(created);
} else {
response = res.serverError(
'Relation student/supervisor not created, ' +
'but no error was received'
);
}
return response;
});
},
......
......@@ -381,5 +381,59 @@ module.exports = {
} , 5);
}
);
},
/**
* Subscribe to supervisor's room
* @param {Object} request must have the following format:
*
* {
* action: subscribe,
* attributes: { id_sup: '' }
* }
*
* @param {Object} response
* @return {Object} response
*/
subscribe: function(request, response) {
var action = request.param('action');
var attributes = request.param('attributes');
if (action === 'subscribe' && request.isSocket && attributes.id_sup) {
sails.hooks.rooms.subscribeToRoom(
sails.hooks.rooms.supervisor(attributes.id_sup),
request.socket
);
return response.ok();
} else {
return response.badRequest();
}
},
/**
* Unsubscribe from supervisor's room
* @param {Object} request must have the following format:
*
* {
* action: unsubscribe,
* attributes: { id_sup: '' }
* }
*
* @param {Object} response
* @return {Object} response
*/
unsubscribe: function(request, response) {
var action = request.param('action');
var attributes = request.param('attributes');
if (action === 'unsubscribe' && request.isSocket && attributes.id_sup) {
sails.hooks.rooms.unsubscribeFromRoom(
sails.hooks.rooms.supervisor(attributes.ip_sup),
request.socket
);
return response.ok();
} else {
return response.badRequest();
}
}
};
/**
* Functions defining the events sent inside the sockets.
* In order to create a new event you have to call the corresponding
* function with the necesary parameters, and you will receive an Object:
*
* {
* name: 'eventName',
* data: 'eventData'
* }
*
* Where 'name' is the name of the event and 'data' is the block of
* information to send.
* @type {Object}
*/
module.exports = function eventsHook (sails) {
return {
/**
* Speacial Function wrapping sails.sockets.broadcast that uses a room
* from sails.hooks.rooms and an event from sails.hooks.events in
* order to broadcast information. This also logs the event as debug
* level information with the message:
*
* "websocketEvent": {
* "room",
* "name",
* "data": { ... }
* }
*
* @param {RoomId} rooms RoomID or IDs where the event will be sent
* @param {Object} event A tuple {name, data} returned by a
* function inside sails.sockets.events
* @param {socket} socketToOmit If specified, this socket will not receive
* the event
*/
broadcastEvent: function (rooms, event, socketToOmit) {
// Ensure rooms is an Array
if (!(rooms instanceof Array)) {
rooms = [rooms];
}
sails.log.debug('"websocketEvent":', JSON.stringify({
rooms: rooms,
name: event.name,
data: event.data,
socketToOmit: socketToOmit ? socketToOmit.id : undefined
}));
sails.sockets.broadcast(
rooms,
event.name,
event.data,
socketToOmit || undefined
);
},
/**
* A supervisor has been linked to a student.
* @param {ID} supId ID of the supervisor
* @param {ID} stu_id ID of the student
* @return {Object} {name, data}
*/
linkSupervisorToStudent: function (supId, stuId) {
return {
name: 'linkSupervisorToStudent',
data: {
sup_id: supId,
stu_id: stuId
}
};
},
/**
* Someone has subscribed/unsubscribed to/from a room. The number
* of subscribes is sent
* @param {number} subscriberCount Number of subscribers
* @return {Object} {name, data}
*/
roomSubscribersChange: function (subscriberCount) {
return {
name: 'update_peers',
data: {
count: subscriberCount
}
};
}
};
};
/**
* This hook is used for managing the rooms IDs.
* Every room created should call one of this functions in order
* to obtain an ID.
* @type {Object}
*/
module.exports = function roomsHook (sails) {
return {
/**
* Special function that subscribes a socket to a given room.
* This creates the connection and logs to debug with this format:
*
* {
* websocketSubscribe: {
* room,
* socket
* }
* }
*
* @param {RoomID} room Room to subscribe
* @param {Socket} socket Socket added to the subscription
*/
subscribeToRoom: function (room, socket) {
sails.log.debug('"websocketSubscribe":', JSON.stringify({
room: room,
socket: socket.id
}));
sails.sockets.join(socket, room, function () {
sails.io.sockets.in(room).clients(function(error, ids) {
if (!error) {
sails.hooks.events.broadcastEvent(
room,
sails.hooks.events.roomSubscribersChange(ids.length)
);
}
});
});
},
/**
* Special function that unsubscribes a socket from a given room.
* This remotes the connection and logs to debug with this format:
*
* {
* websocketUnsubscribe: {
* room,
* socket
* }
* }
*
* @param {RoomID} room Room to unsubscribe from
* @param {Socket} socket Socket removed from the subscription
*/
unsubscribeFromRoom: function (room, socket) {
sails.log.debug('"websocketUnsubscribe":', JSON.stringify({
room: room,
socket: socket.id
}));
sails.sockets.leave(socket, room, function () {
sails.io.sockets.in(room).clients(function(error, ids) {
if (!error) {
sails.hooks.events.broadcastEvent(
room,
sails.hooks.events.roomSubscribersChange(ids.length)
);
}
});
});
},
/**
* Student related rooms
* @param {ID} studentId Student's ID used for creating a room.
* @return {RoomID} RoomID generated
*/
student: function (studentId) {
return 'studentRoom' + studentId;
},
/**
* Supervisor related rooms
* @param {ID} supervisorId Supervisor's ID used for creating a room.
* @return {RoomID} RoomID generated
*/
supervisor: function (supervisorId) {
return 'supervisorRoom' + supervisorId;
}
};
};
{
"rules": {
"comma-dangle": 0,
"func-names": 0,
"jsx-a11y/valid-aria-role": 0,
"jsx-a11y/img-uses-alt": 0,
"jsx-a11y/redundant-alt": 0,
"no-param-reassign": 0,
"no-var": 0,
"object-shorthand": 0,
"prefer-arrow-callback": 0,
"prefer-template": 0,
"strict": 0
}
}
......@@ -84,6 +84,10 @@
"english": "English",
"enlarge": "Enlarge",
"enormous": "Enormous",
"error_downloading_supervisors": "Error downloading supervisors",
"error_downloading_offices": "Error downloading offices",
"error_only_support_images": "Only images are supported (JPG, PNG or GIF files)",
"error_loading_pictos": "Error loading pictos information",
"expand_navigation": "Expand navigation",
"expand_navigation": "Expand navigation",
"expression": "Expression:",
......@@ -229,9 +233,9 @@
"student_pictograms": "Student's pictograms",
"student_updated": "Student updated",
"students": "Students",
"sup_not_added": "Supervisor not added to the student.",
"sup_not_added": "Supervisor not added to the student",
"sup_not_deleted": "The supervisor couldn't be deleted by the student",
"sup_not_found": "There is no supervisor account in Pictogram with this email.",
"sup_not_found": "There is no supervisor account in Pictogram with this email",
"supervisor_added": "Supervisor added",
"supervisor_deleted": "Supervisor deleted",
"supervisor_not_added": "Supervisor not added",
......@@ -258,8 +262,10 @@
"tries_per_instruction_method": "Tries per instruction of method",
"tries_per_months": "Tries per months in",
"tries_results_instruction": "Tries results in instruction",
"tutor_added": "Tutor added to the student",
"tutor_deleted": "Tutor removed from the student",
"tutor_not_added": "Tutor not added to the student.",
"tutor_not_deleted": "The tutor couldn't be deleted by the student",
"tutor_not_deleted": "Tutor couldn't be removed from the student",
"tutor_not_found": "There is no tutor account in Pictogram with this email.",
"tutors": "Parents or tutors",
"unlink": "Unlink",
......
......@@ -87,6 +87,10 @@
"expand_navigation": "Desplegar navegación",
"expand_navigation": "Desplegar navegación",
"expression": "Expresión:",
"error_downloading_supervisors": "Error al descargar los supervisores",
"error_downloading_offices": "Error al descargar las oficinas",
"error_only_support_images": "Sólo se soportan imágenes (ficheros JPG, PNG o GIF)",
"error_loading_pictos": "Error cargando información de los pictos",
"February": "Febrero",
"feedback_picto": "Feedback al colocar un pictograma",
"filter": "Filtrar",
......@@ -258,9 +262,11 @@
"tries_per_instruction_method": "Ensayos por instrucción del método",
"tries_per_months": "Número de ensayos por meses en",
"tries_results_instruction": "Resultados ensayos en instrucción",
"tutor_not_added": "El tutor no se ha podido añadir al estudiante.",
"tutor_not_deleted": "El tutor no se ha podido desvincular del alumno.",
"tutor_not_found": "No hay ningún tutor en Pictoram con ese correo electrónico.",
"tutor_added": "Tutor añadido al estudiante",
"tutor_deleted": "Tutor desvinculado del estudiante",
"tutor_not_added": "El tutor no se ha podido añadir al estudiante",
"tutor_not_deleted": "El tutor no se ha podido desvincular del alumno",
"tutor_not_found": "No hay ningún tutor en Pictoram con ese correo electrónico",
"tutors": "Padres o tutores",
"undefined": "Sin definir",
"unlink": "Desvincular",
......
......@@ -81,6 +81,7 @@
<body ng-controller="MainCtrl">
<!-- <div ng-view></div> -->
<toast></toast>
<div ui-view></div>
<!-- Librería jQuery requerida por los plugins de JavaScript
......
'use strict';
/* Services */
/* global io */
//
// This defines an interceptor service in every HTTP request to add session
// token in the header and in every HTTP response to handle non authorized
// connections
//
'use strict';
var module = angular.module('dashboardServices', []);
angular.module('dashboardServices', [])
.service('authInterceptor', function ($rootScope, $q, $window) {
/**
* This defines an interceptor service in every HTTP request to add session
* token in the header and in every HTTP response to handle non authorized
* connections.
*/
module.factory('AuthInterceptorService', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
......@@ -30,7 +29,68 @@ angular.module('dashboardServices', [])
return $q.reject(rejection);
}
};
})
.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
// Add AuthInterceptorService to $httpProvider.interceptors
module.config(function ($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptorService');
});
/**
* IOService that must be used as communication with the server.
* It allows to subscribe/unsubscribe to/from rooms and listen/stop listening
* to events.
*/
module.factory('IOService', function ($window) {
return {
/**
* Send a get request to the server via websocket
* @param {String} url Url of the request
* @param {Function} callback Function to be called on response
*/
get: function(url, callback) {
io.socket.get(url, { token: $window.sessionStorage.token }, callback);
},
/**
* Send a post request to the server via websocket
* @param {String} url Url of the request
* @param {Object} data If this parameter is not an object, it will
* be wrapped inside an object:
* { data, token }, otherwise the token will be
* appended to the parameters
* @param {Function} callback Function to be called on response
*/
post: function (url, data, callback) {
// Create the request data and convert it to an object if necesary
// Then append the token
var requestData = data;
if (typeof requestData !== 'object') {
requestData = { data: data };
}
requestData.token = $window.sessionStorage.token;
io.socket.post(url, requestData, callback);
},
/**
* Subscribes to an event with the given function using websockets
* @param {String} event Event to subscribe to
* @param {Function} callback Function to be executed when the event occurs
*/
on: function (event, callback) {
io.socket.on(event, callback);
},
/**
* Unsubscribe from an event
* @param {String} event Event to unsubscribe from
* @param {Function} callback If specified, only this funcion will be
* unsuscribed from the event, otherwise all
* functions subscribed to this event will be
* removed
*/
off: function (event, callback) {
io.socket.off(event, callback);
}
};
});
......@@ -3,7 +3,7 @@
//--------------------------
// Admin Supervisors Controller
//--------------------------
dashboardControllers.controller('AdminSupervisorsCtrl', function AdminSupervisorsCtrl($scope, $window, $http, config) {
dashboardControllers.controller('AdminSupervisorsCtrl', function AdminSupervisorsCtrl($scope, $window, $http, config, $translate, ngToast) {
// The last parameter, config, is injected from config.js (defined in dashboardConfig module)
// Don't show the message at the begining
......@@ -25,26 +25,24 @@ dashboardControllers.controller('AdminSupervisorsCtrl', function AdminSupervisor
$http
.get(config.backend+'/sup')
.success(function(data, status, headers, config) {
// Add to list
$scope.supervisors = data;
console.log("Supervisors listed");
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
$translate('error_downloading_supervisors').then(function (translation) {
ngToast.danger({ content: translation });
});
});
// List of offices (for the select form)
$http
.get(config.backend+'/office/get_all')
.success(function(data, status, headers, config) {
// Add to list
$scope.offices = data;
console.log("Offices listed");
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
$translate('error_downloading_offices').then(function (translation) {
ngToast.danger({ content: translation });
});
});
// Reset form Supervisor
......@@ -108,9 +106,9 @@ dashboardControllers.controller('AdminSupervisorsCtrl', function AdminSupervisor
$http
.put(config.backend+'/supervisor/'+supid, supervisor)
.success(function(data, status, headers, config) {
$scope.showmessagesupervisor = true;
$scope.alertsupervisor = "alert-success";
$scope.messagesupervisor = "supervisor_updated";
$translate('supervisor_updated').then(function (translation) {
ngToast.success({ content: translation });
});
// Update the view: Se recorre el array de objetos json para buscarlo
for(var i=0; i < $scope.supervisors.length; i++) {
......@@ -130,15 +128,11 @@ dashboardControllers.controller('AdminSupervisorsCtrl', function AdminSupervisor
// Delete the fields of the form to avoid data binding
// between the new element created and the form fields
$scope.resetForm();
console.log("Supervisor updated");
})
.error(function(data, status, headers, config) {
$scope.showmessagesupervisor = true;
$scope.alertsupervisor = "alert-danger";
$scope.messagesupervisor = "supervisor_not_updated";
console.log("Error from API: " + data.error);
$translate('supervisor_not_updated').then(function (translation) {
ngToast.danger({ content: translation });
});
});
};
......@@ -153,9 +147,9 @@ dashboardControllers.controller('AdminSupervisorsCtrl', function AdminSupervisor
$http
.post(config.backend+'/sup', supervisor)
.success(function(data, status, headers, config) {
$scope.showmessagesupervisor = true;
$scope.alertsupervisor = "alert-success";
$scope.messagesupervisor = "supervisor_added";
$translate('supervisor_added').then(function (translation) {
ngToast.success({ content: translation });
});
// Add to the list of supervisors in view
$scope.supervisors.push(data.user);
......@@ -164,15 +158,11 @@ dashboardControllers.controller('AdminSupervisorsCtrl', function AdminSupervisor
$scope.resetForm();
// Show the add form to new adding
$scope.hidesupervisoradd = false;
console.log("Supervisor added");
})
.error(function(data, status, headers, config) {
$scope.showmessagesupervisor = true;
$scope.alertsupervisor = "alert-danger";
$scope.messagesupervisor = "supervisor_not_added";
console.log("Error from API: " + data.error);
$translate('supervisor_not_added').then(function (translation) {
ngToast.danger({ content: translation });
});
});
};
......@@ -189,23 +179,19 @@ dashboardControllers.controller('AdminSupervisorsCtrl', function AdminSupervisor
if(supervisor.id == $scope.supervisors[i].id)
$scope.supervisors.splice(i,1);
}
console.log("Supervisor deleted:" + supervisor.name);
$scope.showmessagesupervisor = true;
$scope.alertsupervisor = "alert-success";
$scope.messagesupervisor = "supervisor_deleted";
$translate('supervisor_deleted').then(function (translation) {
ngToast.success({ content: translation });
});
// Empty the form
$scope.resetForm();
})
.error(function(data, status, headers, config) {
console.log("Error deleting supervisor from API: " + data.error);
console.log("It could be students associated");
$scope.showmessagesupervisor = true;
$scope.alertsupervisor = "alert-danger";
$scope.messagesupervisor = "supervisor_not_deleted";
$translate('supervisor_not_deleted').then(function (translation) {
ngToast.danger({ content: translation });
});
});
}
};
});
<!-- Admin Supervisors -->
<!-- Alert and success messages -->
<div ng-show="{{ 'showmessagesupervisor' }}" class="alert" ng-class="alertsupervisor">{{ messagesupervisor | translate }}</div>
<div class="row">
<div ng-class="{'col-md-12':hidesupervisoradd === true && hidesupervisorupdate === true, 'col-md-8':hidesupervisoradd === false || hidesupervisorupdate === false}">
......
/* global dashboardControllers */
'use strict';
//------------------
// Login Controller
//------------------
dashboardControllers.controller('LoginCtrl', function LoginCtrl($scope, $http, $window, $translate, $filter, $location, config, $stateParams) {
// The last parameter, config, is injected from config.js (defined in dashboardConfig module)
dashboardControllers.controller('LoginCtrl',
function LoginCtrl(
$scope,
$http,
$window,
$translate,
$filter,
$location,
config,
$stateParams,
ngToast) {
$scope.credentials = {
email: '',
password: '',
lang: 'es-es'
};
// Pop-up blocker check
// var popup = window.open('http://yottacode.com','','',true);
// setTimeout( function() {
// if(!popup || popup.outerHeight === 0) {
// alert("cáspita");
// } else {
// popup && popup.close();
// }
// }, 100);
// Array of key terms to translate
$translate(['login_success', 'login_fail']).then(function (translations) {
//notification_email = translations.email_match;
$scope.message_success = translations.login_success;
$scope.message_fail = translations.login_fail;
});
// Don't show the message at the begining
$scope.showmessage = false;
// Validation of account
// if the code has been sent in the url "...app/login/code/email"
if($stateParams.code && $stateParams.email){
console.log("Code: " + $stateParams.code + "\nEmail: " + $stateParams.email);
if ($stateParams.code && $stateParams.email) {
$http
.post(config.backend+'/sup/activate', $stateParams)
.success(function(data, status, headers, config) {
$scope.showmessage = true;
$scope.alert = "alert-success";
$scope.message = "account_activate";
console.log("Supervisor: " + data.user.name);
//console.log("Account validated: " + data.user.email + " --> " + data.user.active);
.post(config.backend + '/sup/activate', $stateParams)
.success(function () {
$translate('account_activate').then(function (translation) {
ngToast.success({ content: translation });
});
})
.error(function(data, status, headers, config) {
$scope.showmessage = true;
$scope.alert = "alert-danger";
$scope.message = "account_no_activate";
console.log("Account NOT validated! Error: " + data.error);
.error(function () {
$translate('account_no_activate').then(function (translation) {
ngToast.danger({ content: translation });
});
});
}
$scope.login = function () {
$http
.post(config.backend+'/sup/login', $scope.credentials)
.success(function(data, status, headers, config) {
// Save token and user data y sessionStorage
.post(config.backend + '/sup/login', $scope.credentials)
.success(function (data) {
$window.sessionStorage.token = data.token;
// Adapt language en-us to en-gb (the latter is the one supported for 'en')
if (data.user) {
if (data.user.lang === 'en-us')
if (data.user.lang === 'en-us') {
data.user.lang = 'en-gb';
$scope.lang = data.user.lang;
}
else
console.log("ERROR: no data.user!");
$scope.lang = data.user.lang;
} else {
$translate.use($scope.lang);
}
// Change
$window.sessionStorage.user = JSON.stringify(data.user);
// Quitar 4 líneas siguientes. Al hacer redirección no hace falta
$scope.showmessage = true;
$scope.alert = "alert-success";
$scope.message = "login_success";
$translate('login_success').then(function (translation) {
ngToast.success({ content: translation });
});
// Name in login success message
$scope.name = data.user.name;
console.log("logged in!");
// Redirección
$location.path('/students');
})
.error(function(data, status, headers, config) {
// Delete token if user fails to login
.error(function () {
delete $window.sessionStorage.token;
$scope.showmessage = true;
$scope.alert = "alert-danger";
$scope.message = "login_fail";
$translate('login_fail').then(function (translation) {
ngToast.danger({ content: translation });
});
}
});
};
});
......@@ -3,7 +3,7 @@
//------------------
// Login Controller
//------------------
dashboardControllers.controller('LoginAdminCtrl', function LoginAdminCtrl($scope, $http, $window, $translate, $location, config) {
dashboardControllers.controller('LoginAdminCtrl', function LoginAdminCtrl($scope, $http, $window, $translate, $location, config, ngToast) {
// The last parameter, config, is injected from config.js (defined in dashboardConfig module)
$scope.credentials = {
......@@ -11,16 +11,6 @@ dashboardControllers.controller('LoginAdminCtrl', function LoginAdminCtrl($scope
password: ''
};
// Array of key terms to translate
$translate(['login_success', 'login_fail']).then(function (translations) {
//notification_email = translations.email_match;
$scope.message_success = translations.login_success;
$scope.message_fail = translations.login_fail;
});
// Don't show the message at the begining
$scope.showmessage = false;
$scope.login = function () {
$http
.post(config.backend+'/admin/login', $scope.credentials)
......@@ -29,15 +19,18 @@ dashboardControllers.controller('LoginAdminCtrl', function LoginAdminCtrl($scope
$window.sessionStorage.token = data.token;
// Redirect to admin panel
$location.path('/devices');
$translate('login_success').then(function(translation) {
ngToast.success({ content: translation });
});
})
.error(function(data, status, headers, config) {
// Delete token if user fails to login
delete $window.sessionStorage.token;
$scope.showmessage = true;
$scope.alert = "alert-danger";
$scope.message = "login_fail";
$translate('login_fail').then(function(translation) {
ngToast.danger({ content: translation });
});
});
};
});
......@@ -3,33 +3,26 @@
//-----------------------------------
// Login Setting Password Controller
//-----------------------------------
dashboardControllers.controller('LoginSettingPasswordCtrl', function LoginSettingPasswordCtrl($scope, $http, $window, $translate, $location, config, $stateParams) {
// The last parameter, config, is injected from config.js (defined in dashboardConfig module)
// Array of key terms to translate
$translate(['validate_success', 'validate_fail']).then(function (translations) {
//notification_email = translations.email_match;
$scope.message_success = translations.validate_success;
$scope.message_fail = translations.validate_fail;
});
// Don't show the message at the begining
$scope.showmessage = false;
$scope.showlink = false;
dashboardControllers.controller('LoginSettingPasswordCtrl', function LoginSettingPasswordCtrl($scope, $http, $window, $translate, $location, config, $stateParams, ngToast) {
$scope.login_setting_password = function () {
// Validation of account
// if the code has been sent in the url "...app/login/code/email"
if($stateParams.code && $stateParams.email){
console.log("Code: " + $stateParams.code + "\nEmail: " + $stateParams.email);
if ($stateParams.code && $stateParams.email) {
// Validate password match
if($scope.password != $scope.password_confirm){
// ToDo: Highlight with Angular the input
$scope.showmessage = true;
$scope.alert = "alert-danger";
$scope.message = "password_match";
if ($scope.password != $scope.password_confirm) {
$translate([
'validate_fail',
'password_match'
], function (translations) {
ngToast.danger({
content: [
translations.validate_fail,
translations.password_match
].join(': ')
});
});
return;
}
......@@ -42,23 +35,15 @@ dashboardControllers.controller('LoginSettingPasswordCtrl', function LoginSettin
$http
.post(config.backend+'/sup/activate', data)
.success(function(data, status, headers, config) {
$scope.showmessage = true;
$scope.showlink = true;
$scope.hideform = true;
$scope.alert = "alert-success";
$scope.message = "validate_success";
console.log("Supervisor: " + data.user.name);
//console.log("Account validated: " + data.user.email + " --> " + data.user.active);
$translate('validate_success').then(function (translation) {
ngToast.success({ content: translation });
});
})
.error(function(data, status, headers, config) {
$scope.showmessage = true;
$scope.alert = "alert-danger";
$scope.message = "validate_fail";
console.log("Account NOT validated! Error: " + data.error);
$translate('validate_fail').then(function (translation) {
ngToast.danger({ content: translation });
});
});
}
};
});
/* global dashboardControllers */
'use strict';
//-------------------
// SignIn Controller
//-------------------
dashboardControllers.controller('SignInCtrl', function SignInCtrl($scope, $http, $window, reCAPTCHA, $translate, config) {
// The last parameter, config, is injected from config.js (defined in dashboardConfig module)
// The previous parameter, $translate, is a dependency injection to translate text in JavaScript controller code
// Data
dashboardControllers.controller('SignInCtrl',
function SignInCtrl($scope,
$http,
$window,
reCAPTCHA,
$translate,
config,
ngToast) {
$scope.formdata = {
name: '',
surname: '',
......@@ -23,69 +27,43 @@ dashboardControllers.controller('SignInCtrl', function SignInCtrl($scope, $http,
reCAPTCHA.setPublicKey('6LdLjh0TAAAAANblo_KUGNnmRZuIetOkdjdhj1b6');
/* NOT NECESSARY
// Array of key terms to translate
$translate(['password_match', 'email_match']).then(function (translations) {
//notification_email = translations.email_match;
$scope.email_message = translations.email_match;
$scope.password_message = translations.password_match;
});
*/
// Verificar. Si no es necesario eliminar
//reCAPTCHA.setPublicKey('gazpacho andaluz');
// Don't show the message at the begining
$scope.showmessage = false;
// Form submit
$scope.signin = function () {
//$scope.showmessage = false;
// Validate email match
if($scope.formdata.email != $scope.formdata.email_confirm){
// ToDo: Highlight with Angular the input
$scope.showmessage = true;
$scope.alert = "alert-danger";
$scope.message = "email_match";
if ($scope.formdata.email !== $scope.formdata.email_confirm) {
$translate('email_match').then(function (translation) {
ngToast.danger({ content: translation });
});
return;
}
// Validate password match
if($scope.formdata.password != $scope.formdata.password_confirm){
// ToDo: Highlight with Angular the input
$scope.showmessage = true;
$scope.alert = "alert-danger";
$scope.message = "password_match";
if ($scope.formdata.password !== $scope.formdata.password_confirm) {
$translate('password_match').then(function (translation) {
ngToast.danger({ content: translation });
});
return;
}
$scope.captcha = "";
$scope.captcha = '';
if($scope.signInForm.$valid) {
if ($scope.signInForm.$valid) {
$scope.showdialog = true;
console.log('Form is valid');
}else{
} else {
return;
}
$http
.post(config.backend+'/sup', $scope.formdata)
.success(function(data, status, headers, config) {
// ToDo: When this run well, redirect to main page
$scope.showmessage = true;
$scope.alert = "alert-success";
$scope.message = "user_created";
console.log("User created");
.post(config.backend + '/sup', $scope.formdata)
.success(function () {
$translate('user_created').then(function (translation) {
ngToast.success({ content: translation });
});
})
.error(function(data, status, headers, config) {
$scope.showmessage = true;
$scope.alert = "alert-danger";
$scope.message = "user_exists";
console.log("Error from API: " + status);
.error(function () {
$translate('user_exists').then(function (translation) {
ngToast.danger({ content: translation });
});
});
};
});
......@@ -13,14 +13,11 @@
<!-- LoginCtrl controls here, see app.js -->
<form name="loginForm" ng-submit="login()" novalidate>
<!-- Alert and success messages -->
<div ng-show="{{ 'showmessage' }}" class="alert" ng-class="alert" translate translate-value-name="{{name}}">{{message}}</div>
<div class="form-group">
<input type="email" class="form-control" id="login_email" placeholder="{{ 'your_email' | translate}}" required ng-model="credentials.email" ng-focus="showmessage = false" />
<input type="email" class="form-control" id="login_email" placeholder="{{ 'your_email' | translate}}" required ng-model="credentials.email" />
</div>
<div class="form-group">
<input type="password" class="form-control" id="login_password" placeholder="{{ 'your_password' | translate}}" required ng-model="credentials.password" ng-focus="showmessage = false" />
<input type="password" class="form-control" id="login_password" placeholder="{{ 'your_password' | translate}}" required ng-model="credentials.password" />
</div>
<div class="checkbox">
<label>
......
......@@ -12,9 +12,6 @@
<!-- Formulario -->
<!-- LoginAdminCtrl controls here, see app.js -->
<form name="loginForm" ng-submit="login()" novalidate>
<!-- Alert and success messages -->
<div ng-show="{{ 'showmessage' }}" class="alert" ng-class="alert" translate translate-value-name="{{name}}">{{message}}</div>
<h3 class="text-center" translate>admin_login</h3>
<div class="form-group">
......
......@@ -11,9 +11,6 @@
<img src="img/logo_pictogram.png" alt="Pictogram" title="Pictogram" />
</p>
<!-- Alert and success messages -->
<div ng-show="{{ 'showmessage' }}" class="alert" ng-class="alert" translate translate-value-name="{{name}}">{{message}}</div>
<div ng-show="{{ 'showlink' }}" class="text-center">
<a href="/app/#/login" translate>click_login</a>
</div>
......@@ -22,11 +19,11 @@
<form ng-hide="{{ 'hideform' }}" name="loginSettingPasswordForm" ng-submit="login_setting_password()">
<div class="form-group">
<input type="password" class="form-control" id="login_password" placeholder="{{ 'password_type' | translate}}" required ng-model="password" ng-focus="showmessage = false" />
<input type="password" class="form-control" id="login_password" placeholder="{{ 'password_type' | translate}}" required />
</div>
<div class="form-group">
<input type="password" class="form-control" id="login_password_confirm" placeholder="{{ 'password_confirm' | translate}}" required ng-model="password_confirm" ng-focus="showmessage = false" />
<input type="password" class="form-control" id="login_password_confirm" placeholder="{{ 'password_confirm' | translate}}" required ng-model="password_confirm" />
</div>
<p class="color_red text_sm text-center" ng-show="password != password_confirm" translate>password_match</p>
......
......@@ -18,10 +18,6 @@
<!-- Formulario -->
<form name="signInForm" role="form" ng-submit="signin()">
<!-- Alert and success messages -->
<div ng-show="{{ 'showmessage' }}" class="alert" ng-class="alert" translate translate-values="{name: formdata.name, surname: formdata.surname, email: formdata.email}">{{message}}</div>
<fieldset>
<legend translate>personal_data</legend>
<div class="form-group">
......
/* global dashboardControllers */
'use strict';
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.
dashboardControllers.controller('AddPictoCtrl', function ($scope, $modalInstance, $http, config, $window, $filter, $upload, stu_id, sup, studentPictos, categories, $modal) {
dashboardControllers.controller('AddPictoCtrl', function (
$scope,
$modalInstance,
$http,
config,
$window,
$filter,
$upload,
stu_id,
sup,
studentPictos,
categories,
$modal,
$translate,
ngToast) {
var i;
var cat_id;
// Last 4 parameters passed from collections.js
// Basic data passed from the main window
$scope.sup = sup;
......@@ -11,16 +29,16 @@ dashboardControllers.controller('AddPictoCtrl', function ($scope, $modalInstance
// Initially the source is symbolstx collection
$scope.source = 'symbolstx';
// List of studentPictos
//console.log(JSON.stringify(studentPictos));
$scope.studentPictos = studentPictos;
// List of picto categories
// console.log(JSON.stringify(categories));
$scope.categories = categories;
// Array scope for pictos dragged into categories
$scope.pictos_in_category = {};
for(var i=0; i<$scope.categories.length;i++){
var cat_id = $scope.categories[i].picto.id;
$scope.pictos_in_category['cat'+cat_id]=[];
for (i = 0; i < $scope.categories.length; i++) {
cat_id = $scope.categories[i].picto.id;
$scope.pictos_in_category['cat' + cat_id] = [];
}
// List of actual pictos (showed by navigation)
......@@ -29,37 +47,35 @@ dashboardControllers.controller('AddPictoCtrl', function ($scope, $modalInstance
$scope.symbolstxCats = [];
// List of breadcrumbs to show in navigation
$scope.breadcrumbs = [];
$scope.breadcrumbs.push({ id: 0, exp: 'Inicio', glyphicon: 'glyphicon glyphicon-home'});
$scope.breadcrumbs.push({ id: 0, exp: 'Inicio', glyphicon: 'glyphicon glyphicon-home' });
// Request of general pictos categories (symbolstx)
$http
.get(config.backend+'/sup/'+ $scope.sup.id +'/pic_categories/0')
.success(function(data, status, headers, config) {
// Add to list
$http.get(config.backend + '/sup/' + $scope.sup.id + '/pic_categories/0')
.success(function (data) {
$scope.symbolstxCats = data;
console.log("Symbolstx categories recovered");
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
.error(function () {
$translate('error_loading_pictos').then(function (translation) {
ngToast.danger({ content: translation });
});
});
//
// Load pictos from a category
//
$scope.load_pictos = function (id_cat){
$http
.get(config.backend+'/sup/'+ $scope.sup.id +'/pic_fromcategory/' + id_cat)
.success(function(data, status, headers, config) {
// Add to list
if (data)
$scope.load_pictos = function (id_cat) {
$http.get(config.backend + '/sup/' + $scope.sup.id + '/pic_fromcategory/' + id_cat)
.success(function (data) {
if (data) {
$scope.pictos = data;
else $scope.pictos = [];
//console.log(JSON.stringify($scope.pictos));
console.log("Pictos listed" + JSON.stringify(data));
} else {
$scope.pictos = [];
}
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
.error(function () {
$translate('error_loading_pictos').then(function (translation) {
ngToast.danger({ content: translation });
});
});
};
......@@ -67,20 +83,20 @@ dashboardControllers.controller('AddPictoCtrl', function ($scope, $modalInstance
// Load pictos from owned by the actual supervisor
// TEST --> change with real supervisor pictos
//
$scope.load_own_pictos = function (){
$scope.load_own_pictos = function () {
$scope.source = 'ownpictos';
$http
.get(config.backend+'/sup/'+ $scope.sup.id +'/pictos')
.success(function(data, status, headers, config) {
// Add to list
if (data)
$http.get(config.backend + '/sup/' + $scope.sup.id + '/pictos')
.success(function (data) {
if (data) {
$scope.pictos = data;
else $scope.pictos = [];
console.log(JSON.stringify($scope.pictos));
console.log("Pictos listed");
} else {
$scope.pictos = [];
}
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
.error(function () {
$translate('error_loading_pictos').then(function (translation) {
ngToast.danger({ content: translation });
});
});
};
......@@ -88,18 +104,14 @@ dashboardControllers.controller('AddPictoCtrl', function ($scope, $modalInstance
// Load the folders of a category
//
$scope.load_category = function (id_cat){
$http
.get(config.backend+'/sup/'+ $scope.sup.id +'/pic_categories/' + id_cat)
$http.get(config.backend+'/sup/'+ $scope.sup.id +'/pic_categories/' + id_cat)
.success(function(data, status, headers, config) {
// Add to list
if (data)
$scope.symbolstxCats = data;
else $scope.symbolstxCats = [];
console.log("Symbolstx categories recovered");
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
});
};
......
/* global dashboardControllers, io */
'use strict';
//-----------------------
// Student Controller
//-----------------------
dashboardControllers.controller('StudentCtrl', function StudentCtrl($scope, config, $state, $http, $window, $filter, $rootScope) {
/**
* StudentCtrl
*/
dashboardControllers.controller('StudentCtrl', function StudentCtrl(
$scope,
config,
$state,
$http,
$window,
$filter,
$translate,
ngToast) {
var i;
var j;
$scope.studentData = {
id: '',
......@@ -38,24 +50,24 @@ dashboardControllers.controller('StudentCtrl', function StudentCtrl($scope, conf
//
// WebSockets communication
//
io.socket.on('update_peers', function(data) {
console.log(data.count + ' peers connected');
io.socket.on('update_peers', function (data) {
$translate('num_peers').then(function (translation) {
ngToast.success(translation + ': ' + data.count);
});
$scope.studentData.num_peers = data.count;
});
io.socket.on('reconnect', function () {
// Subscribe to student's socket room
console.log("reconnecting to socket");
io.socket.post('/stu/subscribe', {
action: 'subscribe',
attributes:{
attributes: {
id_stu: $scope.studentData.id
},
token: $window.sessionStorage.token
},
function(res) {
console.log("Connected to student: " + res.msg);
function () {
// TODO ngToast res.msg (connected to student room)
});
});
......@@ -65,10 +77,8 @@ dashboardControllers.controller('StudentCtrl', function StudentCtrl($scope, conf
//
//
$http
.get(config.backend+'/stu/' + $scope.studentData.id)
.success(function(data, status, headers, config) {
// studentData
$http.get(config.backend + '/stu/' + $scope.studentData.id)
.success(function (data) {
$scope.studentData.id = data.id;
$scope.studentData.username = data.username;
$scope.studentData.name = data.name;
......@@ -98,42 +108,28 @@ dashboardControllers.controller('StudentCtrl', function StudentCtrl($scope, conf
$scope.formUser.lang = $scope.studentData.lang;
$scope.formUser.notes = $scope.studentData.notes;
console.log("Student personal data recovered");
console.log(JSON.stringify($scope.studentData));
console.log("Attributes: " + JSON.stringify($scope.studentData.attributes));
console.log("Sups: " + JSON.stringify($scope.studentData.stuSup));
//////////////////////////////////////////////////////////
// Subscribe to student's socket room
console.log("connecting to socket");
io.socket.post('/stu/subscribe', {
action: 'subscribe',
attributes:{
attributes: {
id_stu: $scope.studentData.id
},
token: $window.sessionStorage.token
},
function(res) {
console.log("Connected to student: " + res.msg);
function () {
// TODO ngToast res.msg (connected to student room)
});
//////////////////////////////////////////////////////////
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
.error(function () {
// TODO ngToast res.msg (cant connect to student room)
});
// For tab navigation, initially blank goes to collections
// Defined as JSON object to be available in in children as the same scope
$scope.nav = {
tab : 'collections'
tab: 'collections'
};
// ----------------------------------------------------------------------
// COLLECTION
// Load student collection
//
// List of all student pictos
$scope.studentPictos = [];
// List of categories pictos
......@@ -148,131 +144,75 @@ dashboardControllers.controller('StudentCtrl', function StudentCtrl($scope, conf
};
// Initialization of PCB (the tablet view) and PCB-Categories
$scope.pcb_rows = 5, $scope.pcb_cols = 10;
$scope.pcb_rows = 5;
$scope.pcb_cols = 10;
$scope.pcb = [];
$scope.pcb_cat = [];
$scope.pcb = new Array(); $scope.pcb_cat = new Array();
// Set the empty elements
for (var i=0;i<$scope.pcb_rows;i++) {
$scope.pcb[i]=new Array(); $scope.pcb_cat[i]=new Array();
for (var j=0;j<$scope.pcb_cols; j++) {
// Default value
$scope.pcb[i][j]={'picto': {'uri': '/app/img/empty.gif'}, 'attributes': {'coord_x': i, 'coord_y': j}};
$scope.pcb_cat[i][j]={'picto': {'uri': '/app/img/empty.gif'}, 'attributes': {'coord_x': i, 'coord_y': j}};
for (i = 0; i < $scope.pcb_rows; i++) {
$scope.pcb[i] = [];
$scope.pcb_cat[i] = [];
for (j = 0; j < $scope.pcb_cols; j++) {
$scope.pcb[i][j] = {
picto: { uri: '/app/img/empty.gif' },
attributes: { coord_x: i, coord_y: j }
};
$scope.pcb_cat[i][j] = {
picto: { uri: '/app/img/empty.gif' },
attributes: { coord_x: i, coord_y: j }
};
}
}
$http
.get(config.backend+'/stu/'+ $scope.studentData.id +'/pictos')
.success(function(data, status, headers, config) {
// Add to list
$http.get(config.backend + '/stu/' + $scope.studentData.id + '/pictos')
.success(function (data) {
var k;
var pic;
$scope.studentPictos = data;
//console.log(JSON.stringify($scope.pcb_cat));
$scope.pictosCategory = $filter('filter')($scope.studentPictos, {attributes: { id_cat: null }});
console.log("Pictos Categories: " + JSON.stringify($scope.pictosCategory));
$scope.pictosCategory = $filter('filter')($scope.studentPictos, {
attributes: {
id_cat: null
}
});
// Build the pcb_cat with the coords of the pictos
for(var i=0; i < $scope.pictosCategory.length; i++) {
var pic = $scope.pictosCategory[i];
for (k = 0; k < $scope.pictosCategory.length; k++) {
pic = $scope.pictosCategory[k];
$scope.pcb_cat[pic.attributes.coord_x][pic.attributes.coord_y] = pic;
console.log("Pic " + pic.id + ": " + pic.attributes.color );
}
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
}); // Filtered only the categories pictos
////////////////////////////////////////////////////////////////////////////
// Devices /////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
/*
// For mark in list the actual device (Received from PCB via websocket)
$scope.active_device = null;
// 1) Leer los dispositivos del alumno y mostrar en listado
// Array with student's devices
$scope.devices = [];
// Query to obtain an array of student devices
$http
.get(config.backend+'/stu/'+ $scope.studentData.id +'/devices')
.success(function(data, status, headers, config) {
// Add to list
$scope.devices = data;
console.log(JSON.stringify($scope.devices));
console.log("Devices recovered");
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
.error(function () {
$translate('error_loading_pictos').then(function (translation) {
ngToast.danger({ content: translation });
});
});
*/
// ----------------------------------------------------------------------
// REPORTS
// Load information for reports
//
//
// NOTE: this information is created when the tab is selected, so information
// is always updated
// ----------------------------------------------------------------------
// SETUP
// Load student configuration
//
// *******************************************************
// Therapists
// List of student's therapists
$scope.studentSupervisors = [];
$http
.get(config.backend+'/stu/'+ $scope.studentData.id +'/therapists')
.success(function(data, status, headers, config) {
// Add to list
$http.get(config.backend + '/stu/' + $scope.studentData.id + '/therapists')
.success(function (data) {
$scope.studentSupervisors = data;
console.log(JSON.stringify($scope.studentSupervisors));
console.log("Supervisors listed");
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
.error(function () {
// TODO show error with ngToast
});
// List of student's tutors (parents)
$scope.studentTutors = [];
$http
.get(config.backend+'/stu/'+ $scope.studentData.id +'/tutors')
.success(function(data, status, headers, config) {
// Add to list
$http.get(config.backend + '/stu/' + $scope.studentData.id + '/tutors')
.success(function (data) {
$scope.studentTutors = data;
console.log(JSON.stringify($scope.studentTutors));
console.log("Tutors listed");
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
.error(function () {
// TODO show error with ngToast
});
// *******************************************************
// Devices
// List of student's devices
$scope.studentDevices = [];
$http
.get(config.backend+'/stu/'+ $scope.studentData.id +'/devices')
.success(function(data, status, headers, config) {
// Add to list
$http.get(config.backend + '/stu/' + $scope.studentData.id + '/devices')
.success(function (data) {
$scope.studentDevices = data;
console.log("Devices listed: ");
console.log(JSON.stringify($scope.studentDevices));
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
.error(function () {
// TODO show error with ngToast
});
/*
// Events handling
io.socket.on('action', function(data) {
console.log('"action" event received with the following data:');
console.log(data.msg);
});*/
});
'use strict';
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.
/* global dashboardControllers */
dashboardControllers.controller('TagsCtrl', function ($scope, $modalInstance, $http, config, stuPicto, sup) {
// Last parameter passed from collections.js
// Basic data passed from the main window
'use strict';
/**
* TagsCtrl
*/
dashboardControllers.controller('TagsCtrl', function TagsCtrl(
$scope,
$modalInstance,
$http,
config,
stuPicto,
sup,
$translate,
ngToast) {
// Supervisor
$scope.sup = sup;
// List of general tags
......@@ -15,66 +22,62 @@ dashboardControllers.controller('TagsCtrl', function ($scope, $modalInstance, $h
$scope.ownTags = [];
// Request of general tags
$http
.get(config.backend+'/picto/' + stuPicto.picto.id)
.success(function(data, status, headers, config) {
// Add to lists
$http.get(config.backend + '/picto/' + stuPicto.picto.id)
.success(function (data) {
$scope.tags = data.tags;
$scope.ownTags = data.tagsSup;
console.log("Tags recovered");
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
.error(function () {
$translate('error_loading_pictos').then(function (translation) {
ngToast.danger({ content: translation });
});
});
// Add own tag
$scope.add = function () {
$http
.post(config.backend+'/picto/tag',
{ 'picto': stuPicto.picto.id,
'supervisor': $scope.sup.id,
'tag': $scope.tagToAdd,
'lang': $scope.sup.lang
})
.success(function(data, status, headers, config) {
console.log("Tag added: " + JSON.stringify(data));
$http.post(config.backend + '/picto/tag',
{
picto: stuPicto.picto.id,
supervisor: $scope.sup.id,
tag: $scope.tagToAdd,
lang: $scope.sup.lang
}
)
.success(function (data) {
$scope.ownTags.push(data);
$scope.tagToAdd = "";
$scope.tagToAdd = '';
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
.error(function () {
// TODO show error with ngToast
});
};
// Destroy own tag
$scope.del = function (tag) {
$http
.delete(config.backend+'/picto/tag/' + tag.id)
.success(function(data, status, headers, config) {
console.log("Tag destroyed: " + JSON.stringify(data));
$http.delete(config.backend + '/picto/tag/' + tag.id)
.success(function () {
var i;
// TODO show success with ngToast
// Eliminar de la vista: Se recorre el array de objetos json para buscarlo
for(var i=0; i < $scope.ownTags.length; i++) {
if(tag.id == $scope.ownTags[i].id)
$scope.ownTags.splice(i,1);
for (i = 0; i < $scope.ownTags.length; i++) {
if (tag.id === $scope.ownTags[i].id) {
$scope.ownTags.splice(i, 1);
}
}
})
.error(function(data, status, headers, config) {
console.log("Error from API: " + data.error);
.error(function () {
// TODO show error with ngToast
});
};
$scope.close = function () {
$modalInstance.close("Ejemplo de elemento devuelto");
// TODO ¿?¿?
$modalInstance.close('Ejemplo de elemento devuelto');
};
// No usado
$scope.cancel = function () {
// TODO ¿?¿?
$modalInstance.dismiss('cancel');
};
});
<toast></toast>
<!-- Instrucction tab-->
<div class="panel panel-default student_tab_panel">
......
<div class="panel panel-default student_tab_panel">
<div class="panel-body">
<!-- Alert and success messages -->
<div ng-show="{{ 'showmessagestudent' }}" class="alert" ng-class="alertstudent">{{ messagestudent | translate }}</div>
<div class="row">
<!-- Parte izquierda: Datos personales -->
<div class="col-md-6">
......@@ -120,8 +116,6 @@
<img ng-src="{{supToAdd.pic}}" class="profile" alt="" title="" /> {{ supToAdd.name }} {{ supToAdd.surname }}
<a class="btn btn-default btn-lg pull-right" role="button" ng-click="add_sup()" translate>add</a>
</div>
<div ng-show="{{ 'showmessagesupnotfound' }}" class="alert alert-warning">{{ messagesup | translate }}</div>
<!-- Fin de buscador de supervisores -->
<!-- Supervisores asignados -->
......@@ -162,8 +156,6 @@
<img ng-src="{{tutorToAdd.pic}}" class="profile" alt="" title="" /> {{ tutorToAdd.name }} {{ tutorToAdd.surname }}
<a class="btn btn-default btn-sm pull-right" role="button" ng-click="add_tutor()" translate>add</a>
</div>
<div ng-show="{{ 'showmessagetutornotfound' }}" class="alert alert-warning">{{ messagetutor | translate }}</div>
<!-- Fin de buscador de tutores -->
<!-- Tutores asignados -->
......
/* global dashboardControllers */
'use strict';
//------------------
// Setup Controller
//------------------
dashboardControllers.controller('SetupCtrl', function SetupCtrl($scope, $http, $window, $translate, $location, $upload, config) {
// The last parameter, config, is injected from config.js (defined in dashboardConfig module)
/**
* SetupCtrl
*/
dashboardControllers.controller('SetupCtrl', function SetupCtrl(
$scope,
$http,
$window,
$translate,
$location,
$upload,
ngToast,
config) {
var user;
// Don't show the message at the begining
$scope.showmessage = false;
// Restore user values from sessionStorage
var user = JSON.parse($window.sessionStorage.user);
// Fill the form with the user data
user = JSON.parse($window.sessionStorage.user);
$scope.formdata = user;
// Testing --> DELETE
console.log("User id: " + user.id.toString());
console.log("User id to hashcode: " + user.id.toString().hashCode());
// When a picture is selected, launch the request
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
// Check accepted file types
if(file.type == "image/jpeg" || file.type == "image/png" || file.type == "image/gif"){
// Get the file extension
var extension = file.name.split('.').pop();
var filename = user.id + file.name;
console.log("Archivo: " + filename);
$scope.onFileSelect = function ($files) {
var i;
var file;
var extension;
var filename;
for (i = 0; i < $files.length; i++) {
file = $files[i]; // { name, size, type }
if (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif') {
extension = file.name.split('.').pop();
filename = user.id + file.name;
$upload.upload({
url: '/sup/upload', //upload.php script, node.js route, or servlet url
url: '/sup/upload', // upload.php script, node.js route, or servlet url
method: 'POST', // or 'PUT',
// Fields to sent in the body of the request
fields: {'filename': filename, 'extension': extension, 'folder': 'supervisors', 'id': user.id},
// or ['1.jpg', '2.jpg', ...] // to modify the name of the file(s)
file: file, // or list of files ($files) for html5 only
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(JSON.stringify(data.file));
// Assign the new image with new name
$scope.user.pic = "/upload/supervisors/" + data.file.name;
//$scope.picture = user.id + "." + extension + "?t=" + new Date().getTime();
// Modify the user in session
var user = JSON.parse($window.sessionStorage.user);
fields: {
filename: filename,
extension: extension,
folder: 'supervisors',
id: user.id
},
file: file
})
.progress(function () {
// TODO show file upload progress to user
})
.success(function (data) {
// TODO show success ngToast
$scope.user.pic = '/upload/supervisors/' + data.file.name;
user.pic = $scope.user.pic;
$window.sessionStorage.user = JSON.stringify(user);
});
}else{
alert("It's only supported JPG, PNG and GIF files");
} else {
$translate('error_only_support_images').then(function (translation) {
ngToast.error({ content: translation });
});
}
}
};
// Form submit
$scope.setup = function () {
var supervisor;
var actualEmail;
//$scope.showmessage = false;
// Validate password match
if($scope.formdata.password != $scope.formdata.password_confirm){
// ToDo: Highlight with Angular the input
$scope.showmessage = true;
$scope.alert = "alert-danger";
$scope.message = "password_match";
if ($scope.formdata.password !== $scope.formdata.password_confirm) {
$translate('password_match').then(function (translation) {
ngToast.danger({ content: translation });
});
return;
}
if($scope.setupForm.$valid) {
// $scope.showdialog = true;
console.log('Form is valid');
}else{
if (!$scope.setupForm.$valid) {
$translate('invalid_fields').then(function (translation) {
ngToast.danger({ content: translation });
});
return;
}
var supervisor = $scope.formdata;
var actual_email = JSON.parse($window.sessionStorage.user).email;
supervisor = $scope.formdata;
actualEmail = JSON.parse($window.sessionStorage.user).email;
// Comprobation for new email
// If no change, it is deleted from supervisor object
if(supervisor.email == actual_email)
if (supervisor.email === actualEmail) {
delete supervisor.email;
}
// console.log($scope.formdata.uploadFile);
$http
.put(config.backend+'/sup', supervisor)
.success(function(data, status, headers, config) {
// ToDo: When this run well, redirect to main page
$scope.showmessage = true;
$scope.alert = "alert-success";
$scope.message = "data_saved";
$http.put(config.backend + '/sup', supervisor)
.success(function (data) {
$translate('data_saved').then(function (translation) {
ngToast.success({ content: translation });
});
// Modify the name in the header
$scope.name = data.name + " " + data.surname;
$scope.name = data.name + ' ' + data.surname;
// Modify the user data in session
user.name = data.name;
user.surname = data.surname;
......@@ -113,16 +114,11 @@ dashboardControllers.controller('SetupCtrl', function SetupCtrl($scope, $http, $
delete user.password_confirm;
$window.sessionStorage.user = JSON.stringify(user);
console.log("User modified");
})
.error(function(data, status, headers, config) {
$scope.showmessage = true;
$scope.alert = "alert-danger";
$scope.message = "data_no_saved";
console.log("Error from API: " + data.error);
.error(function () {
$translate('data_no_saved').then(function (translation) {
ngToast.danger({ content: translation });
});
});
};
});
/* global io */
'use strict';
//-----------------------
// Supervisor Controller
//-----------------------
dashboardControllers.controller('SupervisorCtrl', function SupervisorCtrl($scope, $window, $location) {
dashboardControllers.controller('SupervisorCtrl', function SupervisorCtrl($scope, $window, $location, IOService) {
// Restore user data from session
var user = JSON.parse($window.sessionStorage.user);
......@@ -22,4 +24,11 @@ dashboardControllers.controller('SupervisorCtrl', function SupervisorCtrl($scope
$location.path('/setup');
};
// Subscribe to the supervisor's room
IOService.post('/sup/subscribe', {
action: 'subscribe',
attributes: {
id_sup: $scope.user.id
}
});
});
......@@ -9,9 +9,6 @@
<!-- Formulario -->
<form name="setupForm" enctype="multipart/form-data" role="form" ng-submit="setup()">
<!-- Alert and success messages -->
<div ng-show="{{ 'showmessage' }}" class="alert" ng-class="alert" translate>{{message}}</div>
<!-- Change profile picture -->
<input type="file" ng-file-select="onFileSelect($files)" ng-model="picFile" accept="image/*">
......@@ -102,4 +99,3 @@
</div>
<toast></toast>
<!-- StudentsCtrl controls here, see app.js -->
<div class="panel panel-default">
<!-- Default panel contents -->
......
......@@ -45,7 +45,9 @@ module.exports.policies = {
destroy: ['tokenAuth', 'isAdmin'],
students: ['tokenAuth'],
pictos: ['tokenAuth'],
upload: ['tokenAuth']
upload: ['tokenAuth'],
subscribe: ['tokenAuth'],
unsubscribe: ['tokenAuth']
},
DeviceController: {
register: true,
......
......@@ -22,16 +22,7 @@
module.exports.routes = {
/***************************************************************************
* *
* Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, *
* etc. depending on your default view engine) your home page. *
* *
* (Alternatively, remove this and add an `index.html` file in your *
* `assets` directory) *
* *
***************************************************************************/
// Supervisor
'post /sup/login': 'SupervisorController.login',
'post /sup': 'SupervisorController.create',
'put /sup': 'SupervisorController.update',
......@@ -40,13 +31,15 @@ module.exports.routes = {
'get /sup/get/:id': 'SupervisorController.findOne',
'post /sup/activate': 'SupervisorController.activate',
'get /sup/:id/students': 'SupervisorController.students',
'post /sup/subscribe': 'SupervisorController.subscribe',
'post /sup/unsubscribe': 'SupervisorController.unsubscribe',
'post /sup/upload': 'SupervisorController.upload', // upload profile img file
// Pictos
'get /sup/:id/pictos': 'SupervisorController.pictos',
'get /sup/:id/pic_categories/:id_cat': 'Picto.categories',
'get /sup/:id/pic_fromcategory/:id_cat': 'Picto.fromcategory',
'post /sup/upload': 'SupervisorController.upload', // upload profile img file
// Pictogram administration
'post /admin/login': 'AdminController.login',
......
......@@ -14,7 +14,7 @@
"lodash": "^3.10.1",
"mocha": "^2.3.4",
"rc": "~0.5.0",
"sails": "^0.11.3",
"sails": "^0.12.3",
"sails-disk": "~0.10.0",
"sails-generate-auth": "^0.2.0",
"sails-mysql": "^0.10.12",
......@@ -35,6 +35,10 @@
"author": "emblanco, amontejo",
"license": "",
"devDependencies": {
"eslint": "^2.8.0",
"eslint-config-airbnb": "^7.0.0",
"eslint-plugin-jsx-a11y": "^1.0.1",
"eslint-plugin-react": "^5.0.1",
"node-inspector": "^0.12.8"
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment