1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2025-01-14 14:43:17 +08:00

source style cleanup

This commit is contained in:
Braun Patrik 2016-05-09 17:04:56 +02:00
parent 0f92ad983b
commit ef5758f3c7
60 changed files with 549 additions and 601 deletions

View File

@ -1,4 +1,3 @@
import {ConfigLoader} from "./ConfigLoader"; import {ConfigLoader} from "./ConfigLoader";
import * as path from "path"; import * as path from "path";
@ -6,10 +5,10 @@ export enum DatabaseType{
memory, mongoDB memory, mongoDB
} }
export class ConfigClass{ export class ConfigClass {
constructor(){ constructor() {
ConfigLoader.init(this,path.join(__dirname,'./../../config.json')); ConfigLoader.init(this, path.join(__dirname, './../../config.json'));
} }
public PORT:number = 80; public PORT:number = 80;

View File

@ -1,10 +1,9 @@
import * as fs from 'fs'; import * as fs from "fs";
import * as optimist from 'optimist'; import * as optimist from "optimist";
export class ConfigLoader { export class ConfigLoader {
static init(configObject:any, configFilePath?:string) {
static init(configObject:any, configFilePath?:string){
this.processConfigFile(configFilePath, configObject); this.processConfigFile(configFilePath, configObject);
this.processArguments(configObject); this.processArguments(configObject);
this.processEnvVariables(configObject); this.processEnvVariables(configObject);
@ -25,16 +24,16 @@ export class ConfigLoader {
let keyArray = key.split("-"); let keyArray = key.split("-");
let value = argv[key]; let value = argv[key];
let setObject = (object,keyArray,value) => { let setObject = (object, keyArray, value) => {
let key = keyArray.shift(); let key = keyArray.shift();
object[key] = {}; object[key] = {};
if(keyArray.length == 0){ if (keyArray.length == 0) {
object[key] = value; object[key] = value;
return; return;
} }
return setObject(object[key],keyArray,value); return setObject(object[key], keyArray, value);
}; };
setObject(config,keyArray,value); setObject(config, keyArray, value);
}); });
this.loadObject(configObject, config); this.loadObject(configObject, config);
@ -48,39 +47,38 @@ export class ConfigLoader {
} }
}; };
private static loadConfigFile(configFilePath,configObject):boolean{ private static loadConfigFile(configFilePath, configObject):boolean {
if(fs.existsSync(configFilePath) === false){ if (fs.existsSync(configFilePath) === false) {
return false; return false;
} }
try { try {
let config = JSON.parse(fs.readFileSync(configFilePath, 'utf8')); let config = JSON.parse(fs.readFileSync(configFilePath, 'utf8'));
this.loadObject(configObject,config); this.loadObject(configObject, config);
return true; return true;
}catch(err){ } catch (err) {
} }
return false; return false;
} }
private static saveConfigFile(configFilePath, configObject) {
private static saveConfigFile(configFilePath,configObject){
try { try {
fs.writeFileSync(configFilePath, JSON.stringify(configObject, null, 4)); fs.writeFileSync(configFilePath, JSON.stringify(configObject, null, 4));
}catch(err){ } catch (err) {
} }
} }
private static loadObject(targetObject,sourceObject){ private static loadObject(targetObject, sourceObject) {
Object.keys(sourceObject).forEach((key)=> { Object.keys(sourceObject).forEach((key)=> {
if(typeof targetObject[key] === "undefined"){ if (typeof targetObject[key] === "undefined") {
return; return;
} }
if(typeof targetObject[key] === "object"){ if (typeof targetObject[key] === "object") {
this.loadObject(targetObject[key],sourceObject[key] ); this.loadObject(targetObject[key], sourceObject[key]);
}else { } else {
targetObject[key] = sourceObject[key]; targetObject[key] = sourceObject[key];
} }
}); });

View File

@ -1,7 +1,6 @@
///<reference path="ExtendedRequest.d.ts"/> ///<reference path="ExtendedRequest.d.ts"/>
///<reference path="../../typings/main.d.ts"/> ///<reference path="../../typings/main.d.ts"/>
import {NextFunction, Request, Response} from "express"; import {NextFunction, Request, Response} from "express";
import {Error, ErrorCodes} from "../../common/entities/Error"; import {Error, ErrorCodes} from "../../common/entities/Error";
import {UserRoles} from "../../common/entities/User"; import {UserRoles} from "../../common/entities/User";
@ -9,16 +8,15 @@ import {ObjectManagerRepository} from "../model/ObjectManagerRepository";
export class AuthenticationMWs { export class AuthenticationMWs {
public static authenticate(req:Request, res:Response, next:NextFunction) {
public static authenticate(req:Request, res:Response, next:NextFunction){ /* if (typeof req.session.user === 'undefined') {
/* if (typeof req.session.user === 'undefined') { return next(new Error(ErrorCodes.NOT_AUTHENTICATED));
return next(new Error(ErrorCodes.NOT_AUTHENTICATED)); }*/
}*/
//TODO: uncomment //TODO: uncomment
return next(); return next();
} }
public static authorise(role:UserRoles){ public static authorise(role:UserRoles) {
return (req:Request, res:Response, next:NextFunction) => { return (req:Request, res:Response, next:NextFunction) => {
if (req.session.user.role < role) { if (req.session.user.role < role) {
return next(new Error(ErrorCodes.NOT_AUTHORISED)); return next(new Error(ErrorCodes.NOT_AUTHORISED));
@ -27,23 +25,23 @@ export class AuthenticationMWs {
}; };
} }
public static inverseAuthenticate(req:Request, res:Response, next:NextFunction){ public static inverseAuthenticate(req:Request, res:Response, next:NextFunction) {
if (typeof req.session.user !== 'undefined') { if (typeof req.session.user !== 'undefined') {
return next(new Error(ErrorCodes.ALREADY_AUTHENTICATED)); return next(new Error(ErrorCodes.ALREADY_AUTHENTICATED));
} }
return next(); return next();
} }
public static login(req:Request, res:Response, next:NextFunction){ public static login(req:Request, res:Response, next:NextFunction) {
//not enough parameter //not enough parameter
if ((typeof req.body === 'undefined') || (typeof req.body.loginCredential === 'undefined') || (typeof req.body.loginCredential.username === 'undefined') || if ((typeof req.body === 'undefined') || (typeof req.body.loginCredential === 'undefined') || (typeof req.body.loginCredential.username === 'undefined') ||
(typeof req.body.loginCredential.password === 'undefined')) { (typeof req.body.loginCredential.password === 'undefined')) {
return next(); return next();
} }
//lets find the user //lets find the user
ObjectManagerRepository.getInstance().getUserManager().findOne({ ObjectManagerRepository.getInstance().getUserManager().findOne({
name: req.body.loginCredential.username, name: req.body.loginCredential.username,
password: req.body.loginCredential.password password: req.body.loginCredential.password
}, (err, result) => { }, (err, result) => {
if ((err) || (!result)) { if ((err) || (!result)) {
return next(new Error(ErrorCodes.CREDENTIAL_NOT_FOUND)); return next(new Error(ErrorCodes.CREDENTIAL_NOT_FOUND));
@ -57,7 +55,4 @@ export class AuthenticationMWs {
} }
} }

View File

@ -1,17 +1,16 @@
declare module Express { declare module Express {
export interface Request{ export interface Request {
resultPipe?:any resultPipe?:any
body?:{ body?:{
loginCredential loginCredential
} }
} }
export interface Response{ export interface Response {
tpl?:any tpl?:any
} }
export interface Session { export interface Session {
user?; user?;
} }
} }

View File

@ -1,9 +1,7 @@
import * as path from "path";
import * as path from 'path'; import * as fs from "fs";
import * as fs from 'fs';
import {NextFunction, Request, Response} from "express"; import {NextFunction, Request, Response} from "express";
import {Error, ErrorCodes} from "../../common/entities/Error"; import {Error, ErrorCodes} from "../../common/entities/Error";
import {GalleryManager} from "../model/memory/GalleryManager";
import {Directory} from "../../common/entities/Directory"; import {Directory} from "../../common/entities/Directory";
import {Config} from "../config/Config"; import {Config} from "../config/Config";
import {ObjectManagerRepository} from "../model/ObjectManagerRepository"; import {ObjectManagerRepository} from "../model/ObjectManagerRepository";
@ -12,35 +10,35 @@ import {AutoCompleteItem} from "../../common/entities/AutoCompleteItem";
export class GalleryMWs { export class GalleryMWs {
private static getImageFolder(){ private static getImageFolder() {
return path.join(__dirname,"/../../",Config.imagesFolder); return path.join(__dirname, "/../../", Config.imagesFolder);
} }
public static listDirectory(req:Request, res:Response, next:NextFunction){ public static listDirectory(req:Request, res:Response, next:NextFunction) {
let directoryName = req.params.directory || "/"; let directoryName = req.params.directory || "/";
let absoluteDirectoryName = path.join(GalleryMWs.getImageFolder(), directoryName); let absoluteDirectoryName = path.join(GalleryMWs.getImageFolder(), directoryName);
if(!fs.statSync(absoluteDirectoryName).isDirectory()){ if (!fs.statSync(absoluteDirectoryName).isDirectory()) {
return next(); return next();
} }
ObjectManagerRepository.getInstance().getGalleryManager().listDirectory(directoryName,(err,directory:Directory) => { ObjectManagerRepository.getInstance().getGalleryManager().listDirectory(directoryName, (err, directory:Directory) => {
if(err || !directory){ if (err || !directory) {
return next(new Error(ErrorCodes.GENERAL_ERROR,err)); return next(new Error(ErrorCodes.GENERAL_ERROR, err));
} }
req.resultPipe = directory; req.resultPipe = directory;
return next(); return next();
}); });
} }
public static loadImage(req:Request, res:Response, next:NextFunction){ public static loadImage(req:Request, res:Response, next:NextFunction) {
if(!(req.params.imagePath)){ if (!(req.params.imagePath)) {
return next(); return next();
} }
let fullImagePath = path.join(GalleryMWs.getImageFolder(), req.params.imagePath); let fullImagePath = path.join(GalleryMWs.getImageFolder(), req.params.imagePath);
if(fs.statSync(fullImagePath).isDirectory()){ if (fs.statSync(fullImagePath).isDirectory()) {
return next(); return next();
} }
@ -49,21 +47,19 @@ export class GalleryMWs {
} }
public static search(req:Request, res:Response, next:NextFunction) {
public static search(req:Request, res:Response, next:NextFunction){
//TODO: implement //TODO: implement
return next(new Error(ErrorCodes.GENERAL_ERROR)); return next(new Error(ErrorCodes.GENERAL_ERROR));
} }
public static autocomplete(req:Request, res:Response, next:NextFunction){ public static autocomplete(req:Request, res:Response, next:NextFunction) {
if(!(req.params.text)){ if (!(req.params.text)) {
return next(); return next();
} }
ObjectManagerRepository.getInstance().getSearchManager().autocomplete(req.params.text,(err,items:Array<AutoCompleteItem>) => { ObjectManagerRepository.getInstance().getSearchManager().autocomplete(req.params.text, (err, items:Array<AutoCompleteItem>) => {
if(err || !items){ if (err || !items) {
return next(new Error(ErrorCodes.GENERAL_ERROR,err)); return next(new Error(ErrorCodes.GENERAL_ERROR, err));
} }
req.resultPipe = items; req.resultPipe = items;
return next(); return next();
@ -71,5 +67,4 @@ export class GalleryMWs {
} }
} }

View File

@ -1,4 +1,3 @@
import {NextFunction, Request, Response} from "express"; import {NextFunction, Request, Response} from "express";
import {Error, ErrorCodes} from "../../common/entities/Error"; import {Error, ErrorCodes} from "../../common/entities/Error";
import {Utils} from "../../common/Utils"; import {Utils} from "../../common/Utils";
@ -6,47 +5,47 @@ import {Message} from "../../common/entities/Message";
export class RenderingMWs { export class RenderingMWs {
public static renderResult(req:Request, res:Response, next:NextFunction){ public static renderResult(req:Request, res:Response, next:NextFunction) {
if(!req.resultPipe) if (!req.resultPipe)
return next(); return next();
return RenderingMWs.renderMessage(res,req.resultPipe); return RenderingMWs.renderMessage(res, req.resultPipe);
} }
public static renderSessionUser(req:Request, res:Response, next:NextFunction){ public static renderSessionUser(req:Request, res:Response, next:NextFunction) {
if(!(req.session.user)){ if (!(req.session.user)) {
return next(new Error(ErrorCodes.GENERAL_ERROR)); return next(new Error(ErrorCodes.GENERAL_ERROR));
} }
let user = Utils.clone(req.session.user); let user = Utils.clone(req.session.user);
delete user.password; delete user.password;
RenderingMWs.renderMessage(res,user); RenderingMWs.renderMessage(res, user);
} }
public static renderFile(req:Request, res:Response, next:NextFunction){ public static renderFile(req:Request, res:Response, next:NextFunction) {
if(!req.resultPipe) if (!req.resultPipe)
return next(); return next();
return res.sendFile(req.resultPipe); return res.sendFile(req.resultPipe);
} }
public static renderOK(req:Request, res:Response, next:NextFunction){ public static renderOK(req:Request, res:Response, next:NextFunction) {
let message = new Message<string> (null,"ok"); let message = new Message<string>(null, "ok");
res.json(message); res.json(message);
} }
public static renderError(err:any, req:Request, res:Response, next:NextFunction):any{ public static renderError(err:any, req:Request, res:Response, next:NextFunction):any {
if(err instanceof Error) { if (err instanceof Error) {
let message = new Message<any> (err,null); let message = new Message<any>(err, null);
return res.json(message); return res.json(message);
} }
return next(err); return next(err);
} }
protected static renderMessage<T>(res:Response, content:T){ protected static renderMessage<T>(res:Response, content:T) {
let message = new Message<T> (null,content); let message = new Message<T>(null, content);
res.json(message); res.json(message);
} }

View File

@ -1,56 +1,55 @@
///<reference path="jimp.d.ts"/> ///<reference path="jimp.d.ts"/>
import * as path from 'path'; import * as path from "path";
import * as Jimp from 'jimp'; import * as Jimp from "jimp";
import * as crypto from 'crypto'; import * as crypto from "crypto";
import * as fs from 'fs'; import * as fs from "fs";
import {NextFunction, Request, Response} from "express"; import {NextFunction, Request, Response} from "express";
import {Error, ErrorCodes} from "../../common/entities/Error"; import {Error, ErrorCodes} from "../../common/entities/Error";
import {Config} from "../config/Config"; import {Config} from "../config/Config";
export class ThumbnailGeneratorMWs { export class ThumbnailGeneratorMWs {
private static getThumbnailFolder(){ private static getThumbnailFolder() {
return path.join(__dirname,"/../../",Config.thumbnailFolder); return path.join(__dirname, "/../../", Config.thumbnailFolder);
} }
public static generateThumbnail(req:Request, res:Response, next:NextFunction){ public static generateThumbnail(req:Request, res:Response, next:NextFunction) {
if(!req.resultPipe) if (!req.resultPipe)
return next(); return next();
let imagePath = req.resultPipe; let imagePath = req.resultPipe;
let size:number = parseInt(req.params.size) || Config.thumbnailSizes[0]; let size:number = parseInt(req.params.size) || Config.thumbnailSizes[0];
let thumbnailFolder = ThumbnailGeneratorMWs.getThumbnailFolder(); let thumbnailFolder = ThumbnailGeneratorMWs.getThumbnailFolder();
if(Config.thumbnailSizes.indexOf(size) === -1){ if (Config.thumbnailSizes.indexOf(size) === -1) {
size = Config.thumbnailSizes[0]; size = Config.thumbnailSizes[0];
} }
let thPath = path.join(thumbnailFolder,ThumbnailGeneratorMWs.generateThumbnailName(imagePath,size)); let thPath = path.join(thumbnailFolder, ThumbnailGeneratorMWs.generateThumbnailName(imagePath, size));
req.resultPipe = thPath; req.resultPipe = thPath;
if(fs.existsSync(thPath) === true){ if (fs.existsSync(thPath) === true) {
return next(); return next();
} }
if (!fs.existsSync(thumbnailFolder)){ if (!fs.existsSync(thumbnailFolder)) {
fs.mkdirSync(thumbnailFolder); fs.mkdirSync(thumbnailFolder);
} }
Jimp.read(imagePath).then( (image) => { Jimp.read(imagePath).then((image) => {
if (image.bitmap.with < image.bitmap.height) { if (image.bitmap.with < image.bitmap.height) {
image.resize(size, Jimp.AUTO); // resize image.resize(size, Jimp.AUTO); // resize
}else{ } else {
image.resize(Jimp.AUTO, size); // resize image.resize(Jimp.AUTO, size); // resize
} }
image.quality(60); // set JPEG quality image.quality(60); // set JPEG quality
image.write(thPath, () =>{ // save image.write(thPath, () => { // save
return next(); return next();
}); });
}).catch(function (err) { }).catch(function (err) {
@ -58,7 +57,7 @@ export class ThumbnailGeneratorMWs {
}); });
} }
private static generateThumbnailName(imagePath:string,size:number):string{ private static generateThumbnailName(imagePath:string, size:number):string {
return crypto.createHash('md5').update(imagePath).digest('hex')+"_"+size+".jpg"; return crypto.createHash('md5').update(imagePath).digest('hex') + "_" + size + ".jpg";
} }
} }

View File

@ -1,5 +1,3 @@
import {UserManager} from "../model/memory/UserManager";
import {NextFunction, Request, Response} from "express"; import {NextFunction, Request, Response} from "express";
import {Error, ErrorCodes} from "../../common/entities/Error"; import {Error, ErrorCodes} from "../../common/entities/Error";
import {ObjectManagerRepository} from "../model/ObjectManagerRepository"; import {ObjectManagerRepository} from "../model/ObjectManagerRepository";
@ -7,7 +5,7 @@ import {User} from "../../common/entities/User";
export class UserMWs { export class UserMWs {
public static changePassword(req:Request, res:Response, next:NextFunction){ public static changePassword(req:Request, res:Response, next:NextFunction) {
if ((typeof req.body === 'undefined') || (typeof req.body.userModReq === 'undefined') if ((typeof req.body === 'undefined') || (typeof req.body.userModReq === 'undefined')
|| (typeof req.body.userModReq.id === 'undefined') || (typeof req.body.userModReq.id === 'undefined')
|| (typeof req.body.userModReq.oldPassword === 'undefined') || (typeof req.body.userModReq.oldPassword === 'undefined')
@ -15,7 +13,7 @@ export class UserMWs {
return next(); return next();
} }
ObjectManagerRepository.getInstance().getUserManager().changePassword(req.body.userModReq, (err, result) =>{ ObjectManagerRepository.getInstance().getUserManager().changePassword(req.body.userModReq, (err, result) => {
if ((err) || (!result)) { if ((err) || (!result)) {
return next(new Error(ErrorCodes.GENERAL_ERROR)); return next(new Error(ErrorCodes.GENERAL_ERROR));
} }
@ -25,12 +23,12 @@ export class UserMWs {
} }
public static createUser(req:Request, res:Response, next:NextFunction){ public static createUser(req:Request, res:Response, next:NextFunction) {
if ((typeof req.body === 'undefined') || (typeof req.body.newUser === 'undefined')) { if ((typeof req.body === 'undefined') || (typeof req.body.newUser === 'undefined')) {
return next(); return next();
} }
ObjectManagerRepository.getInstance().getUserManager().createUser(req.body.newUser, (err, result) =>{ ObjectManagerRepository.getInstance().getUserManager().createUser(req.body.newUser, (err, result) => {
if ((err) || (!result)) { if ((err) || (!result)) {
return next(new Error(ErrorCodes.USER_CREATION_ERROR)); return next(new Error(ErrorCodes.USER_CREATION_ERROR));
} }
@ -40,12 +38,12 @@ export class UserMWs {
} }
public static deleteUser(req:Request, res:Response, next:NextFunction){ public static deleteUser(req:Request, res:Response, next:NextFunction) {
if ((typeof req.params === 'undefined') || (typeof req.params.id === 'undefined')) { if ((typeof req.params === 'undefined') || (typeof req.params.id === 'undefined')) {
return next(); return next();
} }
ObjectManagerRepository.getInstance().getUserManager().deleteUser(req.params.id, (err, result) =>{ ObjectManagerRepository.getInstance().getUserManager().deleteUser(req.params.id, (err, result) => {
if ((err) || (!result)) { if ((err) || (!result)) {
return next(new Error(ErrorCodes.GENERAL_ERROR)); return next(new Error(ErrorCodes.GENERAL_ERROR));
} }
@ -56,13 +54,13 @@ export class UserMWs {
} }
public static changeRole(req:Request, res:Response, next:NextFunction){ public static changeRole(req:Request, res:Response, next:NextFunction) {
if ((typeof req.params === 'undefined') || (typeof req.params.id === 'undefined') if ((typeof req.params === 'undefined') || (typeof req.params.id === 'undefined')
|| (typeof req.body === 'undefined') || (typeof req.body.newRole === 'undefined')) { || (typeof req.body === 'undefined') || (typeof req.body.newRole === 'undefined')) {
return next(); return next();
} }
ObjectManagerRepository.getInstance().getUserManager().changeRole(req.params.id,req.body.newRole, (err) =>{ ObjectManagerRepository.getInstance().getUserManager().changeRole(req.params.id, req.body.newRole, (err) => {
if (err) { if (err) {
return next(new Error(ErrorCodes.GENERAL_ERROR)); return next(new Error(ErrorCodes.GENERAL_ERROR));
} }
@ -72,12 +70,12 @@ export class UserMWs {
} }
public static listUsers(req:Request, res:Response, next:NextFunction){ public static listUsers(req:Request, res:Response, next:NextFunction) {
ObjectManagerRepository.getInstance().getUserManager().find({}, (err, result:Array<User>) =>{ ObjectManagerRepository.getInstance().getUserManager().find({}, (err, result:Array<User>) => {
if ((err) || (!result)) { if ((err) || (!result)) {
return next(new Error(ErrorCodes.GENERAL_ERROR)); return next(new Error(ErrorCodes.GENERAL_ERROR));
} }
for(let i = 0; i < result.length; i++){ for (let i = 0; i < result.length; i++) {
result[i].password = ""; result[i].password = "";
} }
@ -87,6 +85,4 @@ export class UserMWs {
} }
} }

View File

@ -1,5 +1,3 @@
import {UserManager} from "../model/memory/UserManager";
import {NextFunction, Request, Response} from "express"; import {NextFunction, Request, Response} from "express";
import {Error, ErrorCodes} from "../../common/entities/Error"; import {Error, ErrorCodes} from "../../common/entities/Error";
import {UserRoles} from "../../common/entities/User"; import {UserRoles} from "../../common/entities/User";
@ -7,12 +5,11 @@ import {ObjectManagerRepository} from "../model/ObjectManagerRepository";
export class UserRequestConstrainsMWs { export class UserRequestConstrainsMWs {
public static forceSelfRequest(req:Request, res:Response, next:NextFunction) {
public static forceSelfRequest(req:Request, res:Response, next:NextFunction){
if ((typeof req.params === 'undefined') || (typeof req.params.id === 'undefined')) { if ((typeof req.params === 'undefined') || (typeof req.params.id === 'undefined')) {
return next(); return next();
} }
if(req.session.user.id !== req.params.id){ if (req.session.user.id !== req.params.id) {
return next(new Error(ErrorCodes.NOT_AUTHORISED)); return next(new Error(ErrorCodes.NOT_AUTHORISED));
} }
@ -20,32 +17,32 @@ export class UserRequestConstrainsMWs {
} }
public static notSelfRequest(req:Request, res:Response, next:NextFunction){ public static notSelfRequest(req:Request, res:Response, next:NextFunction) {
if ((typeof req.params === 'undefined') || (typeof req.params.id === 'undefined')) { if ((typeof req.params === 'undefined') || (typeof req.params.id === 'undefined')) {
return next(); return next();
} }
if(req.session.user.id === req.params.id){ if (req.session.user.id === req.params.id) {
return next(new Error(ErrorCodes.NOT_AUTHORISED)); return next(new Error(ErrorCodes.NOT_AUTHORISED));
} }
return next(); return next();
} }
public static notSelfRequestOr2Admins(req:Request, res:Response, next:NextFunction){ public static notSelfRequestOr2Admins(req:Request, res:Response, next:NextFunction) {
if ((typeof req.params === 'undefined') || (typeof req.params.id === 'undefined')) { if ((typeof req.params === 'undefined') || (typeof req.params.id === 'undefined')) {
return next(); return next();
} }
if(req.session.user.id !== req.params.id){ if (req.session.user.id !== req.params.id) {
return next(); return next();
} }
//TODO: fix it! //TODO: fix it!
ObjectManagerRepository.getInstance().getUserManager().find({minRole:UserRoles.Admin}, (err, result) =>{ ObjectManagerRepository.getInstance().getUserManager().find({minRole: UserRoles.Admin}, (err, result) => {
if ((err) || (!result)) { if ((err) || (!result)) {
return next(new Error(ErrorCodes.GENERAL_ERROR)); return next(new Error(ErrorCodes.GENERAL_ERROR));
} }
if(result.length <= 1) { if (result.length <= 1) {
return next(new Error(ErrorCodes.GENERAL_ERROR)); return next(new Error(ErrorCodes.GENERAL_ERROR));
} }
@ -55,5 +52,4 @@ export class UserRequestConstrainsMWs {
} }
} }

View File

@ -1,4 +1,5 @@
declare module "jimp"{ declare module "jimp" {
function read(filaname); function read(filaname);
var AUTO:any; var AUTO:any;
} }

View File

@ -1,37 +1,36 @@
import * as fs from 'fs'; import * as fs from "fs";
import * as path from 'path'; import * as path from "path";
import * as mime from 'mime'; import * as mime from "mime";
import * as sizeOf from 'image-size'; import * as sizeOf from "image-size";
import {Directory} from "../../common/entities/Directory"; import {Directory} from "../../common/entities/Directory";
import {Photo} from "../../common/entities/Photo"; import {Photo} from "../../common/entities/Photo";
export class DiskManager{ export class DiskManager {
public static scanDirectory(relativeDirectoryName, cb:(error: any, result:Directory) => void){ public static scanDirectory(relativeDirectoryName, cb:(error:any, result:Directory) => void) {
console.log("DiskManager: scanDirectory"); console.log("DiskManager: scanDirectory");
let directoryName = path.basename(relativeDirectoryName); let directoryName = path.basename(relativeDirectoryName);
let directoryParent = path.join( path.dirname(relativeDirectoryName),"/"); let directoryParent = path.join(path.dirname(relativeDirectoryName), "/");
let absoluteDirectoryName = path.join(__dirname,"/../../demo/images", relativeDirectoryName); let absoluteDirectoryName = path.join(__dirname, "/../../demo/images", relativeDirectoryName);
let directory = new Directory(1,directoryName,directoryParent,new Date(),[],[]); let directory = new Directory(1, directoryName, directoryParent, new Date(), [], []);
fs.readdir(absoluteDirectoryName, function (err, list) { fs.readdir(absoluteDirectoryName, function (err, list) {
if(err){ if (err) {
return cb(err,null); return cb(err, null);
} }
for (let i = 0; i < list.length; i++) { for (let i = 0; i < list.length; i++) {
let file = list[i]; let file = list[i];
let fullFilePath = path.resolve(absoluteDirectoryName, file); let fullFilePath = path.resolve(absoluteDirectoryName, file);
if(fs.statSync(fullFilePath).isDirectory()){ if (fs.statSync(fullFilePath).isDirectory()) {
directory.directories.push(new Directory(2,file,relativeDirectoryName,new Date(),[],[])); directory.directories.push(new Directory(2, file, relativeDirectoryName, new Date(), [], []));
} }
if(DiskManager.isImage(fullFilePath)){ if (DiskManager.isImage(fullFilePath)) {
let dimensions = sizeOf(fullFilePath); let dimensions = sizeOf(fullFilePath);
directory.photos.push(new Photo(1,file,dimensions.width,dimensions.height)); directory.photos.push(new Photo(1, file, dimensions.width, dimensions.height));
} }
} }
@ -40,7 +39,7 @@ export class DiskManager{
}); });
} }
private static isImage(fullPath){ private static isImage(fullPath) {
let imageMimeTypes = [ let imageMimeTypes = [
'image/bmp', 'image/bmp',
'image/gif', 'image/gif',

View File

@ -1,4 +1,4 @@
import {Directory} from "../../common/entities/Directory"; import {Directory} from "../../common/entities/Directory";
export interface IGalleryManager { export interface IGalleryManager {
listDirectory(relativeDirectoryName, cb:(error: any,result:Directory) => void); listDirectory(relativeDirectoryName, cb:(error:any, result:Directory) => void);
} }

View File

@ -1,4 +1,4 @@
import {AutoCompleteItem} from "../../common/entities/AutoCompleteItem"; import {AutoCompleteItem} from "../../common/entities/AutoCompleteItem";
export interface ISearchManager { export interface ISearchManager {
autocomplete(text, cb:(error: any,result:Array<AutoCompleteItem>) => void); autocomplete(text, cb:(error:any, result:Array<AutoCompleteItem>) => void);
} }

View File

@ -1,9 +1,9 @@
import {User, UserRoles} from "../../common/entities/User"; import {User, UserRoles} from "../../common/entities/User";
export interface IUserManager { export interface IUserManager {
findOne(filter,cb:(error: any,result:User) => void); findOne(filter, cb:(error:any, result:User) => void);
find(filter,cb:(error: any,result:Array<User>) => void); find(filter, cb:(error:any, result:Array<User>) => void);
createUser(user,cb:(error: any,result:User) => void); createUser(user, cb:(error:any, result:User) => void);
deleteUser(id:number,cb:(error: any,result:string) => void); deleteUser(id:number, cb:(error:any, result:string) => void);
changeRole(id:number, newRole:UserRoles,cb:(error: any) => void); changeRole(id:number, newRole:UserRoles, cb:(error:any) => void);
changePassword(request:any,cb:(error: any,result:string) => void); changePassword(request:any, cb:(error:any, result:string) => void);
} }

View File

@ -8,27 +8,27 @@ import {ISearchManager} from "./ISearchManager";
import {MongoSearchManager} from "./mongoose/MongoSearchManager"; import {MongoSearchManager} from "./mongoose/MongoSearchManager";
import {SearchManager} from "./memory/SearchManager"; import {SearchManager} from "./memory/SearchManager";
export class ObjectManagerRepository{ export class ObjectManagerRepository {
private _galleryManager:IGalleryManager; private _galleryManager:IGalleryManager;
private _userManager:IUserManager; private _userManager:IUserManager;
private _searchManager:ISearchManager; private _searchManager:ISearchManager;
private static _instance:ObjectManagerRepository = null; private static _instance:ObjectManagerRepository = null;
public static InitMongoManagers(){ public static InitMongoManagers() {
ObjectManagerRepository.getInstance().setGalleryManager(new MongoGalleryManager()); ObjectManagerRepository.getInstance().setGalleryManager(new MongoGalleryManager());
ObjectManagerRepository.getInstance().setUserManager(new MongoUserManager()); ObjectManagerRepository.getInstance().setUserManager(new MongoUserManager());
ObjectManagerRepository.getInstance().setSearchManager(new MongoSearchManager()); ObjectManagerRepository.getInstance().setSearchManager(new MongoSearchManager());
} }
public static MemoryMongoManagers(){ public static MemoryMongoManagers() {
ObjectManagerRepository.getInstance().setGalleryManager(new GalleryManager()); ObjectManagerRepository.getInstance().setGalleryManager(new GalleryManager());
ObjectManagerRepository.getInstance().setUserManager(new UserManager()); ObjectManagerRepository.getInstance().setUserManager(new UserManager());
ObjectManagerRepository.getInstance().setSearchManager(new SearchManager()); ObjectManagerRepository.getInstance().setSearchManager(new SearchManager());
} }
public static getInstance(){ public static getInstance() {
if(this._instance === null){ if (this._instance === null) {
this._instance = new ObjectManagerRepository(); this._instance = new ObjectManagerRepository();
} }
return this._instance; return this._instance;

View File

@ -2,13 +2,12 @@ import {Directory} from "../../../common/entities/Directory";
import {IGalleryManager} from "../IGalleryManager"; import {IGalleryManager} from "../IGalleryManager";
import {DiskManager} from "../DiskManger"; import {DiskManager} from "../DiskManger";
export class GalleryManager implements IGalleryManager{ export class GalleryManager implements IGalleryManager {
public listDirectory(relativeDirectoryName, cb:(error: any,result:Directory) => void){ public listDirectory(relativeDirectoryName, cb:(error:any, result:Directory) => void) {
return DiskManager.scanDirectory(relativeDirectoryName,cb); return DiskManager.scanDirectory(relativeDirectoryName, cb);
} }
} }

View File

@ -1,13 +1,12 @@
import {AutoCompleteItem} from "../../../common/entities/AutoCompleteItem"; import {AutoCompleteItem} from "../../../common/entities/AutoCompleteItem";
import {ISearchManager} from "../ISearchManager"; import {ISearchManager} from "../ISearchManager";
export class SearchManager implements ISearchManager{ export class SearchManager implements ISearchManager {
autocomplete(text, cb:(error: any,result:Array<AutoCompleteItem>) => void){ autocomplete(text, cb:(error:any, result:Array<AutoCompleteItem>) => void) {
throw new Error("not implemented"); throw new Error("not implemented");
} }
} }

View File

@ -1,40 +1,41 @@
import {User, UserRoles} from "../../../common/entities/User"; import {User, UserRoles} from "../../../common/entities/User";
import {IUserManager} from "../IUserManager"; import {IUserManager} from "../IUserManager";
export class UserManager implements IUserManager{ export class UserManager implements IUserManager {
private users = [new User(1,"developer", "developer", UserRoles.Developer), private users = [new User(1, "developer", "developer", UserRoles.Developer),
new User(2,"admin", "admin", UserRoles.Admin), new User(2, "admin", "admin", UserRoles.Admin),
new User(3,"user", "user", UserRoles.User), new User(3, "user", "user", UserRoles.User),
new User(4,"guest", "guest", UserRoles.Guest)]; new User(4, "guest", "guest", UserRoles.Guest)];
public findOne(filter,cb:(error: any,result:User) => void){ public findOne(filter, cb:(error:any, result:User) => void) {
return cb(null, this.users[1]); return cb(null, this.users[1]);
} }
public find(filter,cb:(error: any,result:Array<User>) => void){ public find(filter, cb:(error:any, result:Array<User>) => void) {
return cb(null, this.users); return cb(null, this.users);
} }
public createUser(user,cb:(error: any,result:User) => void){ public createUser(user, cb:(error:any, result:User) => void) {
this.users.push(user); this.users.push(user);
return cb(null, user); return cb(null, user);
} }
public deleteUser(id:number,cb:(error: any) => void){ public deleteUser(id:number, cb:(error:any) => void) {
this.users = this.users.filter(u => u.id != id); this.users = this.users.filter(u => u.id != id);
return cb(null); return cb(null);
} }
public changeRole(id:number, newRole:UserRoles, cb:(error: any,result:string) => void){ public changeRole(id:number, newRole:UserRoles, cb:(error:any, result:string) => void) {
for(let i = 0; i < this.users.length; i++){ for (let i = 0; i < this.users.length; i++) {
if (this.users[i].id === id){ if (this.users[i].id === id) {
this.users[i].role = newRole; this.users[i].role = newRole;
return cb(null,"ok"); return cb(null, "ok");
} }
} }
} }
public changePassword(request:any,cb:(error: any,result:string) => void){
public changePassword(request:any, cb:(error:any, result:string) => void) {
throw new Error("not implemented"); //TODO: implement throw new Error("not implemented"); //TODO: implement
} }

View File

@ -1,5 +1,4 @@
import * as path from 'path'; import * as path from "path";
import {Directory} from "../../../common/entities/Directory"; import {Directory} from "../../../common/entities/Directory";
import {IGalleryManager} from "../IGalleryManager"; import {IGalleryManager} from "../IGalleryManager";
import {DiskManager} from "../DiskManger"; import {DiskManager} from "../DiskManger";
@ -7,30 +6,33 @@ import {Utils} from "../../../common/Utils";
import {DirectoryModel} from "./entities/DirectoryModel"; import {DirectoryModel} from "./entities/DirectoryModel";
import {PhotoModel} from "./entities/PhotoModel"; import {PhotoModel} from "./entities/PhotoModel";
export class MongoGalleryManager implements IGalleryManager{ export class MongoGalleryManager implements IGalleryManager {
constructor(){ constructor() {
} }
public listDirectory(relativeDirectoryName, cb:(error: any,result:Directory) => void){ public listDirectory(relativeDirectoryName, cb:(error:any, result:Directory) => void) {
let directoryName = path.basename(relativeDirectoryName); let directoryName = path.basename(relativeDirectoryName);
let directoryParent = path.join( path.dirname(relativeDirectoryName),"/"); let directoryParent = path.join(path.dirname(relativeDirectoryName), "/");
DirectoryModel.findOne({name:directoryName, path: directoryParent}).populate('photos').populate('directories').exec( (err,res:any) =>{ DirectoryModel.findOne({
if(err || !res){ name: directoryName,
return this.indexDirectory(relativeDirectoryName,cb); path: directoryParent
}).populate('photos').populate('directories').exec((err, res:any) => {
if (err || !res) {
return this.indexDirectory(relativeDirectoryName, cb);
} }
return cb(err, res); return cb(err, res);
}); });
} }
public indexDirectory(relativeDirectoryName, cb:(error: any,result:Directory) => void){ public indexDirectory(relativeDirectoryName, cb:(error:any, result:Directory) => void) {
DiskManager.scanDirectory(relativeDirectoryName,(err,scannedDirectory)=>{ DiskManager.scanDirectory(relativeDirectoryName, (err, scannedDirectory)=> {
let arr = []; let arr = [];
scannedDirectory.directories.forEach((value) => { scannedDirectory.directories.forEach((value) => {
let dir = new DirectoryModel(value); let dir = new DirectoryModel(value);
Utils.setKeys(dir,value); Utils.setKeys(dir, value);
dir.save(); dir.save();
arr.push(dir); arr.push(dir);
}); });
@ -38,19 +40,18 @@ export class MongoGalleryManager implements IGalleryManager{
arr = []; arr = [];
scannedDirectory.photos.forEach((value) => { scannedDirectory.photos.forEach((value) => {
let p = new PhotoModel(value); let p = new PhotoModel(value);
Utils.setKeys(p,value); Utils.setKeys(p, value);
p.save(); p.save();
arr.push(p); arr.push(p);
}); });
scannedDirectory.photos = arr; scannedDirectory.photos = arr;
DirectoryModel.create(scannedDirectory,(err)=>{ DirectoryModel.create(scannedDirectory, (err)=> {
return cb(err,scannedDirectory); return cb(err, scannedDirectory);
}); });
}); });
} }
} }

View File

@ -3,43 +3,45 @@ import {ISearchManager} from "../ISearchManager";
import {DirectoryModel} from "./entities/DirectoryModel"; import {DirectoryModel} from "./entities/DirectoryModel";
import {PhotoModel} from "./entities/PhotoModel"; import {PhotoModel} from "./entities/PhotoModel";
export class MongoSearchManager implements ISearchManager{ export class MongoSearchManager implements ISearchManager {
constructor() {
constructor(){
} }
autocomplete(text, cb:(error:any, result:Array<AutoCompleteItem>) => void) {
autocomplete(text, cb:(error: any,result:Array<AutoCompleteItem>) => void){
console.log("autocomplete: " + text); console.log("autocomplete: " + text);
let items:Array<AutoCompleteItem> = []; let items:Array<AutoCompleteItem> = [];
PhotoModel.find({name: { $regex: text, $options: "i" } }).limit(10).select('name').exec( (err,res:Array<any>) =>{ PhotoModel.find({name: {$regex: text, $options: "i"}}).limit(10).select('name').exec((err, res:Array<any>) => {
if(err || !res){ if (err || !res) {
return cb(err,null); return cb(err, null);
} }
items = items.concat(this.encapsulateAutoComplete(res.map(r => r.name),AutoCompeleteTypes.image)); items = items.concat(this.encapsulateAutoComplete(res.map(r => r.name), AutoCompeleteTypes.image));
DirectoryModel.find({name: { $regex: text, $options: "i" } }).limit(10).select('name').exec( (err,res:Array<any>) =>{ DirectoryModel.find({
if(err || !res){ name: {
return cb(err,null); $regex: text,
$options: "i"
} }
items = items.concat(this.encapsulateAutoComplete(res.map(r => r.name),AutoCompeleteTypes.directory)); }).limit(10).select('name').exec((err, res:Array<any>) => {
return cb(null,items); if (err || !res) {
return cb(err, null);
}
items = items.concat(this.encapsulateAutoComplete(res.map(r => r.name), AutoCompeleteTypes.directory));
return cb(null, items);
}); });
}); });
} }
private encapsulateAutoComplete(values:Array<string>,type: AutoCompeleteTypes){ private encapsulateAutoComplete(values:Array<string>, type:AutoCompeleteTypes) {
let res = []; let res = [];
values.forEach((value)=>{ values.forEach((value)=> {
res.push(new AutoCompleteItem(value,type)); res.push(new AutoCompleteItem(value, type));
}); });
return res; return res;
} }
} }

View File

@ -4,7 +4,6 @@ import {UserModel} from "./entities/UserModel";
export class MongoUserManager implements IUserManager { export class MongoUserManager implements IUserManager {
constructor() { constructor() {
} }

View File

@ -1,10 +1,10 @@
import {DatabaseManager} from "../DatabaseManager"; import {DatabaseManager} from "../DatabaseManager";
import {Schema} from "mongoose"; import {Schema} from "mongoose";
export var DirectoryModel = DatabaseManager.getInstance().getModel('directory',{ export var DirectoryModel = DatabaseManager.getInstance().getModel('directory', {
name:String, name: String,
path:String, path: String,
lastUpdate:Date, lastUpdate: Date,
directories: [{ directories: [{
type: Schema.Types.ObjectId, type: Schema.Types.ObjectId,
ref: 'directory' ref: 'directory'

View File

@ -3,7 +3,7 @@
import {AuthenticationMWs} from "../middlewares/AuthenticationMWs"; import {AuthenticationMWs} from "../middlewares/AuthenticationMWs";
import {UserRoles} from "../../common/entities/User"; import {UserRoles} from "../../common/entities/User";
export class AdminRouter{ export class AdminRouter {
constructor(private app) { constructor(private app) {
this.addResetDB(); this.addResetDB();
@ -27,7 +27,4 @@ export class AdminRouter{
}; };
} }

View File

@ -3,7 +3,7 @@
import {RenderingMWs} from "../middlewares/RenderingMWs"; import {RenderingMWs} from "../middlewares/RenderingMWs";
import {Error, ErrorCodes} from "../../common/entities/Error"; import {Error, ErrorCodes} from "../../common/entities/Error";
export class ErrorRouter{ export class ErrorRouter {
constructor(private app) { constructor(private app) {
this.addApiErrorHandler(); this.addApiErrorHandler();
@ -17,13 +17,13 @@ export class ErrorRouter{
}; };
private addGenericHandler() { private addGenericHandler() {
this.app.use((err, req, res, next) => { this.app.use((err, req, res, next) => {
//Flush out the stack to the console //Flush out the stack to the console
console.error(err.stack); console.error(err.stack);
next(new Error(ErrorCodes.SERVER_ERROR,"Unknown server side error")); next(new Error(ErrorCodes.SERVER_ERROR, "Unknown server side error"));
}, },
RenderingMWs.renderError RenderingMWs.renderError
); );
} }

View File

@ -5,8 +5,8 @@ import {GalleryMWs} from "../middlewares/GalleryMWs";
import {RenderingMWs} from "../middlewares/RenderingMWs"; import {RenderingMWs} from "../middlewares/RenderingMWs";
import {ThumbnailGeneratorMWs} from "../middlewares/ThumbnailGeneratorMWs"; import {ThumbnailGeneratorMWs} from "../middlewares/ThumbnailGeneratorMWs";
export class GalleryRouter{ export class GalleryRouter {
constructor(private app){ constructor(private app) {
this.addGetImageThumbnail(); this.addGetImageThumbnail();
this.addGetImage(); this.addGetImage();
@ -17,7 +17,7 @@ export class GalleryRouter{
} }
private addDirectoryList() { private addDirectoryList() {
this.app.get(["/api/gallery/content/:directory(*)","/api/gallery/","/api/gallery//"], this.app.get(["/api/gallery/content/:directory(*)", "/api/gallery/", "/api/gallery//"],
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
GalleryMWs.listDirectory, GalleryMWs.listDirectory,
RenderingMWs.renderResult RenderingMWs.renderResult
@ -59,5 +59,4 @@ export class GalleryRouter{
}; };
} }

View File

@ -1,21 +1,17 @@
///<reference path="../../typings/main.d.ts"/> ///<reference path="../../typings/main.d.ts"/>
import * as _express from "express";
import * as _express from 'express'; import {NextFunction, Request, Response} from "express";
import * as _path from 'path'; import * as _path from "path";
import {Utils} from "../../common/Utils"; import {Utils} from "../../common/Utils";
import {NextFunction, Request, Response} from "express"; export class PublicRouter {
constructor(private app) {
export class PublicRouter{
constructor(private app){
this.app.use((req:Request, res:Response, next:NextFunction) => { this.app.use((req:Request, res:Response, next:NextFunction) => {
res.tpl = {}; res.tpl = {};
res.tpl.user = null; res.tpl.user = null;
if(req.session.user) { if (req.session.user) {
let user = Utils.clone(req.session.user); let user = Utils.clone(req.session.user);
delete user.password; delete user.password;
res.tpl.user = user; res.tpl.user = user;
@ -25,13 +21,13 @@ export class PublicRouter{
}); });
this.app.use(_express.static(_path.resolve(__dirname, './../../frontend'))); this.app.use(_express.static(_path.resolve(__dirname, './../../frontend')));
this.app.use('/node_modules',_express.static(_path.resolve(__dirname, './../../node_modules'))); this.app.use('/node_modules', _express.static(_path.resolve(__dirname, './../../node_modules')));
var renderIndex = (req: Request, res: Response) => { var renderIndex = (req:Request, res:Response) => {
res.render(_path.resolve(__dirname, './../../frontend/index.ejs'),res.tpl); res.render(_path.resolve(__dirname, './../../frontend/index.ejs'), res.tpl);
}; };
this.app.get(['/','/login',"/gallery*","/admin"], renderIndex); this.app.get(['/', '/login', "/gallery*", "/admin"], renderIndex);
} }

View File

@ -3,7 +3,7 @@
import {AuthenticationMWs} from "../middlewares/AuthenticationMWs"; import {AuthenticationMWs} from "../middlewares/AuthenticationMWs";
import {UserRoles} from "../../common/entities/User"; import {UserRoles} from "../../common/entities/User";
export class SharingRouter{ export class SharingRouter {
constructor(private app) { constructor(private app) {
this.addGetSharing(); this.addGetSharing();
@ -27,7 +27,4 @@ export class SharingRouter{
}; };
} }

View File

@ -6,8 +6,8 @@ import {AuthenticationMWs} from "../middlewares/AuthenticationMWs";
import {UserRequestConstrainsMWs} from "../middlewares/UserRequestConstrainsMWs"; import {UserRequestConstrainsMWs} from "../middlewares/UserRequestConstrainsMWs";
import {RenderingMWs} from "../middlewares/RenderingMWs"; import {RenderingMWs} from "../middlewares/RenderingMWs";
export class UserRouter{ export class UserRouter {
constructor(private app){ constructor(private app) {
this.addLogin(); this.addLogin();
this.addGetSessionUser(); this.addGetSessionUser();
this.addChangePassword(); this.addChangePassword();

View File

@ -1,13 +1,13 @@
export var MessageTypes = { export var MessageTypes = {
Client:{ Client: {
Login:{ Login: {
Authenticate:"Authenticate" Authenticate: "Authenticate"
} }
}, },
Server:{ Server: {
Login:{ Login: {
Authenticated:"Authenticated" Authenticated: "Authenticated"
} }
} }

View File

@ -5,13 +5,13 @@ export class Utils {
} }
static concatUrls(...args:Array<string>){ static concatUrls(...args:Array<string>) {
let url = ""; let url = "";
for(let i = 0 ; i < args.length; i++){ for (let i = 0; i < args.length; i++) {
if(args[i] === "" || typeof args[i] === "undefined") continue; if (args[i] === "" || typeof args[i] === "undefined") continue;
let part = args[i].replace("\\","/"); let part = args[i].replace("\\", "/");
if(part === "/" || part === "./") continue; if (part === "/" || part === "./") continue;
url += part + "/"; url += part + "/";
} }
@ -19,33 +19,33 @@ export class Utils {
return url.substring(0, url.length - 1); return url.substring(0, url.length - 1);
} }
public static updateKeys(targetObject,sourceObject){ public static updateKeys(targetObject, sourceObject) {
Object.keys(sourceObject).forEach((key)=> { Object.keys(sourceObject).forEach((key)=> {
if(typeof targetObject[key] === "undefined"){ if (typeof targetObject[key] === "undefined") {
return; return;
} }
if(typeof targetObject[key] === "object"){ if (typeof targetObject[key] === "object") {
Utils.updateKeys(targetObject[key],sourceObject[key] ); Utils.updateKeys(targetObject[key], sourceObject[key]);
}else { } else {
targetObject[key] = sourceObject[key]; targetObject[key] = sourceObject[key];
} }
}); });
} }
public static setKeys(targetObject,sourceObject){ public static setKeys(targetObject, sourceObject) {
Object.keys(sourceObject).forEach((key)=> { Object.keys(sourceObject).forEach((key)=> {
if(typeof targetObject[key] === "object"){ if (typeof targetObject[key] === "object") {
Utils.updateKeys(targetObject[key],sourceObject[key] ); Utils.updateKeys(targetObject[key], sourceObject[key]);
}else { } else {
targetObject[key] = sourceObject[key]; targetObject[key] = sourceObject[key];
} }
}); });
} }
public static enumToArray(EnumType):Array<{key:number;value:string;}>{ public static enumToArray(EnumType):Array<{key:number;value:string;}> {
let arr:Array<{key:number;value:string;}> = []; let arr:Array<{key:number;value:string;}> = [];
for(let enumMember in EnumType){ for (let enumMember in EnumType) {
if(!EnumType.hasOwnProperty(enumMember)){ if (!EnumType.hasOwnProperty(enumMember)) {
continue; continue;
} }
let key = parseInt(enumMember, 10); let key = parseInt(enumMember, 10);

View File

@ -4,7 +4,8 @@ export enum AutoCompeleteTypes {
imageTag imageTag
} }
export class AutoCompleteItem{ export class AutoCompleteItem {
constructor(public text:string,public type:AutoCompeleteTypes){} constructor(public text:string, public type:AutoCompeleteTypes) {
}
} }

View File

@ -1,10 +1,11 @@
import {Photo} from "./Photo"; import {Photo} from "./Photo";
export class Directory{ export class Directory {
constructor(public id?:number, constructor(public id?:number,
public name?:string, public name?:string,
public path?:string, public path?:string,
public lastUpdate?:Date, public lastUpdate?:Date,
public directories:Array<Directory> =[], public directories:Array<Directory> = [],
public photos:Array<Photo> = []){} public photos:Array<Photo> = []) {
}
} }

View File

@ -1,4 +1,3 @@
export enum ErrorCodes{ export enum ErrorCodes{
NOT_AUTHENTICATED, NOT_AUTHENTICATED,
ALREADY_AUTHENTICATED, ALREADY_AUTHENTICATED,
@ -14,6 +13,7 @@ export enum ErrorCodes{
} }
export class Error{ export class Error {
constructor(public code:ErrorCodes, public message?:String) {} constructor(public code:ErrorCodes, public message?:String) {
}
} }

View File

@ -1,5 +1,5 @@
export class LoginCredential{ export class LoginCredential {
constructor(public username:string = "", public password:string = ""){ constructor(public username:string = "", public password:string = "") {
} }
} }

View File

@ -1,9 +1,10 @@
import {Error} from "./Error"; import {Error} from "./Error";
export class Message<T>{ export class Message<T> {
public error:Error = null; public error:Error = null;
public result:T = null; public result:T = null;
constructor(error:Error, result:T){
constructor(error:Error, result:T) {
this.error = error; this.error = error;
this.result = result; this.result = result;
} }

View File

@ -4,10 +4,11 @@ export class Photo {
constructor(public id:number, public name:string, public width:number, public height:number) { constructor(public id:number, public name:string, public width:number, public height:number) {
} }
public static getThumbnailPath(directory:Directory,photo:Photo){ public static getThumbnailPath(directory:Directory, photo:Photo) {
return Utils.concatUrls("/api/gallery/content/",directory.path,directory.name,photo.name,"thumbnail"); return Utils.concatUrls("/api/gallery/content/", directory.path, directory.name, photo.name, "thumbnail");
} }
public static getPhotoPath(directory:Directory,photo:Photo){
return Utils.concatUrls("/api/gallery/content/",directory.path,directory.name,photo.name); public static getPhotoPath(directory:Directory, photo:Photo) {
return Utils.concatUrls("/api/gallery/content/", directory.path, directory.name, photo.name);
} }
} }

View File

@ -1,4 +1,3 @@
export enum UserRoles{ export enum UserRoles{
Guest = 1, Guest = 1,
User = 2, User = 2,
@ -8,5 +7,6 @@ export enum UserRoles{
} }
export class User { export class User {
constructor(public id?:number,public name?:string, public password?:string, public role:UserRoles = UserRoles.User){} constructor(public id?:number, public name?:string, public password?:string, public role:UserRoles = UserRoles.User) {
}
} }

View File

@ -1,3 +1,4 @@
export class UserModificationRequest{ export class UserModificationRequest {
constructor(public id:number){} constructor(public id:number) {
}
} }

View File

@ -9,7 +9,7 @@ import {FORM_DIRECTIVES} from "@angular/common";
import {Utils} from "../../../common/Utils"; import {Utils} from "../../../common/Utils";
import {AdminService} from "./admin.service"; import {AdminService} from "./admin.service";
import {Message} from "../../../common/entities/Message"; import {Message} from "../../../common/entities/Message";
import {StringifyRole} from "./StringifyRolePipe"; import {StringifyRole} from "./../pipes/StringifyRolePipe";
@Component({ @Component({
selector: 'admin', selector: 'admin',

View File

@ -1,8 +1,7 @@
///<reference path="../../browser.d.ts"/> ///<reference path="../../browser.d.ts"/>
import {Injectable} from '@angular/core'; import {Injectable} from "@angular/core";
import {NetworkService} from "../model/network/network.service.ts"; import {NetworkService} from "../model/network/network.service.ts";
import {Http} from "@angular/http";
import {Message} from "../../../common/entities/Message"; import {Message} from "../../../common/entities/Message";
import {User} from "../../../common/entities/User"; import {User} from "../../../common/entities/User";
@ -10,24 +9,24 @@ import {User} from "../../../common/entities/User";
export class AdminService { export class AdminService {
constructor(private _networkService:NetworkService){ constructor(private _networkService:NetworkService) {
} }
public createUser(user:User): Promise<Message<string>>{ public createUser(user:User):Promise<Message<string>> {
return this._networkService.putJson("/user",{newUser:user}); return this._networkService.putJson("/user", {newUser: user});
} }
public getUsers():Promise<Message<Array<User>>>{ public getUsers():Promise<Message<Array<User>>> {
return this._networkService.getJson("/user/list"); return this._networkService.getJson("/user/list");
} }
public deleteUser(user:User) { public deleteUser(user:User) {
return this._networkService.deleteJson("/user/"+user.id); return this._networkService.deleteJson("/user/" + user.id);
} }
public updateRole(user:User) { public updateRole(user:User) {
return this._networkService.postJson("/user/"+user.id+"/role",{newRole:user.role}); return this._networkService.postJson("/user/" + user.id + "/role", {newRole: user.role});
} }
} }

View File

@ -1,6 +1,6 @@
///<reference path="../browser.d.ts"/> ///<reference path="../browser.d.ts"/>
import { Component,OnInit } from '@angular/core'; import {Component, OnInit} from "@angular/core";
import {LoginComponent} from "./login/login.component"; import {LoginComponent} from "./login/login.component";
import {AuthenticationService} from "./model/network/authentication.service.ts"; import {AuthenticationService} from "./model/network/authentication.service.ts";
import {GalleryComponent} from "./gallery/gallery.component"; import {GalleryComponent} from "./gallery/gallery.component";
@ -43,24 +43,24 @@ import {NetworkService} from "./model/network/network.service";
}, },
{ {
path: '/gallery', path: '/gallery',
redirectTo: ["Gallery",{directory:""}] redirectTo: ["Gallery", {directory: ""}]
}, },
{ {
path: '/gallery/:directory', path: '/gallery/:directory',
name: 'Gallery', name: 'Gallery',
component: GalleryComponent component: GalleryComponent
}, },
]) ])
export class AppComponent implements OnInit{ export class AppComponent implements OnInit {
constructor(private _router: Router, private _authenticationService: AuthenticationService){ constructor(private _router:Router, private _authenticationService:AuthenticationService) {
} }
ngOnInit() { ngOnInit() {
this._authenticationService.OnAuthenticated.on((user:User) => { this._authenticationService.OnAuthenticated.on((user:User) => {
if (this._router.isRouteActive(this._router.generate(['Login']))) { if (this._router.isRouteActive(this._router.generate(['Login']))) {
console.log("routing"); console.log("routing");
this._router.navigate(["Gallery",{directory:""}]); this._router.navigate(["Gallery", {directory: ""}]);
} }
}); });

View File

@ -1,12 +1,12 @@
///<reference path="../../browser.d.ts"/> ///<reference path="../../browser.d.ts"/>
import {Component, ViewEncapsulation} from '@angular/core'; import {Component, ViewEncapsulation} from "@angular/core";
import {RouterLink} from "@angular/router-deprecated"; import {RouterLink} from "@angular/router-deprecated";
@Component({ @Component({
selector: 'app-frame', selector: 'app-frame',
templateUrl: 'app/frame/frame.component.html', templateUrl: 'app/frame/frame.component.html',
directives:[RouterLink], directives: [RouterLink],
encapsulation: ViewEncapsulation.Emulated encapsulation: ViewEncapsulation.Emulated
}) })
export class FrameComponent { export class FrameComponent {

View File

@ -1,6 +1,6 @@
///<reference path="../../../browser.d.ts"/> ///<reference path="../../../browser.d.ts"/>
import {Component, Input} from '@angular/core'; import {Component, Input} from "@angular/core";
import {Directory} from "../../../../common/entities/Directory"; import {Directory} from "../../../../common/entities/Directory";
import {RouterLink} from "@angular/router-deprecated"; import {RouterLink} from "@angular/router-deprecated";
import {Utils} from "../../../../common/Utils"; import {Utils} from "../../../../common/Utils";
@ -8,19 +8,18 @@ import {Utils} from "../../../../common/Utils";
@Component({ @Component({
selector: 'gallery-directory', selector: 'gallery-directory',
templateUrl: 'app/gallery/directory/directory.gallery.component.html', templateUrl: 'app/gallery/directory/directory.gallery.component.html',
directives:[RouterLink], directives: [RouterLink],
}) })
export class GalleryDirectoryComponent{ export class GalleryDirectoryComponent {
@Input() directory: Directory; @Input() directory:Directory;
constructor() { constructor() {
} }
getDirectoryPath(){ getDirectoryPath() {
return Utils.concatUrls(this.directory.path,this.directory.name); return Utils.concatUrls(this.directory.path, this.directory.name);
} }
} }

View File

@ -1,8 +1,8 @@
///<reference path="../../browser.d.ts"/> ///<reference path="../../browser.d.ts"/>
import {Component, OnInit} from '@angular/core'; import {Component, OnInit} from "@angular/core";
import {AuthenticationService} from "../model/network/authentication.service.ts"; import {AuthenticationService} from "../model/network/authentication.service.ts";
import {Router, RouteParams} from "@angular/router-deprecated"; import {Router, RouteParams} from "@angular/router-deprecated";
import {GalleryService} from "./gallery.service"; import {GalleryService} from "./gallery.service";
import {Directory} from "../../../common/entities/Directory"; import {Directory} from "../../../common/entities/Directory";
import {Message} from "../../../common/entities/Message"; import {Message} from "../../../common/entities/Message";
@ -16,24 +16,24 @@ import {GallerySearchComponent} from "./search/search.gallery.component";
selector: 'gallery', selector: 'gallery',
templateUrl: 'app/gallery/gallery.component.html', templateUrl: 'app/gallery/gallery.component.html',
styleUrls: ['app/gallery/gallery.component.css'], styleUrls: ['app/gallery/gallery.component.css'],
directives:[GalleryGridComponent, directives: [GalleryGridComponent,
GalleryDirectoryComponent, GalleryDirectoryComponent,
GalleryLightboxComponent, GalleryLightboxComponent,
FrameComponent, FrameComponent,
GallerySearchComponent] GallerySearchComponent]
}) })
export class GalleryComponent implements OnInit{ export class GalleryComponent implements OnInit {
currentDirectory:Directory = new Directory(); currentDirectory:Directory = new Directory();
constructor(private _galleryService:GalleryService, constructor(private _galleryService:GalleryService,
private _params: RouteParams, private _params:RouteParams,
private _authService: AuthenticationService, private _authService:AuthenticationService,
private _router: Router) { private _router:Router) {
} }
ngOnInit(){ ngOnInit() {
if (!this._authService.isAuthenticated()) { if (!this._authService.isAuthenticated()) {
this._router.navigate(['Login']); this._router.navigate(['Login']);
return; return;
@ -43,8 +43,8 @@ export class GalleryComponent implements OnInit{
console.log(this._params); console.log(this._params);
console.log(directoryName); console.log(directoryName);
directoryName = directoryName ? directoryName : ""; directoryName = directoryName ? directoryName : "";
this._galleryService.getDirectory(directoryName).then(( message:Message<Directory>) => { this._galleryService.getDirectory(directoryName).then((message:Message<Directory>) => {
if(message.error){ if (message.error) {
//TODO: implement //TODO: implement
return; return;
} }
@ -54,7 +54,5 @@ export class GalleryComponent implements OnInit{
} }
} }

View File

@ -1,19 +1,18 @@
///<reference path="../../browser.d.ts"/> ///<reference path="../../browser.d.ts"/>
import {Injectable} from '@angular/core'; import {Injectable} from "@angular/core";
import {NetworkService} from "../model/network/network.service.ts"; import {NetworkService} from "../model/network/network.service.ts";
import {Http} from "@angular/http";
import {Message} from "../../../common/entities/Message"; import {Message} from "../../../common/entities/Message";
import {Directory} from "../../../common/entities/Directory"; import {Directory} from "../../../common/entities/Directory";
@Injectable() @Injectable()
export class GalleryService{ export class GalleryService {
constructor(private _networkService:NetworkService){ constructor(private _networkService:NetworkService) {
} }
public getDirectory(directoryName:string): Promise<Message<Directory>>{ public getDirectory(directoryName:string):Promise<Message<Directory>> {
return this._networkService.getJson("/gallery/content/"+directoryName); return this._networkService.getJson("/gallery/content/" + directoryName);
} }
} }

View File

@ -1,25 +1,24 @@
import {Photo} from "../../../../common/entities/Photo"; import {Photo} from "../../../../common/entities/Photo";
export class GridRowBuilder{ export class GridRowBuilder {
private photoRow:Array<Photo> = []; private photoRow:Array<Photo> = [];
private photoIndex:number = 0; //index of the last pushed photo to the photoRow private photoIndex:number = 0; //index of the last pushed photo to the photoRow
constructor(private photos:Array<Photo>, private startIndex:number, private photoMargin:number, private containerWidth:number){ constructor(private photos:Array<Photo>, private startIndex:number, private photoMargin:number, private containerWidth:number) {
this.photoIndex = startIndex; this.photoIndex = startIndex;
} }
public addPhotos(number:number){ public addPhotos(number:number) {
for(let i = 0; i < number; i++){ for (let i = 0; i < number; i++) {
this.addPhoto(); this.addPhoto();
} }
} }
public addPhoto():boolean{ public addPhoto():boolean {
if(this.photoIndex + 1 > this.photos.length){ if (this.photoIndex + 1 > this.photos.length) {
return false; return false;
} }
this.photoRow.push(this.photos[this.photoIndex]); this.photoRow.push(this.photos[this.photoIndex]);
@ -27,8 +26,8 @@ export class GridRowBuilder{
return true; return true;
} }
public removePhoto():boolean{ public removePhoto():boolean {
if(this.photoIndex - 1 < this.startIndex){ if (this.photoIndex - 1 < this.startIndex) {
return false; return false;
} }
this.photoIndex--; this.photoIndex--;
@ -36,11 +35,11 @@ export class GridRowBuilder{
return true; return true;
} }
public getPhotoRow():Array<Photo>{ public getPhotoRow():Array<Photo> {
return this.photoRow; return this.photoRow;
} }
public adjustRowHeightBetween(minHeight:number,maxHeight:number){ public adjustRowHeightBetween(minHeight:number, maxHeight:number) {
while (this.calcRowHeight() > maxHeight && this.addPhoto() === true) { //row too high -> add more images while (this.calcRowHeight() > maxHeight && this.addPhoto() === true) { //row too high -> add more images
} }
@ -48,18 +47,18 @@ export class GridRowBuilder{
} }
//keep at least one photo int thr row //keep at least one photo int thr row
if(this.photoRow.length <= 0){ if (this.photoRow.length <= 0) {
this.addPhoto(); this.addPhoto();
} }
} }
public calcRowHeight():number { public calcRowHeight():number {
let width = 0; let width = 0;
for(let i = 0; i < this.photoRow.length; i++){ for (let i = 0; i < this.photoRow.length; i++) {
width += ((this.photoRow[i].width) / (this.photoRow[i].height)); //summing up aspect ratios width += ((this.photoRow[i].width) / (this.photoRow[i].height)); //summing up aspect ratios
} }
let height = (this.containerWidth - this.photoRow.length * (this.photoMargin * 2) - 1) / width; //cant be equal -> width-1 let height = (this.containerWidth - this.photoRow.length * (this.photoMargin * 2) - 1) / width; //cant be equal -> width-1
return height +(this.photoMargin * 2); return height + (this.photoMargin * 2);
}; };
} }

View File

@ -45,8 +45,7 @@ export class GalleryLightboxComponent {
from.top -= this.getBodyScrollTop(); from.top -= this.getBodyScrollTop();
let fromImage = {width: from.width + "px", height: from.height + "px", top: "0px", left: "0px"};
let fromImage = {width: from.width + "px", height: from.height + "px", top: "0px", left:"0px"};
let toImage = this.calcLightBoxPhotoDimension(this.activePhoto.photo).toStyle(); let toImage = this.calcLightBoxPhotoDimension(this.activePhoto.photo).toStyle();
this.forceAnimateFrom(fromImage, this.forceAnimateFrom(fromImage,
@ -91,7 +90,7 @@ export class GalleryLightboxComponent {
let fromImage = this.calcLightBoxPhotoDimension(this.activePhoto.photo).toStyle(); let fromImage = this.calcLightBoxPhotoDimension(this.activePhoto.photo).toStyle();
let toImage = {width: to.width + "px", height: to.height + "px", top: "0px", left:"0px"}; let toImage = {width: to.width + "px", height: to.height + "px", top: "0px", left: "0px"};
this.forceAnimateTo(fromImage, this.forceAnimateTo(fromImage,
toImage, toImage,
@ -103,7 +102,7 @@ export class GalleryLightboxComponent {
} }
private findPhotoComponenet(photo){ private findPhotoComponenet(photo) {
let galleryPhotoComponents = this.gridPhotoQL.toArray(); let galleryPhotoComponents = this.gridPhotoQL.toArray();
let selectedPhoto:GalleryPhotoComponent = null; let selectedPhoto:GalleryPhotoComponent = null;
for (let i = 0; i < galleryPhotoComponents.length; i++) { for (let i = 0; i < galleryPhotoComponents.length; i++) {
@ -174,20 +173,20 @@ export class GalleryLightboxComponent {
} }
private calcLightBoxPhotoDimension(photo:Photo):Dimension{ private calcLightBoxPhotoDimension(photo:Photo):Dimension {
let width = 0; let width = 0;
let height = 0; let height = 0;
if (photo.height > photo.width) { if (photo.height > photo.width) {
width= Math.round(photo.width * (this.getScreenHeight() / photo.height)); width = Math.round(photo.width * (this.getScreenHeight() / photo.height));
height= this.getScreenHeight(); height = this.getScreenHeight();
} else { } else {
width= this.getScreenWidth(); width = this.getScreenWidth();
height= Math.round(photo.height * (this.getScreenWidth() / photo.width)); height = Math.round(photo.height * (this.getScreenWidth() / photo.width));
} }
let top = (this.getScreenHeight() / 2 - height / 2); let top = (this.getScreenHeight() / 2 - height / 2);
let left = (this.getScreenWidth() / 2 - width / 2); let left = (this.getScreenWidth() / 2 - width / 2);
return new Dimension(top,left,width,height); return new Dimension(top, left, width, height);
} }
} }

View File

@ -1,6 +1,6 @@
///<reference path="../../../browser.d.ts"/> ///<reference path="../../../browser.d.ts"/>
import {Component, Input, ElementRef, ViewChild} from '@angular/core'; import {Component, Input, ElementRef, ViewChild} from "@angular/core";
import {Photo} from "../../../../common/entities/Photo"; import {Photo} from "../../../../common/entities/Photo";
import {Directory} from "../../../../common/entities/Directory"; import {Directory} from "../../../../common/entities/Directory";
import {IRenderable, Dimension} from "../../model/IRenderable"; import {IRenderable, Dimension} from "../../model/IRenderable";
@ -10,24 +10,24 @@ import {IRenderable, Dimension} from "../../model/IRenderable";
templateUrl: 'app/gallery/photo/photo.gallery.component.html', templateUrl: 'app/gallery/photo/photo.gallery.component.html',
styleUrls: ['app/gallery/photo/photo.gallery.component.css'], styleUrls: ['app/gallery/photo/photo.gallery.component.css'],
}) })
export class GalleryPhotoComponent implements IRenderable{ export class GalleryPhotoComponent implements IRenderable {
@Input() photo: Photo; @Input() photo:Photo;
@Input() directory: Directory; @Input() directory:Directory;
@ViewChild("image") imageRef:ElementRef; @ViewChild("image") imageRef:ElementRef;
constructor() { constructor() {
} }
getPhotoPath(){ getPhotoPath() {
return Photo.getThumbnailPath(this.directory,this.photo); return Photo.getThumbnailPath(this.directory, this.photo);
} }
public getDimension():Dimension{ public getDimension():Dimension {
return new Dimension(this.imageRef.nativeElement.offsetTop, return new Dimension(this.imageRef.nativeElement.offsetTop,
this.imageRef.nativeElement.offsetLeft, this.imageRef.nativeElement.offsetLeft,
this.imageRef.nativeElement.width, this.imageRef.nativeElement.width,
this.imageRef.nativeElement.height); this.imageRef.nativeElement.height);
} }
} }

View File

@ -1,7 +1,6 @@
///<reference path="../../../browser.d.ts"/> ///<reference path="../../../browser.d.ts"/>
import {Injectable} from "@angular/core"; import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {NetworkService} from "../../model/network/network.service"; import {NetworkService} from "../../model/network/network.service";
import {AutoCompleteItem} from "../../../../common/entities/AutoCompleteItem"; import {AutoCompleteItem} from "../../../../common/entities/AutoCompleteItem";
import {Message} from "../../../../common/entities/Message"; import {Message} from "../../../../common/entities/Message";
@ -10,11 +9,11 @@ import {Message} from "../../../../common/entities/Message";
export class AutoCompleteService { export class AutoCompleteService {
constructor(private _networkService:NetworkService){ constructor(private _networkService:NetworkService) {
} }
public autoComplete(text:string): Promise<Message<Array<AutoCompleteItem> >> { public autoComplete(text:string):Promise<Message<Array<AutoCompleteItem> >> {
return this._networkService.getJson("/gallery/autocomplete/"+text); return this._networkService.getJson("/gallery/autocomplete/" + text);
} }

View File

@ -14,56 +14,55 @@ import {Message} from "../../../../common/entities/Message";
export class GallerySearchComponent { export class GallerySearchComponent {
autoCompleteItems:Array<AutoCompleteRenderItem> = []; autoCompleteItems:Array<AutoCompleteRenderItem> = [];
constructor(private _autoCompleteService:AutoCompleteService) { constructor(private _autoCompleteService:AutoCompleteService) {
} }
getSuggestions(event:KeyboardEvent){ getSuggestions(event:KeyboardEvent) {
let searchText = (<HTMLInputElement>event.target).value; let searchText = (<HTMLInputElement>event.target).value;
if(searchText.trim().length > 0) { if (searchText.trim().length > 0) {
this._autoCompleteService.autoComplete(searchText).then((message:Message<Array<AutoCompleteItem>>) =>{ this._autoCompleteService.autoComplete(searchText).then((message:Message<Array<AutoCompleteItem>>) => {
if(message.error){ if (message.error) {
//TODO: implement //TODO: implement
console.error(message.error); console.error(message.error);
return; return;
} }
this.showSuggestions(message.result,searchText); this.showSuggestions(message.result, searchText);
}); });
}else{ } else {
this.emptyAutoComplete(); this.emptyAutoComplete();
} }
} }
private showSuggestions(suggestions:Array<AutoCompleteItem>,searchText:string){ private showSuggestions(suggestions:Array<AutoCompleteItem>, searchText:string) {
this.emptyAutoComplete(); this.emptyAutoComplete();
suggestions.forEach((item)=>{ suggestions.forEach((item)=> {
let preIndex = item.text.toLowerCase().indexOf(searchText.toLowerCase()); let preIndex = item.text.toLowerCase().indexOf(searchText.toLowerCase());
let renderItem = new AutoCompleteRenderItem(); let renderItem = new AutoCompleteRenderItem();
if(preIndex > -1){ if (preIndex > -1) {
renderItem.preText = item.text.substring(0,preIndex); renderItem.preText = item.text.substring(0, preIndex);
renderItem.highLightText = item.text.substring(preIndex, preIndex + searchText.length); renderItem.highLightText = item.text.substring(preIndex, preIndex + searchText.length);
renderItem.postText = item.text.substring(preIndex + searchText.length); renderItem.postText = item.text.substring(preIndex + searchText.length);
}else{ } else {
renderItem.postText = item.text; renderItem.postText = item.text;
} }
this.autoCompleteItems.push(renderItem); this.autoCompleteItems.push(renderItem);
}); });
} }
public onFocusLost(event){ public onFocusLost(event) {
this.autoCompleteItems = []; this.autoCompleteItems = [];
} }
private emptyAutoComplete(){ private emptyAutoComplete() {
this.autoCompleteItems = []; this.autoCompleteItems = [];
} }
} }
class AutoCompleteRenderItem{ class AutoCompleteRenderItem {
constructor(public preText:string = "",public highLightText:string = "", public postText:string = ""){ constructor(public preText:string = "", public highLightText:string = "", public postText:string = "") {
} }
} }

View File

@ -1,7 +1,7 @@
///<reference path="../../browser.d.ts"/> ///<reference path="../../browser.d.ts"/>
import {Component, OnInit} from '@angular/core'; import {Component, OnInit} from "@angular/core";
import {LoginCredential} from '../../../common/entities/LoginCredential'; import {LoginCredential} from "../../../common/entities/LoginCredential";
import {AuthenticationService} from "../model/network/authentication.service.ts"; import {AuthenticationService} from "../model/network/authentication.service.ts";
import {Router} from "@angular/router-deprecated"; import {Router} from "@angular/router-deprecated";
import {FORM_DIRECTIVES} from "@angular/common"; import {FORM_DIRECTIVES} from "@angular/common";
@ -9,22 +9,23 @@ import {FORM_DIRECTIVES} from "@angular/common";
@Component({ @Component({
selector: 'login', selector: 'login',
templateUrl: 'app/login/login.component.html', templateUrl: 'app/login/login.component.html',
styleUrls:['app/login/login.component.css'], styleUrls: ['app/login/login.component.css'],
directives:[FORM_DIRECTIVES] directives: [FORM_DIRECTIVES]
}) })
export class LoginComponent implements OnInit{ export class LoginComponent implements OnInit {
loginCredential: LoginCredential; loginCredential:LoginCredential;
constructor(private _authService: AuthenticationService, private _router: Router) {
constructor(private _authService:AuthenticationService, private _router:Router) {
this.loginCredential = new LoginCredential(); this.loginCredential = new LoginCredential();
} }
ngOnInit(){ ngOnInit() {
if (this._authService.isAuthenticated()) { if (this._authService.isAuthenticated()) {
this._router.navigate(['Gallery',{directory:"/"}]); this._router.navigate(['Gallery', {directory: "/"}]);
} }
} }
onLogin(){ onLogin() {
this._authService.login(this.loginCredential); this._authService.login(this.loginCredential);
} }
} }

View File

@ -1,13 +1,7 @@
///<reference path="../../../browser.d.ts"/> ///<reference path="../../../browser.d.ts"/>
import { import {it, inject, beforeEachProviders} from "@angular/core/testing";
it, import {provide} from "@angular/core";
inject,
beforeEachProviders
} from '@angular/core/testing';
import {provide} from '@angular/core';
import {UserService} from "./user.service.ts"; import {UserService} from "./user.service.ts";
import {User} from "../../../../common/entities/User"; import {User} from "../../../../common/entities/User";
import {Message} from "../../../../common/entities/Message"; import {Message} from "../../../../common/entities/Message";
@ -16,8 +10,8 @@ import {LoginCredential} from "../../../../common/entities/LoginCredential";
import {AuthenticationService} from "./authentication.service"; import {AuthenticationService} from "./authentication.service";
class MockUserService { class MockUserService {
public login(credential:LoginCredential){ public login(credential:LoginCredential) {
return Promise.resolve(new Message<User>(null,new User(0,"testUserName"))) return Promise.resolve(new Message<User>(null, new User(0, "testUserName")))
} }
} }
@ -28,24 +22,24 @@ describe('AuthenticationService', () => {
]); ]);
it('should call User service login', inject([ AuthenticationService,UserService ], (authService, userService) => { it('should call User service login', inject([AuthenticationService, UserService], (authService, userService) => {
spyOn(userService,"login").and.callThrough(); spyOn(userService, "login").and.callThrough();
expect(userService.login).not.toHaveBeenCalled(); expect(userService.login).not.toHaveBeenCalled();
authService.login(); authService.login();
expect(userService.login).toHaveBeenCalled(); expect(userService.login).toHaveBeenCalled();
})); }));
it('should have NO Authenticated use', inject([ AuthenticationService ], (authService) => { it('should have NO Authenticated use', inject([AuthenticationService], (authService) => {
expect(authService.getUser()).toBe(null); expect(authService.getUser()).toBe(null);
expect(authService.isAuthenticated()).toBe(false); expect(authService.isAuthenticated()).toBe(false);
})); }));
it('should have Authenticated use', inject([ AuthenticationService ], (authService) => { it('should have Authenticated use', inject([AuthenticationService], (authService) => {
spyOn(authService.OnAuthenticated,"trigger").and.callThrough(); spyOn(authService.OnAuthenticated, "trigger").and.callThrough();
authService.login(); authService.login();
authService.OnAuthenticated.on(() =>{ authService.OnAuthenticated.on(() => {
expect(authService.OnAuthenticated.trigger).toHaveBeenCalled(); expect(authService.OnAuthenticated.trigger).toHaveBeenCalled();
expect(authService.getUser()).not.toBe(null); expect(authService.getUser()).not.toBe(null);
expect(authService.isAuthenticated()).toBe(true); expect(authService.isAuthenticated()).toBe(true);

View File

@ -1,30 +1,30 @@
///<reference path="../../../browser.d.ts"/> ///<reference path="../../../browser.d.ts"/>
import {Injectable} from '@angular/core'; import {Injectable} from "@angular/core";
import {User} from "../../../../common/entities/User"; import {User} from "../../../../common/entities/User";
import {Event} from "../../../../common/event/Event"; import {Event} from "../../../../common/event/Event";
import {UserService} from "./user.service.ts"; import {UserService} from "./user.service.ts";
import {LoginCredential} from "../../../../common/entities/LoginCredential"; import {LoginCredential} from "../../../../common/entities/LoginCredential";
import {Message} from "../../../../common/entities/Message"; import {Message} from "../../../../common/entities/Message";
import { Cookie } from 'ng2-cookies/ng2-cookies'; import {Cookie} from "ng2-cookies/ng2-cookies";
import {ErrorCodes} from "../../../../common/entities/Error"; import {ErrorCodes} from "../../../../common/entities/Error";
declare module ServerInject{ declare module ServerInject {
export var user; export var user;
} }
@Injectable() @Injectable()
export class AuthenticationService{ export class AuthenticationService {
private _user:User = null; private _user:User = null;
public OnAuthenticated:Event<User>; public OnAuthenticated:Event<User>;
constructor(private _userService: UserService){ constructor(private _userService:UserService) {
this.OnAuthenticated = new Event(); this.OnAuthenticated = new Event();
//picking up session.. //picking up session..
if(this.isAuthenticated() == false && Cookie.getCookie('pigallery2-session') != null){ if (this.isAuthenticated() == false && Cookie.getCookie('pigallery2-session') != null) {
if(typeof ServerInject !== "undefined" && typeof ServerInject.user !== "undefined"){ if (typeof ServerInject !== "undefined" && typeof ServerInject.user !== "undefined") {
console.log("user found"); console.log("user found");
this.setUser(ServerInject.user); this.setUser(ServerInject.user);
} }
@ -33,38 +33,38 @@ export class AuthenticationService{
} }
private getSessionUser(){ private getSessionUser() {
this._userService.getSessionUser().then( (message:Message<User>) =>{ this._userService.getSessionUser().then((message:Message<User>) => {
if(message.error){ if (message.error) {
console.log(message.error); console.log(message.error);
}else{ } else {
this._user = message.result; this._user = message.result;
this.OnAuthenticated.trigger(this._user); this.OnAuthenticated.trigger(this._user);
} }
}); });
} }
private setUser(user:User){ private setUser(user:User) {
this._user = user; this._user = user;
this.OnAuthenticated.trigger(this._user); this.OnAuthenticated.trigger(this._user);
} }
public login(credential:LoginCredential) { public login(credential:LoginCredential) {
this._userService.login(credential).then( (message:Message<User>) =>{ this._userService.login(credential).then((message:Message<User>) => {
if(message.error){ if (message.error) {
console.log(ErrorCodes[message.error.code] + "message: "+ message.error.message); console.log(ErrorCodes[message.error.code] + "message: " + message.error.message);
}else{ } else {
this.setUser(message.result); this.setUser(message.result);
} }
}); });
} }
public isAuthenticated():boolean{ public isAuthenticated():boolean {
return (this._user && this._user != null) ? true : false; return (this._user && this._user != null) ? true : false;
} }
public getUser(){ public getUser() {
return this._user; return this._user;
} }

View File

@ -1,7 +1,7 @@
///<reference path="../../../browser.d.ts"/> ///<reference path="../../../browser.d.ts"/>
import {it, inject, beforeEachProviders, beforeEach, afterEach} from "@angular/core/testing"; import {it, inject, beforeEachProviders, beforeEach, afterEach} from "@angular/core/testing";
import {BaseRequestOptions, Http, Response, ResponseOptions, ResponseType, BaseResponseOptions} from "@angular/http"; import {BaseRequestOptions, Http, Response, ResponseOptions} from "@angular/http";
import {MockBackend, MockConnection} from "@angular/http/testing"; import {MockBackend, MockConnection} from "@angular/http/testing";
import {provide} from "@angular/core"; import {provide} from "@angular/core";
import "rxjs/Rx"; import "rxjs/Rx";
@ -115,7 +115,7 @@ describe('NetworkService Fail tests', () => {
backend.connections.subscribe((c) => { backend.connections.subscribe((c) => {
connection = c; connection = c;
connection.mockError({name :"errorName",message:testError}); connection.mockError({name: "errorName", message: testError});
}); });
})); }));

View File

@ -1,54 +1,54 @@
///<reference path="../../../browser.d.ts"/> ///<reference path="../../../browser.d.ts"/>
import {Injectable} from '@angular/core'; import {Injectable} from "@angular/core";
import {Http, Headers, RequestOptions} from "@angular/http"; import {Http, Headers, RequestOptions} from "@angular/http";
import {Message} from "../../../../common/entities/Message"; import {Message} from "../../../../common/entities/Message";
import "rxjs/Rx"; import "rxjs/Rx";
@Injectable() @Injectable()
export class NetworkService{ export class NetworkService {
_baseUrl = "/api"; _baseUrl = "/api";
constructor(protected _http:Http){ constructor(protected _http:Http) {
} }
private callJson<T>(method:string, url:string, data:any = {}): Promise<T>{ private callJson<T>(method:string, url:string, data:any = {}):Promise<T> {
let body = JSON.stringify( data ); let body = JSON.stringify(data);
let headers = new Headers({ 'Content-Type': 'application/json' }); let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers }); let options = new RequestOptions({headers: headers});
if(method == "get" || method == "delete"){ if (method == "get" || method == "delete") {
return this._http[method](this._baseUrl+url, options) return this._http[method](this._baseUrl + url, options)
.toPromise() .toPromise()
.then(res => <Message<any>> res.json()) .then(res => <Message<any>> res.json())
.catch(NetworkService.handleError); .catch(NetworkService.handleError);
} }
return this._http[method](this._baseUrl+url, body, options) return this._http[method](this._baseUrl + url, body, options)
.toPromise() .toPromise()
.then(res => <Message<any>> res.json()) .then(res => <Message<any>> res.json())
.catch(NetworkService.handleError); .catch(NetworkService.handleError);
} }
public postJson<T>(url:string, data:any = {}): Promise<T>{ public postJson<T>(url:string, data:any = {}):Promise<T> {
return this.callJson("post",url,data); return this.callJson("post", url, data);
} }
public putJson<T>(url:string, data:any = {}): Promise<T>{ public putJson<T>(url:string, data:any = {}):Promise<T> {
return this.callJson("put",url,data); return this.callJson("put", url, data);
} }
public getJson<T>(url:string): Promise<T>{ public getJson<T>(url:string):Promise<T> {
return this.callJson("get",url); return this.callJson("get", url);
} }
public deleteJson<T>(url:string): Promise<T>{ public deleteJson<T>(url:string):Promise<T> {
return this.callJson("delete",url); return this.callJson("delete", url);
} }
private static handleError (error: any) { private static handleError(error:any) {
// TODO: in a real world app, we may send the error to some remote logging infrastructure // TODO: in a real world app, we may send the error to some remote logging infrastructure
// instead of just logging it to the console // instead of just logging it to the console
console.error(error); console.error(error);

View File

@ -1,14 +1,12 @@
///<reference path="../../../browser.d.ts"/> ///<reference path="../../../browser.d.ts"/>
import {it, inject, beforeEachProviders, beforeEach, afterEach} from "@angular/core/testing"; import {it, inject, beforeEachProviders} from "@angular/core/testing";
import {BaseRequestOptions, Http, Response, ResponseOptions} from "@angular/http"; import {BaseRequestOptions, Http} from "@angular/http";
import {MockBackend, MockConnection} from "@angular/http/testing"; import {MockBackend} from "@angular/http/testing";
import {provide} from "@angular/core"; import {provide} from "@angular/core";
import "rxjs/Rx"; import "rxjs/Rx";
import {NetworkService} from "./network.service"; import {NetworkService} from "./network.service";
import {Message} from "../../../../common/entities/Message";
import {UserService} from "./user.service"; import {UserService} from "./user.service";
import {LoginComponent} from "../../login/login.component";
import {LoginCredential} from "../../../../common/entities/LoginCredential"; import {LoginCredential} from "../../../../common/entities/LoginCredential";
@ -28,25 +26,20 @@ describe('UserService', () => {
]); ]);
it('should call postJson at login', inject([UserService, NetworkService], (userService, networkService) => {
spyOn(networkService, "postJson");
let credential = new LoginCredential("name", "pass");
it('should call postJson at login', inject([UserService,NetworkService], (userService,networkService) => {
spyOn(networkService,"postJson");
let credential = new LoginCredential("name","pass");
userService.login(credential); userService.login(credential);
expect(networkService.postJson).toHaveBeenCalled(); expect(networkService.postJson).toHaveBeenCalled();
expect(networkService.postJson.calls.argsFor(0)).toEqual(["/user/login",{"loginCredential": credential}]); expect(networkService.postJson.calls.argsFor(0)).toEqual(["/user/login", {"loginCredential": credential}]);
})); }));
it('should call getJson at getSessionUser', inject([UserService,NetworkService], (userService,networkService) => { it('should call getJson at getSessionUser', inject([UserService, NetworkService], (userService, networkService) => {
spyOn(networkService,"getJson"); spyOn(networkService, "getJson");
userService.getSessionUser(); userService.getSessionUser();
expect(networkService.getJson).toHaveBeenCalled(); expect(networkService.getJson).toHaveBeenCalled();
expect(networkService.getJson.calls.argsFor(0)).toEqual(["/user/login"]); expect(networkService.getJson.calls.argsFor(0)).toEqual(["/user/login"]);
})); }));
}); });

View File

@ -1,26 +1,24 @@
///<reference path="../../../browser.d.ts"/> ///<reference path="../../../browser.d.ts"/>
import {Injectable} from '@angular/core'; import {Injectable} from "@angular/core";
import {LoginCredential} from "../../../../common/entities/LoginCredential"; import {LoginCredential} from "../../../../common/entities/LoginCredential";
import {Http} from "@angular/http";
import {NetworkService} from "./network.service.ts"; import {NetworkService} from "./network.service.ts";
import {User} from "../../../../common/entities/User"; import {User} from "../../../../common/entities/User";
import {Message} from "../../../../common/entities/Message"; import {Message} from "../../../../common/entities/Message";
@Injectable() @Injectable()
export class UserService{ export class UserService {
constructor(private _networkService:NetworkService) {
constructor(private _networkService:NetworkService){
} }
public login(credential:LoginCredential): Promise<Message<User>>{ public login(credential:LoginCredential):Promise<Message<User>> {
return this._networkService.postJson("/user/login",{"loginCredential": credential}); return this._networkService.postJson("/user/login", {"loginCredential": credential});
} }
public getSessionUser(): Promise<Message<User>>{ public getSessionUser():Promise<Message<User>> {
return this._networkService.getJson("/user/login"); return this._networkService.getJson("/user/login");
} }

View File

@ -4,7 +4,7 @@ import {UserRoles} from "../../../common/entities/User";
@Pipe({name: 'stringifyRole'}) @Pipe({name: 'stringifyRole'})
export class StringifyRole implements PipeTransform { export class StringifyRole implements PipeTransform {
transform(role: string): number { transform(role:string):number {
return UserRoles[role]; return UserRoles[role];
} }
} }

View File

@ -1,6 +1,6 @@
///<reference path="../typings/browser.d.ts"/> ///<reference path="../typings/browser.d.ts"/>
import { bootstrap } from '@angular/platform-browser-dynamic'; import {bootstrap} from "@angular/platform-browser-dynamic";
import {AppComponent} from "./app/app.component.ts"; import {AppComponent} from "./app/app.component.ts";
bootstrap(AppComponent) bootstrap(AppComponent)