diff --git a/backend/ProjectPath.ts b/backend/ProjectPath.ts index b2a77d0..77617d9 100644 --- a/backend/ProjectPath.ts +++ b/backend/ProjectPath.ts @@ -2,12 +2,12 @@ import * as path from "path"; import {Config} from "./config/Config"; class ProjectPathClass { - public Root:string; - public ImageFolder:string; - public ThumbnailFolder:string; + public Root: string; + public ImageFolder: string; + public ThumbnailFolder: string; - isAbsolutePath(pathStr) { - return path.resolve(pathStr) === path.normalize(pathStr).replace(RegExp(pathStr.sep + '$'), ''); + isAbsolutePath(pathStr: string) { + return path.resolve(pathStr) === path.normalize(pathStr); } constructor() { @@ -17,4 +17,4 @@ class ProjectPathClass { } } -export var ProjectPath = new ProjectPathClass(); \ No newline at end of file +export let ProjectPath = new ProjectPathClass(); \ No newline at end of file diff --git a/backend/config/Config.ts b/backend/config/Config.ts index 6fb5fe8..1994774 100644 --- a/backend/config/Config.ts +++ b/backend/config/Config.ts @@ -1,10 +1,8 @@ -/// - -import {ConfigLoader} from "./../../backend/config/ConfigLoader"; +import {ConfigLoader} from "./ConfigLoader"; import * as path from "path"; import {ConfigClass, DatabaseType} from "../../common/config/Config"; -export var Config = new ConfigClass(); +export let Config = new ConfigClass(); Config.Server = { port: 80, diff --git a/backend/config/ConfigLoader.ts b/backend/config/ConfigLoader.ts index a782342..4b00fdd 100644 --- a/backend/config/ConfigLoader.ts +++ b/backend/config/ConfigLoader.ts @@ -3,16 +3,16 @@ import * as optimist from "optimist"; export class ConfigLoader { - static init(configObject:any, configFilePath?:string, envAlias:Array> = []) { + static init(configObject: any, configFilePath?: string, envAlias: Array> = []) { this.processConfigFile(configFilePath, configObject); this.processArguments(configObject); this.processEnvVariables(configObject, envAlias); } - private static processEnvVariables(configObject:any, envAlias:Array>) { + private static processEnvVariables(configObject: any, envAlias: Array>) { let varAliases = {}; - envAlias.forEach((alias)=> { + envAlias.forEach((alias) => { if (process.env[alias[0]]) { varAliases[alias[1]] = process.env[alias[0]]; } @@ -21,24 +21,25 @@ export class ConfigLoader { this.loadObject(configObject, process.env); }; - private static processArguments(configObject:any) { + private static processArguments(configObject: any) { let argv = optimist.argv; delete(argv._); delete(argv.$0); this.processHierarchyVar(configObject, argv); }; - private static processHierarchyVar(configObject:any, vars:any) { + + private static processHierarchyVar(configObject: any, vars: any) { let config = {}; - Object.keys(vars).forEach((key)=> { + Object.keys(vars).forEach((key) => { let keyArray = key.split("-"); let value = vars[key]; //recursive settings - let setObject = (object, keyArray, value) => { + let setObject = (object: any, keyArray: Array, value: any): void => { let key = keyArray.shift(); - object[key] = {}; + object[key] = object[key] || {}; if (keyArray.length == 0) { //convert to boolean @@ -48,6 +49,7 @@ export class ConfigLoader { if (value.toLowerCase && value.toLowerCase() === "true") { value = true; } + object[key] = value; return; } @@ -57,10 +59,11 @@ export class ConfigLoader { setObject(config, keyArray, value); }); + this.loadObject(configObject, config); } - private static processConfigFile(configFilePath:string, configObject:any) { + private static processConfigFile(configFilePath: string, configObject: any) { if (typeof configFilePath !== 'undefined') { if (ConfigLoader.loadConfigFile(configFilePath, configObject) === false) { ConfigLoader.saveConfigFile(configFilePath, configObject); @@ -68,7 +71,7 @@ export class ConfigLoader { } }; - private static loadConfigFile(configFilePath, configObject):boolean { + private static loadConfigFile(configFilePath: string, configObject: any): boolean { if (fs.existsSync(configFilePath) === false) { return false; } @@ -84,7 +87,7 @@ export class ConfigLoader { } - private static saveConfigFile(configFilePath, configObject) { + private static saveConfigFile(configFilePath: string, configObject: any) { try { fs.writeFileSync(configFilePath, JSON.stringify(configObject, null, 4)); } catch (err) { @@ -92,8 +95,8 @@ export class ConfigLoader { } } - private static loadObject(targetObject, sourceObject) { - Object.keys(sourceObject).forEach((key)=> { + private static loadObject(targetObject: any, sourceObject: any) { + Object.keys(sourceObject).forEach((key) => { if (typeof targetObject[key] === "undefined") { return; } diff --git a/backend/middlewares/user/AuthenticationMWs.ts b/backend/middlewares/user/AuthenticationMWs.ts index 043983c..4229ae5 100644 --- a/backend/middlewares/user/AuthenticationMWs.ts +++ b/backend/middlewares/user/AuthenticationMWs.ts @@ -1,6 +1,4 @@ /// -/// - import {NextFunction, Request, Response} from "express"; import {Error, ErrorCodes} from "../../../common/entities/Error"; import {UserRoles, User} from "../../../common/entities/User"; @@ -12,6 +10,7 @@ export class AuthenticationMWs { public static authenticate(req:Request, res:Response, next:NextFunction) { if (Config.Client.authenticationRequired === false) { req.session.user = new User("", "", UserRoles.Admin); + return next(); } if (typeof req.session.user === 'undefined') { diff --git a/backend/model/DiskManger.ts b/backend/model/DiskManger.ts index 4b77a8a..36c05e1 100644 --- a/backend/model/DiskManger.ts +++ b/backend/model/DiskManger.ts @@ -1,6 +1,4 @@ /// - - import * as fs from "fs"; import * as path from "path"; import * as mime from "mime"; @@ -18,7 +16,7 @@ import { import {ProjectPath} from "../ProjectPath"; export class DiskManager { - public static scanDirectory(relativeDirectoryName, cb:(error:any, result:Directory) => void) { + public static scanDirectory(relativeDirectoryName: string, cb: (error: any, result: Directory) => void) { console.log("DiskManager: scanDirectory"); let directoryName = path.basename(relativeDirectoryName); let directoryParent = path.join(path.dirname(relativeDirectoryName), "/"); @@ -26,7 +24,7 @@ export class DiskManager { let directory = new Directory(1, directoryName, directoryParent, new Date(), [], []); - let promises:Array< Promise > = []; + let promises: Array< Promise > = []; fs.readdir(absoluteDirectoryName, function (err, list) { if (err) { @@ -44,7 +42,7 @@ export class DiskManager { if (DiskManager.isImage(fullFilePath)) { - let promise = DiskManager.loadPhotoMetadata(fullFilePath).then((photoMetadata)=> { + let promise = DiskManager.loadPhotoMetadata(fullFilePath).then((photoMetadata) => { directory.photos.push(new Photo(1, file, directory, photoMetadata)); }); @@ -52,14 +50,14 @@ export class DiskManager { } } - Promise.all(promises).then(()=> { + Promise.all(promises).then(() => { return cb(err, directory); }); }); } - private static isImage(fullPath) { + private static isImage(fullPath: string) { let imageMimeTypes = [ 'image/bmp', 'image/gif', @@ -72,7 +70,7 @@ export class DiskManager { 'image/x-windows-bmp' ]; - var extension = mime.lookup(fullPath); + let extension = mime.lookup(fullPath); if (imageMimeTypes.indexOf(extension) !== -1) { return true; @@ -113,8 +111,8 @@ export class DiskManager { } };*/ - private static loadPhotoMetadata(fullPath):Promise { - return new Promise((resolve:(metadata:PhotoMetadata)=>void, reject) => { + private static loadPhotoMetadata(fullPath: string): Promise { + return new Promise((resolve: (metadata: PhotoMetadata) => void, reject) => { fs.readFile(fullPath, function (err, data) { if (err) { reject(err); @@ -122,8 +120,8 @@ export class DiskManager { let exif = exif_parser.create(data).parse(); let iptcData = iptc(data); - let imageSize:ImageSize = {width: exif.imageSize.width, height: exif.imageSize.height}; - let cameraData:CameraMetadata = { + let imageSize: ImageSize = {width: exif.imageSize.width, height: exif.imageSize.height}; + let cameraData: CameraMetadata = { ISO: exif.tags.ISO, model: exif.tags.Modeol, maker: exif.tags.Make, @@ -132,14 +130,14 @@ export class DiskManager { focalLength: exif.tags.FocalLength, lens: exif.tags.LensModel, }; - let GPS:GPSMetadata = { + let GPS: GPSMetadata = { latitude: exif.tags.GPSLatitude, longitude: exif.tags.GPSLongitude, altitude: exif.tags.GPSAltitude }; - let positionData:PositionMetaData = { + let positionData: PositionMetaData = { GPSData: GPS, country: iptcData.country_or_primary_location_name, state: iptcData.province_or_state, @@ -147,24 +145,21 @@ export class DiskManager { }; //Decode characters to UTF8 - let decode = (s)=> { - for (var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l; - + let decode = (s: any) => { + for (let a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l; ((a = s[i][c](0)) & 0x80) && - (s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ? - o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "") ); return s.join(""); }; - let keywords:[string] = iptcData.keywords.map(s => decode(s)); - let creationDate:Date = iptcData.date_time; + let keywords: [string] = iptcData.keywords.map((s: string) => decode(s)); + let creationDate: Date = iptcData.date_time; console.log(keywords); - let metadata:PhotoMetadata = new PhotoMetadata(keywords, cameraData, positionData, imageSize, creationDate); + let metadata: PhotoMetadata = new PhotoMetadata(keywords, cameraData, positionData, imageSize, creationDate); resolve(metadata); } }); diff --git a/backend/model/IGalleryManager.ts b/backend/model/IGalleryManager.ts index 27b77e8..c3722ad 100644 --- a/backend/model/IGalleryManager.ts +++ b/backend/model/IGalleryManager.ts @@ -1,4 +1,4 @@ import {Directory} from "../../common/entities/Directory"; export interface IGalleryManager { - listDirectory(relativeDirectoryName, cb:(error:any, result:Directory) => void); + listDirectory(relativeDirectoryName: string, cb: (error: any, result: Directory) => void): void; } \ No newline at end of file diff --git a/backend/model/ISearchManager.ts b/backend/model/ISearchManager.ts index 017c6dc..1512ae1 100644 --- a/backend/model/ISearchManager.ts +++ b/backend/model/ISearchManager.ts @@ -1,7 +1,7 @@ import {AutoCompleteItem, SearchTypes} from "../../common/entities/AutoCompleteItem"; import {SearchResult} from "../../common/entities/SearchResult"; export interface ISearchManager { - autocomplete(text:string, cb:(error:any, result:Array) => void); - search(text:string, searchType:SearchTypes, cb:(error:any, result:SearchResult) => void); - instantSearch(text:string, cb:(error:any, result:SearchResult) => void); + autocomplete(text: string, cb: (error: any, result: Array) => void): void; + search(text: string, searchType: SearchTypes, cb: (error: any, result: SearchResult) => void): void; + instantSearch(text: string, cb: (error: any, result: SearchResult) => void): void; } \ No newline at end of file diff --git a/backend/model/IUserManager.ts b/backend/model/IUserManager.ts index 5b284a9..4433387 100644 --- a/backend/model/IUserManager.ts +++ b/backend/model/IUserManager.ts @@ -1,9 +1,9 @@ import {User, UserRoles} from "../../common/entities/User"; export interface IUserManager { - findOne(filter, cb:(error:any, result:User) => void); - find(filter, cb:(error:any, result:Array) => void); - createUser(user, cb:(error:any, result:User) => void); - deleteUser(id:number, cb:(error:any, result:string) => void); - changeRole(id:number, newRole:UserRoles, cb:(error:any) => void); - changePassword(request:any, cb:(error:any, result:string) => void); + findOne(filter: any, cb: (error: any, result: User) => void): void; + find(filter: any, cb: (error: any, result: Array) => void): void; + createUser(user: User, cb: (error: any, result: User) => void): void; + deleteUser(id: number, cb: (error: any, result: string) => void): void; + changeRole(id: number, newRole: UserRoles, cb: (error: any) => void): void; + changePassword(request: any, cb: (error: any, result: string) => void): void; } \ No newline at end of file diff --git a/backend/model/ObjectManagerRepository.ts b/backend/model/ObjectManagerRepository.ts index afa449b..734a6a1 100644 --- a/backend/model/ObjectManagerRepository.ts +++ b/backend/model/ObjectManagerRepository.ts @@ -1,5 +1,3 @@ -/// - import {IUserManager} from "./IUserManager"; import {IGalleryManager} from "./IGalleryManager"; import {ISearchManager} from "./ISearchManager"; diff --git a/backend/model/memory/GalleryManager.ts b/backend/model/memory/GalleryManager.ts index 91999da..43823d0 100644 --- a/backend/model/memory/GalleryManager.ts +++ b/backend/model/memory/GalleryManager.ts @@ -5,7 +5,7 @@ import {DiskManager} from "../DiskManger"; export class GalleryManager implements IGalleryManager { - public listDirectory(relativeDirectoryName, cb:(error:any, result:Directory) => void) { + public listDirectory(relativeDirectoryName: string, cb: (error: any, result: Directory) => void) { return DiskManager.scanDirectory(relativeDirectoryName, cb); } diff --git a/backend/model/memory/SearchManager.ts b/backend/model/memory/SearchManager.ts index 12e50a3..315f39d 100644 --- a/backend/model/memory/SearchManager.ts +++ b/backend/model/memory/SearchManager.ts @@ -5,15 +5,15 @@ import {SearchResult} from "../../../common/entities/SearchResult"; export class SearchManager implements ISearchManager { - autocomplete(text, cb:(error:any, result:Array) => void) { + autocomplete(text: string, cb: (error: any, result: Array) => void) { throw new Error("not implemented"); } - search(text, searchType:SearchTypes, cb:(error:any, result:SearchResult) => void) { + search(text: string, searchType: SearchTypes, cb: (error: any, result: SearchResult) => void) { throw new Error("not implemented"); } - instantSearch(text, cb:(error:any, result:SearchResult) => void) { + instantSearch(text: string, cb: (error: any, result: SearchResult) => void) { throw new Error("not implemented"); } diff --git a/backend/model/memory/UserManager.ts b/backend/model/memory/UserManager.ts index 9c17a63..1187b0f 100644 --- a/backend/model/memory/UserManager.ts +++ b/backend/model/memory/UserManager.ts @@ -1,6 +1,4 @@ /// - - import {User, UserRoles} from "../../../common/entities/User"; import {IUserManager} from "../IUserManager"; import {ProjectPath} from "../../ProjectPath"; @@ -10,9 +8,9 @@ import * as path from "path"; export class UserManager implements IUserManager { - private db:any = null; + private db: any = null; - generateId():string { + generateId(): string { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) @@ -43,8 +41,8 @@ export class UserManager implements IUserManager { } - public findOne(filter, cb:(error:any, result:User) => void) { - this.find(filter, (error, result:Array)=> { + public findOne(filter: any, cb: (error: any, result: User) => void) { + this.find(filter, (error, result: Array) => { if (error) { return cb(error, null); } @@ -56,14 +54,14 @@ export class UserManager implements IUserManager { }); } - public find(filter, cb:(error:any, result:Array) => void) { + public find(filter: any, cb: (error: any, result: Array) => void) { - let users = this.db.get("users").filter((u) => Utils.equalsFilter(u, filter)); + let users = this.db.get("users").filter((u: User) => Utils.equalsFilter(u, filter)); return cb(null, users); } - public createUser(user:User, cb:(error:any, result:User) => void = (e, r) => { + public createUser(user: User, cb: (error: any, result: User) => void = (e, r) => { }) { user.id = parseInt(this.db.get("idCounter")) + 1; this.db.put("idCounter", user.id); @@ -74,15 +72,15 @@ export class UserManager implements IUserManager { return cb(null, user); } - public deleteUser(id:number, cb:(error:any) => void) { - let users = this.db.get("users").filter((u) => u.id != id); + public deleteUser(id: number, cb: (error: any) => void) { + let users = this.db.get("users").filter((u: User) => u.id != id); this.db.put("users", users); 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) { - let users:Array = this.db.get("users"); + let users: Array = this.db.get("users"); for (let i = 0; i < users.length; i++) { if (users[i].id == id) { @@ -93,7 +91,7 @@ export class UserManager implements IUserManager { this.db.put("users", users); } - 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 } diff --git a/backend/model/memory/flat-file-db.ts b/backend/model/memory/flat-file-db.ts index cb5b6c9..3ce09f2 100644 --- a/backend/model/memory/flat-file-db.ts +++ b/backend/model/memory/flat-file-db.ts @@ -1,13 +1,13 @@ declare module "flat-file-db" { - export function sync(path:string):DB; + export function sync(path: string): DB; } declare interface DB { - sync(); - put(); - get(); - del(); - has(); - keys(); - close(); + sync(): any; + put(): any; + get(): any; + del(): any; + has(): any; + keys(): any; + close(): any; } \ No newline at end of file diff --git a/backend/routes/AdminRouter.ts b/backend/routes/AdminRouter.ts index b191350..03efbcc 100644 --- a/backend/routes/AdminRouter.ts +++ b/backend/routes/AdminRouter.ts @@ -1,10 +1,8 @@ -/// - import {AuthenticationMWs} from "../middlewares/user/AuthenticationMWs"; import {UserRoles} from "../../common/entities/User"; export class AdminRouter { - constructor(private app) { + constructor(private app: any) { this.addResetDB(); this.addIndexGallery(); diff --git a/backend/routes/ErrorRouter.ts b/backend/routes/ErrorRouter.ts index 41803cc..4f27a04 100644 --- a/backend/routes/ErrorRouter.ts +++ b/backend/routes/ErrorRouter.ts @@ -1,10 +1,10 @@ -/// - import {RenderingMWs} from "../middlewares/RenderingMWs"; import {Error, ErrorCodes} from "../../common/entities/Error"; +import Request = Express.Request; +import Response = Express.Response; export class ErrorRouter { - constructor(private app) { + constructor(private app: any) { this.addApiErrorHandler(); this.addGenericHandler(); @@ -17,7 +17,7 @@ export class ErrorRouter { }; private addGenericHandler() { - this.app.use((err, req, res, next) => { + this.app.use((err: any, req: Request, res: Response, next: Function) => { //Flush out the stack to the console console.error(err.stack); diff --git a/backend/routes/GalleryRouter.ts b/backend/routes/GalleryRouter.ts index 6deb03e..00133ee 100644 --- a/backend/routes/GalleryRouter.ts +++ b/backend/routes/GalleryRouter.ts @@ -1,12 +1,10 @@ -/// - import {AuthenticationMWs} from "../middlewares/user/AuthenticationMWs"; import {GalleryMWs} from "../middlewares/GalleryMWs"; import {RenderingMWs} from "../middlewares/RenderingMWs"; import {ThumbnailGeneratorMWs} from "../middlewares/ThumbnailGeneratorMWs"; export class GalleryRouter { - constructor(private app) { + constructor(private app: any) { this.addGetImageThumbnail(); this.addGetImage(); diff --git a/backend/routes/PublicRouter.ts b/backend/routes/PublicRouter.ts index 67cf554..73d8bb4 100644 --- a/backend/routes/PublicRouter.ts +++ b/backend/routes/PublicRouter.ts @@ -1,5 +1,3 @@ -/// - import * as _express from "express"; import {NextFunction, Request, Response} from "express"; import * as _path from "path"; @@ -24,8 +22,9 @@ export class PublicRouter { this.app.use(_express.static(_path.resolve(__dirname, './../../frontend'))); this.app.use('/node_modules', _express.static(_path.resolve(__dirname, './../../node_modules'))); + this.app.use('/common', _express.static(_path.resolve(__dirname, './../../common'))); - var renderIndex = (req:Request, res:Response) => { + const renderIndex = (req: Request, res: Response) => { res.render(_path.resolve(__dirname, './../../frontend/index.ejs'), res.tpl); }; diff --git a/backend/routes/SharingRouter.ts b/backend/routes/SharingRouter.ts index 9776002..f28490e 100644 --- a/backend/routes/SharingRouter.ts +++ b/backend/routes/SharingRouter.ts @@ -1,10 +1,8 @@ -/// - import {AuthenticationMWs} from "../middlewares/user/AuthenticationMWs"; import {UserRoles} from "../../common/entities/User"; export class SharingRouter { - constructor(private app) { + constructor(private app: any) { this.addGetSharing(); this.addUpdateSharing(); diff --git a/backend/routes/UserRouter.ts b/backend/routes/UserRouter.ts index df66c99..eec7ec7 100644 --- a/backend/routes/UserRouter.ts +++ b/backend/routes/UserRouter.ts @@ -1,5 +1,3 @@ -/// - import {UserMWs} from "../middlewares/user/UserMWs"; import {UserRoles} from "../../common/entities/User"; import {AuthenticationMWs} from "../middlewares/user/AuthenticationMWs"; diff --git a/backend/server.ts b/backend/server.ts index 7cc1aeb..4c4e98f 100644 --- a/backend/server.ts +++ b/backend/server.ts @@ -1,5 +1,3 @@ -/// - import * as _express from "express"; import * as _session from "express-session"; import * as _bodyParser from "body-parser"; @@ -11,16 +9,16 @@ import {GalleryRouter} from "./routes/GalleryRouter"; import {AdminRouter} from "./routes/AdminRouter"; import {ErrorRouter} from "./routes/ErrorRouter"; import {SharingRouter} from "./routes/SharingRouter"; -import {DatabaseType} from "./../common/config/Config"; +import {DatabaseType} from "../common/config/Config"; import {ObjectManagerRepository} from "./model/ObjectManagerRepository"; import {Config} from "./config/Config"; export class Server { - private debug:any; - private app:any; - private server:any; + private debug: any; + private app: any; + private server: any; constructor() { @@ -30,7 +28,7 @@ export class Server { this.app.set('view engine', 'ejs'); if (process.env.DEBUG) { - var _morgan = require('morgan'); + let _morgan = require('morgan'); this.app.use(_morgan('dev')); } @@ -90,7 +88,7 @@ export class Server { /** * Event listener for HTTP server "error" event. */ - private onError = (error) => { + private onError = (error: any) => { if (error.syscall !== 'listen') { throw error; } diff --git a/backend/tsconfig.json b/backend/tsconfig.json index 9adcce7..30660b3 100644 --- a/backend/tsconfig.json +++ b/backend/tsconfig.json @@ -1,15 +1,15 @@ { "compilerOptions": { "target": "es5", - "sourceMap": false, "module": "commonjs", "moduleResolution": "node", + "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, - "removeComments": false - }, - "exclude": [ - "node_modules", - "typings" - ] -} \ No newline at end of file + "lib": [ + "es2015", + "dom" + ], + "suppressImplicitAnyIndexErrors": true + } +} diff --git a/common/Utils.ts b/common/Utils.ts index 649b61a..2cce111 100644 --- a/common/Utils.ts +++ b/common/Utils.ts @@ -1,11 +1,11 @@ export class Utils { - static clone(object:T):T { + static clone(object: T): T { return JSON.parse(JSON.stringify(object)); } - static equalsFilter(object:any, filter:any):boolean { + static equalsFilter(object: any, filter: any): boolean { let keys = Object.keys(filter); for (let i = 0; i < keys.length; i++) { @@ -19,7 +19,7 @@ export class Utils { } - static concatUrls(...args:Array) { + static concatUrls(...args: Array) { let url = ""; for (let i = 0; i < args.length; i++) { if (args[i] === "" || typeof args[i] === "undefined") continue; @@ -34,8 +34,8 @@ export class Utils { return url.substring(0, url.length - 1); } - public static updateKeys(targetObject, sourceObject) { - Object.keys(sourceObject).forEach((key)=> { + public static updateKeys(targetObject: any, sourceObject: any) { + Object.keys(sourceObject).forEach((key) => { if (typeof targetObject[key] === "undefined") { return; } @@ -47,8 +47,8 @@ export class Utils { }); } - public static setKeys(targetObject, sourceObject) { - Object.keys(sourceObject).forEach((key)=> { + public static setKeys(targetObject: any, sourceObject: any) { + Object.keys(sourceObject).forEach((key) => { if (typeof targetObject[key] === "object") { Utils.setKeys(targetObject[key], sourceObject[key]); } else { @@ -57,8 +57,8 @@ export class Utils { }); } - public static setKeysForced(targetObject, sourceObject) { - Object.keys(sourceObject).forEach((key)=> { + public static setKeysForced(targetObject: any, sourceObject: any) { + Object.keys(sourceObject).forEach((key) => { if (typeof sourceObject[key] === "object") { if (typeof targetObject[key] === "undefined") { targetObject[key] = {}; @@ -70,8 +70,8 @@ export class Utils { }); } - public static enumToArray(EnumType):Array<{key:number;value:string;}> { - let arr:Array<{key:number;value:string;}> = []; + public static enumToArray(EnumType: any): Array<{key: number;value: string;}> { + let arr: Array<{key: number;value: string;}> = []; for (let enumMember in EnumType) { if (!EnumType.hasOwnProperty(enumMember)) { continue; @@ -85,12 +85,12 @@ export class Utils { } - public static findClosest(number:number, arr:Array) { + public static findClosest(number: number, arr: Array) { let curr = arr[0]; let diff = Math.abs(number - curr); - arr.forEach((value)=> { + arr.forEach((value) => { let newDiff = Math.abs(number - value); diff --git a/common/event/Event.ts b/common/event/Event.ts index 69fc992..5c4faa9 100644 --- a/common/event/Event.ts +++ b/common/event/Event.ts @@ -1,19 +1,19 @@ -function isFunction(functionToCheck) { - var getType = {}; +function isFunction(functionToCheck: any) { + let getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } export class Event { - private handlers: { (data?: T): void; }[] = []; + private handlers: {(data?: T): void;}[] = []; - public on(handler: { (data?: T): void }) { - if(!isFunction(handler)){ + public on(handler: {(data?: T): void}) { + if (!isFunction(handler)) { throw new Error("Handler is not a function"); } this.handlers.push(handler); } - public off(handler: { (data?: T): void }) { + public off(handler: {(data?: T): void}) { this.handlers = this.handlers.filter(h => h !== handler); } diff --git a/common/tsconfig.json b/common/tsconfig.json index 44782a1..30660b3 100644 --- a/common/tsconfig.json +++ b/common/tsconfig.json @@ -1,13 +1,15 @@ { "compilerOptions": { "target": "es5", - "sourceMap": true, "module": "commonjs", + "moduleResolution": "node", + "sourceMap": true, "emitDecoratorMetadata": true, - "experimentalDecorators": true - }, - "exclude": [ - "./../node_modules", - "./../typings" - ] -} \ No newline at end of file + "experimentalDecorators": true, + "lib": [ + "es2015", + "dom" + ], + "suppressImplicitAnyIndexErrors": true + } +} diff --git a/frontend/app/admin/admin.component.ts b/frontend/app/admin/admin.component.ts index 8612b93..170f725 100644 --- a/frontend/app/admin/admin.component.ts +++ b/frontend/app/admin/admin.component.ts @@ -1,26 +1,17 @@ -/// - import {Component, OnInit} from "@angular/core"; -import {AuthenticationService} from "../model/network/authentication.service.ts"; -import {Router} from "@angular/router-deprecated"; -import {FrameComponent} from "../frame/frame.component"; +import {AuthenticationService} from "../model/network/authentication.service"; +import {Router} from "@angular/router"; import {UserRoles} from "../../../common/entities/User"; -import {FORM_DIRECTIVES} from "@angular/common"; -import {StringifyRole} from "./../pipes/StringifyRolePipe"; import {Config} from "../config/Config"; -import {UserMangerSettingsComponent} from "../settings/usermanager/usermanager.settings.component"; - @Component({ selector: 'admin', templateUrl: 'app/admin/admin.component.html', - styleUrls: ['app/admin/admin.component.css'], - directives: [FrameComponent, FORM_DIRECTIVES, UserMangerSettingsComponent], - pipes: [StringifyRole] + styleUrls: ['app/admin/admin.component.css'] }) export class AdminComponent implements OnInit { - userManagementEnable:boolean = false; + userManagementEnable: boolean = false; - constructor(private _authService:AuthenticationService, private _router:Router) { + constructor(private _authService: AuthenticationService, private _router: Router) { this.userManagementEnable = Config.Client.authenticationRequired; } diff --git a/frontend/app/app.component.ts b/frontend/app/app.component.ts index f2a144e..8e36fe8 100644 --- a/frontend/app/app.component.ts +++ b/frontend/app/app.component.ts @@ -1,83 +1,29 @@ -/// - import {Component, OnInit} from "@angular/core"; -import {LoginComponent} from "./login/login.component"; -import {AuthenticationService} from "./model/network/authentication.service.ts"; -import {GalleryComponent} from "./gallery/gallery.component"; +import {AuthenticationService} from "./model/network/authentication.service"; import {User} from "../../common/entities/User"; -import {Router, RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from "@angular/router-deprecated"; -import {HTTP_PROVIDERS} from "@angular/http"; -import {UserService} from "./model/network/user.service.ts"; -import {GalleryService} from "./gallery/gallery.service"; -import {AdminComponent} from "./admin/admin.component"; -import {NetworkService} from "./model/network/network.service"; -import {ThumbnailLoaderService} from "./gallery/grid/thumnailLoader.service"; -import {GalleryCacheService} from "./gallery/cache.gallery.service"; -import {FullScreenService} from "./gallery/fullscreen.service"; - +import {Router} from "@angular/router"; @Component({ selector: 'pi-gallery2-app', template: ``, - directives: [ROUTER_DIRECTIVES], - providers: [ - HTTP_PROVIDERS, - ROUTER_PROVIDERS, - NetworkService, - UserService, - GalleryCacheService, - GalleryService, - AuthenticationService, - ThumbnailLoaderService, - FullScreenService] + }) -@RouteConfig([ - { - path: '/', - redirectTo: ["Login"] - }, - { - path: '/login', - name: 'Login', - component: LoginComponent, - useAsDefault: true - }, - { - path: '/admin', - name: 'Admin', - component: AdminComponent - }, - { - path: '/gallery', - redirectTo: ["Gallery", {directory: ""}] - }, - { - path: '/gallery/:directory', - name: 'Gallery', - component: GalleryComponent - }, - { - path: '/search/:searchText', - name: 'Search', - component: GalleryComponent - }, -]) export class AppComponent implements OnInit { - constructor(private _router:Router, private _authenticationService:AuthenticationService) { + constructor(private _router: Router, private _authenticationService: AuthenticationService) { } ngOnInit() { - this._authenticationService.OnUserChanged.on((user:User) => { + this._authenticationService.OnUserChanged.on((user: User) => { if (user != null) { - if (this._router.isRouteActive(this._router.generate(['Login']))) { + if (this._router.isActive('login', true)) { console.log("routing"); - this._router.navigate(["Gallery", {directory: ""}]); + this._router.navigate(["gallery", ""]); } } else { - if (!this._router.isRouteActive(this._router.generate(['Login']))) { + if (this._router.isActive('login', true)) { console.log("routing"); - this._router.navigate(["Login"]); + this._router.navigate(["login"]); } } diff --git a/frontend/app/app.module.ts b/frontend/app/app.module.ts new file mode 100644 index 0000000..6849b13 --- /dev/null +++ b/frontend/app/app.module.ts @@ -0,0 +1,65 @@ +import {NgModule} from "@angular/core"; +import {BrowserModule} from "@angular/platform-browser"; +import {FormsModule} from "@angular/forms"; +import {HttpModule} from "@angular/http"; +import {AppComponent} from "./app.component"; +import {appRoutes} from "./app.routing"; +import {UserService} from "./model/network/user.service"; +import {GalleryService} from "./gallery/gallery.service"; +import {NetworkService} from "./model/network/network.service"; +import {ThumbnailLoaderService} from "./gallery/grid/thumnailLoader.service"; +import {GalleryCacheService} from "./gallery/cache.gallery.service"; +import {FullScreenService} from "./gallery/fullscreen.service"; +import {AuthenticationService} from "./model/network/authentication.service"; +import {UserMangerSettingsComponent} from "./settings/usermanager/usermanager.settings.component"; +import {FrameComponent} from "./frame/frame.component"; +import {GalleryLightboxPhotoComponent} from "./gallery/lightbox/photo/photo.lightbox.gallery.component"; +import {GalleryPhotoLoadingComponent} from "./gallery/grid/photo/loading/loading.photo.grid.gallery.component"; +import {GalleryNavigatorComponent} from "./gallery/navigator/navigator.gallery.component"; +import {GallerySearchComponent} from "./gallery/search/search.gallery.component"; +import {GalleryLightboxComponent} from "./gallery/lightbox/lightbox.gallery.component"; +import {GalleryDirectoryComponent} from "./gallery/directory/directory.gallery.component"; +import {GalleryGridComponent} from "./gallery/grid/grid.gallery.component"; +import {GalleryPhotoComponent} from "./gallery/grid/photo/photo.grid.gallery.component"; +import {LoginComponent} from "./login/login.component"; +import {AdminComponent} from "./admin/admin.component"; +import {GalleryComponent} from "./gallery/gallery.component"; +import {StringifyRole} from "./pipes/StringifyRolePipe"; + +@NgModule({ + imports: [ + BrowserModule, + FormsModule, + HttpModule, + appRoutes + ], + declarations: [AppComponent, + LoginComponent, + AdminComponent, + GalleryComponent, + FrameComponent, + UserMangerSettingsComponent, + GalleryLightboxPhotoComponent, + GalleryPhotoLoadingComponent, + GalleryGridComponent, + GalleryDirectoryComponent, + GalleryLightboxComponent, + FrameComponent, + GallerySearchComponent, + GalleryNavigatorComponent, + GalleryPhotoComponent, + FrameComponent, + StringifyRole], + providers: [ + NetworkService, + UserService, + GalleryCacheService, + GalleryService, + AuthenticationService, + ThumbnailLoaderService, + FullScreenService], + + bootstrap: [AppComponent] +}) +export class AppModule { +} \ No newline at end of file diff --git a/frontend/app/app.routing.ts b/frontend/app/app.routing.ts new file mode 100644 index 0000000..45d6790 --- /dev/null +++ b/frontend/app/app.routing.ts @@ -0,0 +1,32 @@ +import {ModuleWithProviders} from "@angular/core"; +import {Routes, RouterModule} from "@angular/router"; +import {LoginComponent} from "./login/login.component"; +import {GalleryComponent} from "./gallery/gallery.component"; +import {AdminComponent} from "./admin/admin.component"; + +const ROUTES: Routes = [ + { + path: 'login', + component: LoginComponent + }, + { + path: 'admin', + component: AdminComponent + }, + { + path: 'gallery/:directory', + component: GalleryComponent + }, + { + path: 'gallery', + component: GalleryComponent + }, + { + path: 'search/:searchText', + component: GalleryComponent + }, + {path: '', redirectTo: '/login', pathMatch: 'full'} +]; + +export const appRoutes: ModuleWithProviders = RouterModule.forRoot(ROUTES); + diff --git a/frontend/app/config/Config.ts b/frontend/app/config/Config.ts index 9930701..f92d358 100644 --- a/frontend/app/config/Config.ts +++ b/frontend/app/config/Config.ts @@ -2,10 +2,10 @@ import {ConfigClass} from "../../../common/config/Config"; import {Utils} from "../../../common/Utils"; declare module ServerInject { - export var ConfigInject; + export let ConfigInject: ConfigClass; } -export var Config = new ConfigClass(); +export let Config = new ConfigClass(); if (typeof ServerInject !== "undefined" && typeof ServerInject.ConfigInject !== "undefined") { Utils.updateKeys(Config.Client, ServerInject.ConfigInject); diff --git a/frontend/app/frame/frame.component.html b/frontend/app/frame/frame.component.html index aa3fd21..e582e70 100644 --- a/frontend/app/frame/frame.component.html +++ b/frontend/app/frame/frame.component.html @@ -12,8 +12,8 @@ - Gallery - Admin + Gallery + Admin diff --git a/frontend/app/frame/frame.component.ts b/frontend/app/frame/frame.component.ts index a5305af..7a5fe58 100644 --- a/frontend/app/frame/frame.component.ts +++ b/frontend/app/frame/frame.component.ts @@ -1,7 +1,5 @@ -/// - import {Component, ViewEncapsulation} from "@angular/core"; -import {RouterLink} from "@angular/router-deprecated"; +import {RouterLink} from "@angular/router"; import {AuthenticationService} from "../model/network/authentication.service"; import {User} from "../../../common/entities/User"; import {Config} from "../config/Config"; @@ -9,7 +7,7 @@ import {Config} from "../config/Config"; @Component({ selector: 'app-frame', templateUrl: 'app/frame/frame.component.html', - directives: [RouterLink], + providers: [RouterLink], encapsulation: ViewEncapsulation.Emulated }) export class FrameComponent { diff --git a/frontend/app/gallery/cache.gallery.service.ts b/frontend/app/gallery/cache.gallery.service.ts index d39cb23..a0a1f27 100644 --- a/frontend/app/gallery/cache.gallery.service.ts +++ b/frontend/app/gallery/cache.gallery.service.ts @@ -1,5 +1,3 @@ -/// - import {Injectable} from "@angular/core"; import {Photo} from "../../../common/entities/Photo"; import {Directory} from "../../../common/entities/Directory"; @@ -10,20 +8,20 @@ import {Config} from "../config/Config"; export class GalleryCacheService { - public getDirectory(directoryName:string):Directory { + public getDirectory(directoryName: string): Directory { if (Config.Client.enableCache == false) { return null; } let value = localStorage.getItem(directoryName); if (value != null) { - let directory:Directory = JSON.parse(value); + let directory: Directory = JSON.parse(value); - directory.photos.forEach((photo:Photo) => { + directory.photos.forEach((photo: Photo) => { photo.metadata.creationDate = new Date(photo.metadata.creationDate); }); - - directory.photos.forEach((photo:Photo) => { + + directory.photos.forEach((photo: Photo) => { photo.directory = directory; }); @@ -32,14 +30,14 @@ export class GalleryCacheService { return null; } - public setDirectory(directory:Directory):void { + public setDirectory(directory: Directory): void { if (Config.Client.enableCache == false) { return; } - + localStorage.setItem(Utils.concatUrls(directory.path, directory.name), JSON.stringify(directory)); - directory.directories.forEach((dir:Directory) => { + directory.directories.forEach((dir: Directory) => { let name = Utils.concatUrls(dir.path, dir.name); if (localStorage.getItem(name) == null) { //don't override existing localStorage.setItem(Utils.concatUrls(dir.path, dir.name), JSON.stringify(dir)); @@ -52,7 +50,7 @@ export class GalleryCacheService { * Update photo state at cache too (Eg.: thumbnail rendered) * @param photo */ - public photoUpdated(photo:Photo):void { + public photoUpdated(photo: Photo): void { if (Config.Client.enableCache == false) { return; @@ -61,7 +59,7 @@ export class GalleryCacheService { let directoryName = Utils.concatUrls(photo.directory.path, photo.directory.name); let value = localStorage.getItem(directoryName); if (value != null) { - let directory:Directory = JSON.parse(value); + let directory: Directory = JSON.parse(value); directory.photos.forEach((p) => { if (p.name === photo.name) { //update data diff --git a/frontend/app/gallery/directory/directory.gallery.component.html b/frontend/app/gallery/directory/directory.gallery.component.html index 5e57179..fd7be79 100644 --- a/frontend/app/gallery/directory/directory.gallery.component.html +++ b/frontend/app/gallery/directory/directory.gallery.component.html @@ -1,4 +1,4 @@ - {{directory.name}} diff --git a/frontend/app/gallery/directory/directory.gallery.component.ts b/frontend/app/gallery/directory/directory.gallery.component.ts index b5defd1..32f1f09 100644 --- a/frontend/app/gallery/directory/directory.gallery.component.ts +++ b/frontend/app/gallery/directory/directory.gallery.component.ts @@ -1,14 +1,12 @@ -/// - import {Component, Input} from "@angular/core"; import {Directory} from "../../../../common/entities/Directory"; -import {RouterLink} from "@angular/router-deprecated"; +import {RouterLink} from "@angular/router"; import {Utils} from "../../../../common/Utils"; @Component({ selector: 'gallery-directory', templateUrl: 'app/gallery/directory/directory.gallery.component.html', - directives: [RouterLink], + providers: [RouterLink], }) export class GalleryDirectoryComponent { @Input() directory:Directory; diff --git a/frontend/app/gallery/fullscreen.service.ts b/frontend/app/gallery/fullscreen.service.ts index d84e495..ae45ced 100644 --- a/frontend/app/gallery/fullscreen.service.ts +++ b/frontend/app/gallery/fullscreen.service.ts @@ -1,16 +1,14 @@ -/// - import {Injectable} from "@angular/core"; @Injectable() export class FullScreenService { - public isFullScreenEnabled():boolean { + public isFullScreenEnabled(): boolean { return !!(document.fullscreenElement || document['mozFullScreenElement'] || document.webkitFullscreenElement); } - public showFullScreen(element:any) { + public showFullScreen(element: any) { if (this.isFullScreenEnabled()) { return; } diff --git a/frontend/app/gallery/gallery.component.html b/frontend/app/gallery/gallery.component.html index 4f4e5ff..bccf591 100644 --- a/frontend/app/gallery/gallery.component.html +++ b/frontend/app/gallery/gallery.component.html @@ -17,10 +17,10 @@ Searching for: - - - - + + + + {{_galleryService.content.searchResult.searchText}} diff --git a/frontend/app/gallery/gallery.component.ts b/frontend/app/gallery/gallery.component.ts index 5e87ce4..582b531 100644 --- a/frontend/app/gallery/gallery.component.ts +++ b/frontend/app/gallery/gallery.component.ts @@ -1,72 +1,65 @@ -/// - import {Component, OnInit, ViewChild} from "@angular/core"; -import {AuthenticationService} from "../model/network/authentication.service.ts"; -import {Router, RouteParams} from "@angular/router-deprecated"; +import {AuthenticationService} from "../model/network/authentication.service"; +import {Router, ActivatedRoute, Params} from "@angular/router"; import {GalleryService} from "./gallery.service"; -import {GalleryDirectoryComponent} from "./directory/directory.gallery.component"; import {GalleryGridComponent} from "./grid/grid.gallery.component"; -import {FrameComponent} from "../frame/frame.component"; -import {GalleryLightboxComponent} from "./lightbox/lightbox.gallery.component"; import {GallerySearchComponent} from "./search/search.gallery.component"; import {Config} from "../config/Config"; import {SearchTypes} from "../../../common/entities/AutoCompleteItem"; -import {GalleryNavigatorComponent} from "./navigator/navigator.gallery.component"; @Component({ selector: 'gallery', templateUrl: 'app/gallery/gallery.component.html', - styleUrls: ['app/gallery/gallery.component.css'], - directives: [GalleryGridComponent, - GalleryDirectoryComponent, - GalleryLightboxComponent, - FrameComponent, - GallerySearchComponent, - GalleryNavigatorComponent] + styleUrls: ['app/gallery/gallery.component.css'] }) export class GalleryComponent implements OnInit { - @ViewChild(GallerySearchComponent) search:GallerySearchComponent; - @ViewChild(GalleryGridComponent) grid:GalleryGridComponent; + @ViewChild(GallerySearchComponent) search: GallerySearchComponent; + @ViewChild(GalleryGridComponent) grid: GalleryGridComponent; - public showSearchBar:boolean = true; + public showSearchBar: boolean = true; - constructor(private _galleryService:GalleryService, - private _params:RouteParams, - private _authService:AuthenticationService, - private _router:Router) { + constructor(private _galleryService: GalleryService, + private _authService: AuthenticationService, + private _router: Router, + private _route: ActivatedRoute) { this.showSearchBar = Config.Client.Search.searchEnabled; } ngOnInit() { if (!this._authService.isAuthenticated()) { - this._router.navigate(['Login']); + this._router.navigate(['login']); return; } + this._route.params + .subscribe((params: Params) => { + let searchText = params['searchText']; + if (searchText && searchText != "") { + console.log("searching"); + let typeString = params['type']; - let searchText = this._params.get('searchText'); - if (searchText && searchText != "") { - console.log("searching"); - let typeString = this._params.get('type'); + if (typeString && typeString != "") { + console.log("with type"); + let type: SearchTypes = SearchTypes[typeString]; + this._galleryService.search(searchText, type); + return; + } - if (typeString && typeString != "") { - console.log("with type"); - let type:SearchTypes = SearchTypes[typeString]; - this._galleryService.search(searchText, type); - return; - } - - this._galleryService.search(searchText); - return; - } + this._galleryService.search(searchText); + return; + } - let directoryName = this._params.get('directory'); - directoryName = directoryName ? directoryName : ""; + let directoryName = params['directory']; + directoryName = directoryName ? directoryName : ""; + + this._galleryService.getDirectory(directoryName); + + }); + - this._galleryService.getDirectory(directoryName); } diff --git a/frontend/app/gallery/gallery.service.spec.ts b/frontend/app/gallery/gallery.service.spec.ts deleted file mode 100644 index 3f14c13..0000000 --- a/frontend/app/gallery/gallery.service.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -import {it, inject, addProviders} from "@angular/core/testing"; -import {BaseRequestOptions, Http} from "@angular/http"; -import {MockBackend} from "@angular/http/testing"; -import {provide} from "@angular/core"; -import "rxjs/Rx"; -import {NetworkService} from "../model/network/network.service"; -import {GalleryService} from "./gallery.service"; - - -describe('GalleryService', () => { - - beforeEach(() => { - addProviders([ - MockBackend, - BaseRequestOptions, - provide(Http, { - useFactory: (backend, options) => { - return new Http(backend, options); - }, deps: [MockBackend, BaseRequestOptions] - }), - NetworkService, - GalleryService - ]); - }); - - - - it('placeholder test', inject([], () => { - expect(true).toBe(true); - })); - -}); diff --git a/frontend/app/gallery/gallery.service.ts b/frontend/app/gallery/gallery.service.ts index fc371e4..a0c4d1e 100644 --- a/frontend/app/gallery/gallery.service.ts +++ b/frontend/app/gallery/gallery.service.ts @@ -1,7 +1,5 @@ -/// - import {Injectable} from "@angular/core"; -import {NetworkService} from "../model/network/network.service.ts"; +import {NetworkService} from "../model/network/network.service"; import {Message} from "../../../common/entities/Message"; import {ContentWrapper} from "../../../common/entities/ConentWrapper"; import {Photo} from "../../../common/entities/Photo"; @@ -20,7 +18,7 @@ export class GalleryService { this.content = new ContentWrapper(); } - lastRequest = { + lastRequest: {directory: any} = { directory: null }; public getDirectory(directoryName:string):Promise> { diff --git a/frontend/app/gallery/grid/grid.gallery.component.ts b/frontend/app/gallery/grid/grid.gallery.component.ts index 7eef5bc..280d09c 100644 --- a/frontend/app/gallery/grid/grid.gallery.component.ts +++ b/frontend/app/gallery/grid/grid.gallery.component.ts @@ -1,5 +1,3 @@ -/// - import { Component, Input, @@ -22,7 +20,6 @@ import {Config} from "../../config/Config"; selector: 'gallery-grid', templateUrl: 'app/gallery/grid/grid.gallery.component.html', styleUrls: ['app/gallery/grid/grid.gallery.component.css'], - directives: [GalleryPhotoComponent] }) export class GalleryGridComponent implements OnChanges,AfterViewInit { diff --git a/frontend/app/gallery/grid/photo/photo.grid.gallery.component.ts b/frontend/app/gallery/grid/photo/photo.grid.gallery.component.ts index 4ea6238..1be9c52 100644 --- a/frontend/app/gallery/grid/photo/photo.grid.gallery.component.ts +++ b/frontend/app/gallery/grid/photo/photo.grid.gallery.component.ts @@ -1,10 +1,8 @@ -/// - import {Component, Input, ElementRef, ViewChild, OnInit, AfterViewInit, OnDestroy} from "@angular/core"; import {IRenderable, Dimension} from "../../../model/IRenderable"; import {GridPhoto} from "../GridPhoto"; import {SearchTypes} from "../../../../../common/entities/AutoCompleteItem"; -import {RouterLink} from "@angular/router-deprecated"; +import {RouterLink} from "@angular/router"; import {Config} from "../../../config/Config"; import { ThumbnailLoaderService, @@ -12,19 +10,18 @@ import { ThumbnailLoadingListener, ThumbnailLoadingPriority } from "../thumnailLoader.service"; -import {GalleryPhotoLoadingComponent} from "./loading/loading.photo.grid.gallery.component"; @Component({ selector: 'gallery-grid-photo', templateUrl: 'app/gallery/grid/photo/photo.grid.gallery.component.html', styleUrls: ['app/gallery/grid/photo/photo.grid.gallery.component.css'], - directives: [RouterLink, GalleryPhotoLoadingComponent], + providers: [RouterLink], }) export class GalleryPhotoComponent implements IRenderable, OnInit, AfterViewInit, OnDestroy { - @Input() gridPhoto:GridPhoto; - @ViewChild("img") imageRef:ElementRef; - @ViewChild("info") infoDiv:ElementRef; - @ViewChild("photoContainer") container:ElementRef; + @Input() gridPhoto: GridPhoto; + @ViewChild("img") imageRef: ElementRef; + @ViewChild("info") infoDiv: ElementRef; + @ViewChild("photoContainer") container: ElementRef; image = { @@ -37,19 +34,19 @@ export class GalleryPhotoComponent implements IRenderable, OnInit, AfterViewInit show: true }; - thumbnailTask:ThumbnailTaskEntity = null; + thumbnailTask: ThumbnailTaskEntity = null; infoStyle = { height: 0, background: "rgba(0,0,0,0.0)" }; - SearchTypes:any = []; - searchEnabled:boolean = true; + SearchTypes: any = []; + searchEnabled: boolean = true; - wasInView:boolean = null; + wasInView: boolean = null; - constructor(private thumbnailService:ThumbnailLoaderService) { + constructor(private thumbnailService: ThumbnailLoaderService) { this.SearchTypes = SearchTypes; this.searchEnabled = Config.Client.Search.searchEnabled; @@ -74,17 +71,17 @@ export class GalleryPhotoComponent implements IRenderable, OnInit, AfterViewInit if (!this.gridPhoto.isThumbnailAvailable()) { setImmediate(() => { - let listener:ThumbnailLoadingListener = { - onStartedLoading: ()=> { //onLoadStarted + let listener: ThumbnailLoadingListener = { + onStartedLoading: () => { //onLoadStarted this.loading.animate = true; }, - onLoad: ()=> {//onLoaded + onLoad: () => {//onLoaded this.image.src = this.gridPhoto.getThumbnailPath(); this.image.show = true; this.loading.show = false; this.thumbnailTask = null; }, - onError: (error)=> {//onError + onError: (error) => {//onError this.thumbnailTask = null; //TODO: handle error //TODO: not an error if its from cache @@ -111,7 +108,7 @@ export class GalleryPhotoComponent implements IRenderable, OnInit, AfterViewInit } - isInView():boolean { + isInView(): boolean { return document.body.scrollTop < this.container.nativeElement.offsetTop + this.container.nativeElement.clientHeight && document.body.scrollTop + window.innerHeight > this.container.nativeElement.offsetTop; } @@ -139,7 +136,7 @@ export class GalleryPhotoComponent implements IRenderable, OnInit, AfterViewInit } } - getPositionText():string { + getPositionText(): string { if (!this.gridPhoto) { return "" } @@ -164,7 +161,7 @@ export class GalleryPhotoComponent implements IRenderable, OnInit, AfterViewInit this.loading.show = false; } - public getDimension():Dimension { + public getDimension(): Dimension { return new Dimension(this.imageRef.nativeElement.offsetTop, this.imageRef.nativeElement.offsetLeft, this.imageRef.nativeElement.width, diff --git a/frontend/app/gallery/grid/thumnailLoader.service.ts b/frontend/app/gallery/grid/thumnailLoader.service.ts index 07c0528..80464d8 100644 --- a/frontend/app/gallery/grid/thumnailLoader.service.ts +++ b/frontend/app/gallery/grid/thumnailLoader.service.ts @@ -1,5 +1,3 @@ -/// - import {Injectable} from "@angular/core"; import {GridPhoto} from "./GridPhoto"; import {Config} from "../../config/Config"; @@ -12,17 +10,17 @@ export enum ThumbnailLoadingPriority{ @Injectable() export class ThumbnailLoaderService { - que:Array = []; - runningRequests:number = 0; + que: Array = []; + runningRequests: number = 0; - constructor(private galleryChacheService:GalleryCacheService) { + constructor(private galleryChacheService: GalleryCacheService) { } removeTasks() { this.que = []; } - removeTask(taskEntry:ThumbnailTaskEntity) { + removeTask(taskEntry: ThumbnailTaskEntity) { for (let i = 0; i < this.que.length; i++) { let index = this.que[i].taskEntities.indexOf(taskEntry); @@ -38,9 +36,9 @@ export class ThumbnailLoaderService { } - loadImage(gridPhoto:GridPhoto, priority:ThumbnailLoadingPriority, listener:ThumbnailLoadingListener):ThumbnailTaskEntity { + loadImage(gridPhoto: GridPhoto, priority: ThumbnailLoadingPriority, listener: ThumbnailLoadingListener): ThumbnailTaskEntity { - let tmp:ThumbnailTask = null; + let tmp: ThumbnailTask = null; //is image already qued? for (let i = 0; i < this.que.length; i++) { if (this.que[i].gridPhoto.getThumbnailPath() == gridPhoto.getThumbnailPath()) { @@ -71,7 +69,7 @@ export class ThumbnailLoaderService { } - private getNextTask():ThumbnailTask { + private getNextTask(): ThumbnailTask { if (this.que.length === 0) { return null; } @@ -95,7 +93,7 @@ export class ThumbnailLoaderService { return this.que[0]; } - private taskReady(task:ThumbnailTask) { + private taskReady(task: ThumbnailTask) { let i = this.que.indexOf(task); if (i == -1) { if (task.taskEntities.length !== 0) { @@ -118,7 +116,7 @@ export class ThumbnailLoaderService { } this.runningRequests++; - task.taskEntities.forEach(te=>te.listener.onStartedLoading()); + task.taskEntities.forEach(te => te.listener.onStartedLoading()); task.inProgress = true; let curImg = new Image(); @@ -128,7 +126,7 @@ export class ThumbnailLoaderService { task.gridPhoto.thumbnailLoaded(); this.galleryChacheService.photoUpdated(task.gridPhoto.photo); - task.taskEntities.forEach(te=>te.listener.onLoad()); + task.taskEntities.forEach((te: ThumbnailTaskEntity) => te.listener.onLoad()); this.taskReady(task); this.runningRequests--; @@ -136,7 +134,7 @@ export class ThumbnailLoaderService { }; curImg.onerror = (error) => { - task.taskEntities.forEach(te=>te.listener.onError(error)); + task.taskEntities.forEach((te: ThumbnailTaskEntity) => te.listener.onError(error)); this.taskReady(task); this.runningRequests--; @@ -147,21 +145,21 @@ export class ThumbnailLoaderService { export interface ThumbnailLoadingListener { - onStartedLoading:()=>void; - onLoad:()=>void; - onError:(error)=>void; + onStartedLoading: () => void; + onLoad: () => void; + onError: (error: any) => void; } export interface ThumbnailTaskEntity { - priority:ThumbnailLoadingPriority; - listener:ThumbnailLoadingListener; + priority: ThumbnailLoadingPriority; + listener: ThumbnailLoadingListener; } interface ThumbnailTask { - gridPhoto:GridPhoto; - inProgress:boolean; - taskEntities:Array; + gridPhoto: GridPhoto; + inProgress: boolean; + taskEntities: Array; } diff --git a/frontend/app/gallery/lightbox/lightbox.gallery.component.ts b/frontend/app/gallery/lightbox/lightbox.gallery.component.ts index 9e54bdb..3c47344 100644 --- a/frontend/app/gallery/lightbox/lightbox.gallery.component.ts +++ b/frontend/app/gallery/lightbox/lightbox.gallery.component.ts @@ -1,36 +1,29 @@ -/// - import {Component, QueryList, Output, EventEmitter, HostListener, ElementRef, ViewChild} from "@angular/core"; import {Photo} from "../../../../common/entities/Photo"; -import {GalleryPhotoComponent} from "../grid/photo/photo.grid.gallery.component.ts"; -import {BrowserDomAdapter} from "@angular/platform-browser/src/browser/browser_adapter"; +import {GalleryPhotoComponent} from "../grid/photo/photo.grid.gallery.component"; import {Dimension} from "../../model/IRenderable"; -import {GalleryLightboxPhotoComponent} from "./photo/photo.lightbox.gallery.component"; import {FullScreenService} from "../fullscreen.service"; @Component({ selector: 'gallery-lightbox', styleUrls: ['app/gallery/lightbox/lightbox.gallery.component.css'], templateUrl: 'app/gallery/lightbox/lightbox.gallery.component.html', - directives: [GalleryLightboxPhotoComponent] }) export class GalleryLightboxComponent { @Output('onLastElement') onLastElement = new EventEmitter(); public navigation = {hasPrev: true, hasNext: true}; - public photoDimension:Dimension = new Dimension(0, 0, 0, 0); + public photoDimension: Dimension = new Dimension(0, 0, 0, 0); - private activePhoto:GalleryPhotoComponent; - public gridPhotoQL:QueryList; + private activePhoto: GalleryPhotoComponent; + public gridPhotoQL: QueryList; - private dom:BrowserDomAdapter; private visible = false; - @ViewChild("root") elementRef:ElementRef; + @ViewChild("root") elementRef: ElementRef; - constructor(private fullScreenService:FullScreenService) { - this.dom = new BrowserDomAdapter(); + constructor(private fullScreenService: FullScreenService) { } @@ -65,9 +58,9 @@ export class GalleryLightboxComponent { } - private showPhoto(photoComponent:GalleryPhotoComponent) { + private showPhoto(photoComponent: GalleryPhotoComponent) { this.activePhoto = null; - setImmediate(()=> { + setImmediate(() => { let pcList = this.gridPhotoQL.toArray(); let index = pcList.indexOf(photoComponent); @@ -82,7 +75,7 @@ export class GalleryLightboxComponent { }); } - public show(photo:Photo) { + public show(photo: Photo) { this.visible = true; let selectedPhoto = this.findPhotoComponent(photo); if (selectedPhoto === null) { @@ -91,7 +84,7 @@ export class GalleryLightboxComponent { this.showPhoto(selectedPhoto); - this.dom.setStyle(this.dom.query('body'), 'overflow', 'hidden'); + document.getElementsByTagName('body')[0].style.overflow = 'hidden'; } public hide() { @@ -104,14 +97,14 @@ export class GalleryLightboxComponent { this.setBodyScrollTop(to.top); } - this.dom.setStyle(this.dom.query('body'), 'overflow', 'auto'); + document.getElementsByTagName('body')[0].style.overflow = 'auto'; this.activePhoto = null; } - private findPhotoComponent(photo) { + private findPhotoComponent(photo: any) { let galleryPhotoComponents = this.gridPhotoQL.toArray(); for (let i = 0; i < galleryPhotoComponents.length; i++) { if (galleryPhotoComponents[i].gridPhoto.photo == photo) { @@ -122,8 +115,8 @@ export class GalleryLightboxComponent { } @HostListener('window:keydown', ['$event']) - onKeyPress(e) { - let event = window.event ? window.event : e; + onKeyPress(e: KeyboardEvent) { + let event: KeyboardEvent = window.event ? window.event : e; switch (event.keyCode) { case 37: this.prevImage(); @@ -134,11 +127,11 @@ export class GalleryLightboxComponent { } } - private getBodyScrollTop():number { + private getBodyScrollTop(): number { return window.scrollY; } - private setBodyScrollTop(value:number) { + private setBodyScrollTop(value: number) { window.scrollTo(window.scrollX, value); } @@ -151,7 +144,7 @@ export class GalleryLightboxComponent { } - private calcLightBoxPhotoDimension(photo:Photo):Dimension { + private calcLightBoxPhotoDimension(photo: Photo): Dimension { let width = 0; let height = 0; if (photo.metadata.size.height > photo.metadata.size.width) { diff --git a/frontend/app/gallery/navigator/navigator.gallery.component.html b/frontend/app/gallery/navigator/navigator.gallery.component.html index c4931b1..341fc9a 100644 --- a/frontend/app/gallery/navigator/navigator.gallery.component.html +++ b/frontend/app/gallery/navigator/navigator.gallery.component.html @@ -1,6 +1,6 @@ - {{path.name}} + {{path.name}} {{path.name}} diff --git a/frontend/app/gallery/navigator/navigator.gallery.component.ts b/frontend/app/gallery/navigator/navigator.gallery.component.ts index f84eda3..61bc317 100644 --- a/frontend/app/gallery/navigator/navigator.gallery.component.ts +++ b/frontend/app/gallery/navigator/navigator.gallery.component.ts @@ -1,18 +1,16 @@ -/// - import {Component, Input, OnChanges} from "@angular/core"; import {Directory} from "../../../../common/entities/Directory"; -import {RouterLink} from "@angular/router-deprecated"; +import {RouterLink} from "@angular/router"; @Component({ selector: 'gallery-navbar', templateUrl: 'app/gallery/navigator/navigator.gallery.component.html', - directives: [RouterLink], + providers: [RouterLink], }) export class GalleryNavigatorComponent implements OnChanges { - @Input() directory:Directory; + @Input() directory: Directory; - routes:Array = []; + routes: Array = []; constructor() { } @@ -22,7 +20,7 @@ export class GalleryNavigatorComponent implements OnChanges { this.getPath(); } - getPath() { + getPath(): any { if (!this.directory) { return []; } @@ -41,7 +39,7 @@ export class GalleryNavigatorComponent implements OnChanges { } - let arr = []; + let arr: any = []; //create root link if (dirs.length == 0) { @@ -52,7 +50,7 @@ export class GalleryNavigatorComponent implements OnChanges { } //create rest navigation - dirs.forEach((name, index)=> { + dirs.forEach((name, index) => { let route = dirs.slice(0, dirs.indexOf(name) + 1).join("/"); if (dirs.length - 1 == index) { arr.push({name: name, route: null}); diff --git a/frontend/app/gallery/search/autocomplete.service.spec.ts b/frontend/app/gallery/search/autocomplete.service.spec.ts deleted file mode 100644 index 37cb9f8..0000000 --- a/frontend/app/gallery/search/autocomplete.service.spec.ts +++ /dev/null @@ -1,30 +0,0 @@ -import {it, inject, beforeEachProviders} from "@angular/core/testing"; -import {BaseRequestOptions, Http} from "@angular/http"; -import {MockBackend} from "@angular/http/testing"; -import {provide} from "@angular/core"; -import "rxjs/Rx"; -import {AutoCompleteService} from "./autocomplete.service"; -import {NetworkService} from "../../model/network/network.service"; - - -describe('AutoCompleteService', () => { - - - beforeEachProviders(() => [ - MockBackend, - BaseRequestOptions, - provide(Http, { - useFactory: (backend, options) => { - return new Http(backend, options); - }, deps: [MockBackend, BaseRequestOptions] - }), - NetworkService, - AutoCompleteService - ]); - - - it('placeholder test', inject([], () => { - expect(true).toBe(true); - })); - -}); diff --git a/frontend/app/gallery/search/search.gallery.component.html b/frontend/app/gallery/search/search.gallery.component.html index a34899c..00e3234 100644 --- a/frontend/app/gallery/search/search.gallery.component.html +++ b/frontend/app/gallery/search/search.gallery.component.html @@ -2,7 +2,7 @@ @@ -11,10 +11,10 @@ - - - - + + + + {{item.preText}}{{item.highLightText}}{{item.postText}} diff --git a/frontend/app/gallery/search/search.gallery.component.ts b/frontend/app/gallery/search/search.gallery.component.ts index e99e228..5d6cee2 100644 --- a/frontend/app/gallery/search/search.gallery.component.ts +++ b/frontend/app/gallery/search/search.gallery.component.ts @@ -1,38 +1,41 @@ -/// - import {Component} from "@angular/core"; import {AutoCompleteService} from "./autocomplete.service"; import {AutoCompleteItem, SearchTypes} from "../../../../common/entities/AutoCompleteItem"; -import {RouteParams, RouterLink} from "@angular/router-deprecated"; +import {RouterLink, ActivatedRoute, Params} from "@angular/router"; import {Message} from "../../../../common/entities/Message"; import {GalleryService} from "../gallery.service"; -import {FORM_DIRECTIVES} from "@angular/common"; import {Config} from "../../config/Config"; @Component({ selector: 'gallery-search', templateUrl: 'app/gallery/search/search.gallery.component.html', styleUrls: ['app/gallery/search/search.gallery.component.css'], - providers: [AutoCompleteService], - directives: [FORM_DIRECTIVES, RouterLink] + providers: [AutoCompleteService, RouterLink] }) export class GallerySearchComponent { - autoCompleteItems:Array = []; - private searchText:string = ""; + autoCompleteItems: Array = []; + private searchText: string = ""; - SearchTypes:any = []; + SearchTypes: any = []; - constructor(private _autoCompleteService:AutoCompleteService, private _galleryService:GalleryService, private _params:RouteParams) { + constructor(private _autoCompleteService: AutoCompleteService, + private _galleryService: GalleryService, + private _route: ActivatedRoute) { this.SearchTypes = SearchTypes; - let searchText = this._params.get('searchText'); - if (searchText && searchText != "") { - this.searchText = searchText; - } + + this._route.params + .subscribe((params: Params) => { + let searchText = params['searchText']; + if (searchText && searchText != "") { + this.searchText = searchText; + } + + }); } - onSearchChange(event:KeyboardEvent) { + onSearchChange(event: KeyboardEvent) { let searchText = (event.target).value; @@ -51,26 +54,26 @@ export class GallerySearchComponent { } } - public search(item:AutoCompleteItem) { + public search(item: AutoCompleteItem) { console.log("clicked"); this.searchText = item.text; this.onSearch(); } - mouseOverAutoComplete:boolean = false; + mouseOverAutoComplete: boolean = false; - public setMouseOverAutoComplete(value) { + public setMouseOverAutoComplete(value: boolean) { this.mouseOverAutoComplete = value; } - - public onFocusLost(event) { + + public onFocusLost() { if (this.mouseOverAutoComplete == false) { this.autoCompleteItems = []; } } - public onFocus(event) { + public onFocus() { this.autocomplete(this.searchText); } @@ -78,12 +81,12 @@ export class GallerySearchComponent { this.autoCompleteItems = []; } - private autocomplete(searchText:string) { + private autocomplete(searchText: string) { if (!Config.Client.Search.autocompleteEnabled) { return } if (searchText.trim().length > 0) { - this._autoCompleteService.autoComplete(searchText).then((message:Message>) => { + this._autoCompleteService.autoComplete(searchText).then((message: Message>) => { if (message.error) { //TODO: implement console.error(message.error); @@ -96,27 +99,27 @@ export class GallerySearchComponent { } } - private showSuggestions(suggestions:Array, searchText:string) { + private showSuggestions(suggestions: Array, searchText: string) { this.emptyAutoComplete(); - suggestions.forEach((item:AutoCompleteItem)=> { + suggestions.forEach((item: AutoCompleteItem) => { let renderItem = new AutoCompleteRenderItem(item.text, searchText, item.type); this.autoCompleteItems.push(renderItem); }); } - public setSearchText(searchText:string) { + public setSearchText(searchText: string) { this.searchText = searchText; } } class AutoCompleteRenderItem { - public preText:string = ""; - public highLightText:string = ""; - public postText:string = ""; - public type:SearchTypes; + public preText: string = ""; + public highLightText: string = ""; + public postText: string = ""; + public type: SearchTypes; - constructor(public text:string, searchText:string, type:SearchTypes) { + constructor(public text: string, searchText: string, type: SearchTypes) { let preIndex = text.toLowerCase().indexOf(searchText.toLowerCase()); if (preIndex > -1) { this.preText = text.substring(0, preIndex); diff --git a/frontend/app/login/login.component.html b/frontend/app/login/login.component.html index 4ce1e4f..10bfffb 100644 --- a/frontend/app/login/login.component.html +++ b/frontend/app/login/login.component.html @@ -5,10 +5,10 @@ {{loginError}} - - + + Sign in diff --git a/frontend/app/login/login.component.ts b/frontend/app/login/login.component.ts index d6fef4e..e9e3382 100644 --- a/frontend/app/login/login.component.ts +++ b/frontend/app/login/login.component.ts @@ -1,10 +1,7 @@ -/// - import {Component, OnInit} from "@angular/core"; import {LoginCredential} from "../../../common/entities/LoginCredential"; -import {AuthenticationService} from "../model/network/authentication.service.ts"; -import {Router} from "@angular/router-deprecated"; -import {FORM_DIRECTIVES} from "@angular/common"; +import {AuthenticationService} from "../model/network/authentication.service"; +import {Router} from "@angular/router"; import {Message} from "../../../common/entities/Message"; import {User} from "../../../common/entities/User"; import {ErrorCodes} from "../../../common/entities/Error"; @@ -13,25 +10,24 @@ import {ErrorCodes} from "../../../common/entities/Error"; selector: 'login', templateUrl: 'app/login/login.component.html', styleUrls: ['app/login/login.component.css'], - directives: [FORM_DIRECTIVES] }) export class LoginComponent implements OnInit { - loginCredential:LoginCredential; - loginError = null; + loginCredential: LoginCredential; + loginError: any = null; - constructor(private _authService:AuthenticationService, private _router:Router) { + constructor(private _authService: AuthenticationService, private _router: Router) { this.loginCredential = new LoginCredential(); } ngOnInit() { if (this._authService.isAuthenticated()) { - this._router.navigate(['Gallery', {directory: "/"}]); + this._router.navigate(['gallery', "/"]); } } onLogin() { this.loginError = null; - this._authService.login(this.loginCredential).then((message:Message) => { + this._authService.login(this.loginCredential).then((message: Message) => { if (message.error) { if (message.error.code === ErrorCodes.CREDENTIAL_NOT_FOUND) { this.loginError = "Wrong username or password"; diff --git a/frontend/app/model/network/autehentication.service.spec.ts b/frontend/app/model/network/autehentication.service.spec.ts index d340990..3eebffe 100644 --- a/frontend/app/model/network/autehentication.service.spec.ts +++ b/frontend/app/model/network/autehentication.service.spec.ts @@ -1,8 +1,5 @@ -/// - -import {it, inject, beforeEachProviders} from "@angular/core/testing"; -import {provide} from "@angular/core"; -import {UserService} from "./user.service.ts"; +import {inject, TestBed} from "@angular/core/testing"; +import {UserService} from "./user.service"; import {User} from "../../../../common/entities/User"; import {Message} from "../../../../common/entities/Message"; import "rxjs/Rx"; @@ -10,16 +7,19 @@ import {LoginCredential} from "../../../../common/entities/LoginCredential"; import {AuthenticationService} from "./authentication.service"; class MockUserService { - public login(credential:LoginCredential) { + public login(credential: LoginCredential) { return Promise.resolve(new Message(null, new User("testUserName"))) } } describe('AuthenticationService', () => { - beforeEachProviders(() => [ - provide(UserService, {useClass: MockUserService}), - AuthenticationService - ]); + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + {provide: UserService, useClass: MockUserService}, + AuthenticationService] + }); + }); it('should call User service login', inject([AuthenticationService, UserService], (authService, userService) => { diff --git a/frontend/app/model/network/authentication.service.ts b/frontend/app/model/network/authentication.service.ts index 7caf1e7..66880e0 100644 --- a/frontend/app/model/network/authentication.service.ts +++ b/frontend/app/model/network/authentication.service.ts @@ -1,26 +1,24 @@ -/// - import {Injectable} from "@angular/core"; import {User, UserRoles} from "../../../../common/entities/User"; import {Event} from "../../../../common/event/Event"; -import {UserService} from "./user.service.ts"; +import {UserService} from "./user.service"; import {LoginCredential} from "../../../../common/entities/LoginCredential"; import {Message} from "../../../../common/entities/Message"; -import {Cookie} from "ng2-cookies/ng2-cookies"; +import {Cookie} from "ng2-cookies"; import {ErrorCodes} from "../../../../common/entities/Error"; import {Config} from "../../config/Config"; declare module ServerInject { - export var user; + export let user: User; } @Injectable() export class AuthenticationService { - private _user:User = null; - public OnUserChanged:Event; + private _user: User = null; + public OnUserChanged: Event; - constructor(private _userService:UserService) { + constructor(private _userService: UserService) { this.OnUserChanged = new Event(); //picking up session.. @@ -29,12 +27,14 @@ export class AuthenticationService { this.setUser(ServerInject.user); } this.getSessionUser(); + } else { + this.OnUserChanged.trigger(this._user); } } private getSessionUser() { - this._userService.getSessionUser().then((message:Message) => { + this._userService.getSessionUser().then((message: Message) => { if (message.error) { console.log(message.error); } else { @@ -44,15 +44,15 @@ export class AuthenticationService { }); } - private setUser(user:User) { + private setUser(user: User) { this._user = user; this.OnUserChanged.trigger(this._user); } - public login(credential:LoginCredential) { - return this._userService.login(credential).then((message:Message) => { + public login(credential: LoginCredential) { + return this._userService.login(credential).then((message: Message) => { if (message.error) { - console.log(ErrorCodes[message.error.code] + ", message: " + message.error.message); + console.log(ErrorCodes[message.error.code] + ", message: ", message.error.message); } else { this.setUser(message.result); } @@ -61,11 +61,11 @@ export class AuthenticationService { } - public isAuthenticated():boolean { + public isAuthenticated(): boolean { if (Config.Client.authenticationRequired === false) { return true; } - return (this._user && this._user != null) ? true : false; + return !!(this._user && this._user != null); } public getUser() { diff --git a/frontend/app/model/network/network.service.spec.ts b/frontend/app/model/network/network.service.spec.ts index 3e75061..c06e8d4 100644 --- a/frontend/app/model/network/network.service.spec.ts +++ b/frontend/app/model/network/network.service.spec.ts @@ -1,32 +1,35 @@ -/// - -import {it, inject, beforeEachProviders, beforeEach, afterEach} from "@angular/core/testing"; +import {inject, TestBed} from "@angular/core/testing"; import {BaseRequestOptions, Http, Response, ResponseOptions} from "@angular/http"; import {MockBackend, MockConnection} from "@angular/http/testing"; -import {provide} from "@angular/core"; import "rxjs/Rx"; import {NetworkService} from "./network.service"; import {Message} from "../../../../common/entities/Message"; describe('NetworkService Success tests', () => { - let connection:MockConnection = null; + let connection: MockConnection = null; let testUrl = "/test/url"; let testData = {data: "testData"}; let testResponse = "testResponse"; let testResponseMessage = new Message(null, testResponse); - beforeEachProviders(() => [ - MockBackend, - BaseRequestOptions, - provide(Http, { - useFactory: (backend, options) => { - return new Http(backend, options); - }, deps: [MockBackend, BaseRequestOptions] - }), - NetworkService - ]); + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + MockBackend, + BaseRequestOptions, + { + provide: Http, useFactory: (backend, options) => { + return new Http(backend, options); + }, deps: [MockBackend, BaseRequestOptions] + }, + NetworkService + ] + }); + }); + beforeEach(inject([MockBackend], (backend) => { @@ -48,7 +51,7 @@ describe('NetworkService Success tests', () => { it('should call GET', inject([NetworkService], (networkService) => { - networkService.getJson(testUrl).then((res:Message) => { + networkService.getJson(testUrl).then((res: Message) => { expect(res.result).toBe(testResponse); }); @@ -56,13 +59,13 @@ describe('NetworkService Success tests', () => { it('should call POST', inject([NetworkService, MockBackend], (networkService) => { - networkService.postJson(testUrl, testData).then((res:Message) => { + networkService.postJson(testUrl, testData).then((res: Message) => { expect(res.result).toBe(testResponse); }); expect(connection.request.text()).toBe(JSON.stringify(testData)); - networkService.postJson(testUrl).then((res:Message) => { + networkService.postJson(testUrl).then((res: Message) => { expect(res.result).toBe(testResponse); }); expect(connection.request.text()).toBe(JSON.stringify({})); @@ -70,14 +73,14 @@ describe('NetworkService Success tests', () => { it('should call PUT', inject([NetworkService, MockBackend], (networkService) => { - networkService.putJson(testUrl, testData).then((res:Message) => { + networkService.putJson(testUrl, testData).then((res: Message) => { expect(res.result).toBe(testResponse); }); expect(connection.request.text()).toBe(JSON.stringify(testData)); - networkService.putJson(testUrl).then((res:Message) => { + networkService.putJson(testUrl).then((res: Message) => { expect(res.result).toBe(testResponse); }); expect(connection.request.text()).toBe(JSON.stringify({})); @@ -86,7 +89,7 @@ describe('NetworkService Success tests', () => { it('should call DELETE', inject([NetworkService, MockBackend], (networkService) => { - networkService.deleteJson(testUrl).then((res:Message) => { + networkService.deleteJson(testUrl).then((res: Message) => { expect(res.result).toBe(testResponse); }); })); @@ -94,22 +97,26 @@ describe('NetworkService Success tests', () => { describe('NetworkService Fail tests', () => { - let connection:MockConnection = null; + let connection: MockConnection = null; let testUrl = "/test/url"; let testData = {data: "testData"}; let testError = "testError"; - beforeEachProviders(() => [ - MockBackend, - BaseRequestOptions, - provide(Http, { - useFactory: (backend, options) => { - return new Http(backend, options); - }, deps: [MockBackend, BaseRequestOptions] - }), - NetworkService - ]); + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + MockBackend, + BaseRequestOptions, + { + provide: Http, useFactory: (backend, options) => { + return new Http(backend, options); + }, deps: [MockBackend, BaseRequestOptions] + }, + NetworkService + ] + }); + }); beforeEach(inject([MockBackend], (backend) => { @@ -127,7 +134,7 @@ describe('NetworkService Fail tests', () => { it('should call GET with error', inject([NetworkService], (networkService) => { - networkService.getJson(testUrl).then((res:Message) => { + networkService.getJson(testUrl).then((res: Message) => { expect(res).toBe(null); }).catch((err) => { expect(err).toBe(testError); @@ -137,7 +144,7 @@ describe('NetworkService Fail tests', () => { it('should call POST with error', inject([NetworkService, MockBackend], (networkService) => { - networkService.postJson(testUrl, testData).then((res:Message) => { + networkService.postJson(testUrl, testData).then((res: Message) => { expect(res).toBe(null); }).catch((err) => { expect(err).toBe(testError); @@ -147,7 +154,7 @@ describe('NetworkService Fail tests', () => { it('should call PUT with error', inject([NetworkService, MockBackend], (networkService) => { - networkService.putJson(testUrl, testData).then((res:Message) => { + networkService.putJson(testUrl, testData).then((res: Message) => { expect(res).toBe(null); }).catch((err) => { expect(err).toBe(testError); @@ -159,7 +166,7 @@ describe('NetworkService Fail tests', () => { it('should call DELETE with error', inject([NetworkService, MockBackend], (networkService) => { - networkService.deleteJson(testUrl).then((res:Message) => { + networkService.deleteJson(testUrl).then((res: Message) => { expect(res).toBe(null); }).catch((err) => { expect(err).toBe(testError); diff --git a/frontend/app/model/network/network.service.ts b/frontend/app/model/network/network.service.ts index 396276f..1ebdc28 100644 --- a/frontend/app/model/network/network.service.ts +++ b/frontend/app/model/network/network.service.ts @@ -1,5 +1,3 @@ -/// - import {Injectable} from "@angular/core"; import {Http, Headers, RequestOptions} from "@angular/http"; import {Message} from "../../../../common/entities/Message"; @@ -19,7 +17,7 @@ export class NetworkService { let options = new RequestOptions({headers: headers}); if (method == "get" || method == "delete") { - return this._http[method](this._baseUrl + url, options) + return this._http[method](this._baseUrl + url, options) .toPromise() .then(res => > res.json()) .catch(NetworkService.handleError); @@ -27,7 +25,7 @@ export class NetworkService { return this._http[method](this._baseUrl + url, body, options) .toPromise() - .then(res => > res.json()) + .then((res: any) => > res.json()) .catch(NetworkService.handleError); } diff --git a/frontend/app/model/network/user.service.spec.ts b/frontend/app/model/network/user.service.spec.ts index b53d5e4..5ab5a62 100644 --- a/frontend/app/model/network/user.service.spec.ts +++ b/frontend/app/model/network/user.service.spec.ts @@ -1,9 +1,6 @@ -/// - -import {it, inject, beforeEachProviders} from "@angular/core/testing"; +import {inject, TestBed} from "@angular/core/testing"; import {BaseRequestOptions, Http} from "@angular/http"; import {MockBackend} from "@angular/http/testing"; -import {provide} from "@angular/core"; import "rxjs/Rx"; import {NetworkService} from "./network.service"; import {UserService} from "./user.service"; @@ -12,34 +9,36 @@ import {LoginCredential} from "../../../../common/entities/LoginCredential"; describe('UserService', () => { - - beforeEachProviders(() => [ - MockBackend, - BaseRequestOptions, - provide(Http, { - useFactory: (backend, options) => { - return new Http(backend, options); - }, deps: [MockBackend, BaseRequestOptions] - }), - NetworkService, - UserService - ]); + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + MockBackend, + BaseRequestOptions, + { + provide: Http, useFactory: (backend, options) => { + return new Http(backend, options); + }, deps: [MockBackend, BaseRequestOptions] + }, + NetworkService, + UserService] + }); - it('should call postJson at login', inject([UserService, NetworkService], (userService, networkService) => { - spyOn(networkService, "postJson"); - let credential = new LoginCredential("name", "pass"); - userService.login(credential); - expect(networkService.postJson).toHaveBeenCalled(); - expect(networkService.postJson.calls.argsFor(0)).toEqual(["/user/login", {"loginCredential": credential}]); - })); + it('should call postJson at login', inject([UserService, NetworkService], (userService, networkService) => { + spyOn(networkService, "postJson"); + let credential = new LoginCredential("name", "pass"); + userService.login(credential); + expect(networkService.postJson).toHaveBeenCalled(); + expect(networkService.postJson.calls.argsFor(0)).toEqual(["/user/login", {"loginCredential": credential}]); + })); - it('should call getJson at getSessionUser', inject([UserService, NetworkService], (userService, networkService) => { - spyOn(networkService, "getJson"); - userService.getSessionUser(); - expect(networkService.getJson).toHaveBeenCalled(); - expect(networkService.getJson.calls.argsFor(0)).toEqual(["/user/login"]); - })); + it('should call getJson at getSessionUser', inject([UserService, NetworkService], (userService, networkService) => { + spyOn(networkService, "getJson"); + userService.getSessionUser(); + expect(networkService.getJson).toHaveBeenCalled(); + expect(networkService.getJson.calls.argsFor(0)).toEqual(["/user/login"]); + })); -}); + }); +}); \ No newline at end of file diff --git a/frontend/app/model/network/user.service.ts b/frontend/app/model/network/user.service.ts index 69c12c6..ed03e36 100644 --- a/frontend/app/model/network/user.service.ts +++ b/frontend/app/model/network/user.service.ts @@ -1,8 +1,6 @@ -/// - import {Injectable} from "@angular/core"; import {LoginCredential} from "../../../../common/entities/LoginCredential"; -import {NetworkService} from "./network.service.ts"; +import {NetworkService} from "./network.service"; import {User} from "../../../../common/entities/User"; import {Message} from "../../../../common/entities/Message"; @@ -10,19 +8,19 @@ import {Message} from "../../../../common/entities/Message"; export class UserService { - constructor(private _networkService:NetworkService) { + constructor(private _networkService: NetworkService) { } - public logout():Promise> { + public logout(): Promise> { console.log("call logout"); return this._networkService.postJson("/user/logout"); } - public login(credential:LoginCredential):Promise> { + public login(credential: LoginCredential): Promise> { return this._networkService.postJson("/user/login", {"loginCredential": credential}); } - public getSessionUser():Promise> { + public getSessionUser(): Promise> { return this._networkService.getJson("/user/login"); } diff --git a/frontend/app/settings/usermanager/usermanager.settings.component.html b/frontend/app/settings/usermanager/usermanager.settings.component.html index 39fc4b7..4c8e78d 100644 --- a/frontend/app/settings/usermanager/usermanager.settings.component.html +++ b/frontend/app/settings/usermanager/usermanager.settings.component.html @@ -52,10 +52,10 @@ + [(ngModel)]="newUser.name" name="name" required> - + [(ngModel)]="newUser.password" name="password" required> + {{repository.value}} diff --git a/frontend/app/settings/usermanager/usermanager.settings.component.ts b/frontend/app/settings/usermanager/usermanager.settings.component.ts index 6b4b7da..24436a5 100644 --- a/frontend/app/settings/usermanager/usermanager.settings.component.ts +++ b/frontend/app/settings/usermanager/usermanager.settings.component.ts @@ -1,31 +1,24 @@ -/// - import {Component, OnInit} from "@angular/core"; -import {AuthenticationService} from "../../model/network/authentication.service.ts"; -import {Router} from "@angular/router-deprecated"; -import {FrameComponent} from "../../frame/frame.component"; +import {AuthenticationService} from "../../model/network/authentication.service"; +import {Router} from "@angular/router"; import {User, UserRoles} from "../../../../common/entities/User"; -import {FORM_DIRECTIVES} from "@angular/common"; import {Utils} from "../../../../common/Utils"; import {Message} from "../../../../common/entities/Message"; -import {StringifyRole} from "./../../pipes/StringifyRolePipe"; import {UserManagerSettingsService} from "./usermanager.settings.service"; @Component({ selector: 'settings-usermanager', templateUrl: 'app/settings/usermanager/usermanager.settings.component.html', styleUrls: ['app/settings/usermanager/usermanager.settings.component.css'], - directives: [FrameComponent, FORM_DIRECTIVES], providers: [UserManagerSettingsService], - pipes: [StringifyRole] }) export class UserMangerSettingsComponent implements OnInit { private newUser = new User(); - private userRoles:Array = []; - private users:Array = []; + private userRoles: Array = []; + private users: Array = []; - constructor(private _authService:AuthenticationService, private _router:Router, private _userSettings:UserManagerSettingsService) { + constructor(private _authService: AuthenticationService, private _router: Router, private _userSettings: UserManagerSettingsService) { } ngOnInit() { @@ -38,13 +31,13 @@ export class UserMangerSettingsComponent implements OnInit { } private getUsersList() { - this._userSettings.getUsers().then((result:Message>) => { + this._userSettings.getUsers().then((result: Message>) => { this.users = result.result; }); } - canModifyUser(user:User):boolean { + canModifyUser(user: User): boolean { let currentUser = this._authService.getUser(); if (!currentUser) { return false; @@ -64,13 +57,13 @@ export class UserMangerSettingsComponent implements OnInit { }); } - updateRole(user:User) { + updateRole(user: User) { this._userSettings.updateRole(user).then(() => { this.getUsersList(); }); } - deleteUser(user:User) { + deleteUser(user: User) { this._userSettings.deleteUser(user).then(() => { this.getUsersList(); }); diff --git a/frontend/app/settings/usermanager/usermanager.settings.service.spec.ts b/frontend/app/settings/usermanager/usermanager.settings.service.spec.ts deleted file mode 100644 index 13fe0d2..0000000 --- a/frontend/app/settings/usermanager/usermanager.settings.service.spec.ts +++ /dev/null @@ -1,30 +0,0 @@ -import {it, inject, beforeEachProviders} from "@angular/core/testing"; -import {BaseRequestOptions, Http} from "@angular/http"; -import {MockBackend} from "@angular/http/testing"; -import {provide} from "@angular/core"; -import "rxjs/Rx"; -import {NetworkService} from "../../model/network/network.service"; -import {UserManagerSettingsService} from "./usermanager.settings.service"; - - -describe('AdminService', () => { - - - beforeEachProviders(() => [ - MockBackend, - BaseRequestOptions, - provide(Http, { - useFactory: (backend, options) => { - return new Http(backend, options); - }, deps: [MockBackend, BaseRequestOptions] - }), - NetworkService, - UserManagerSettingsService - ]); - - - it('placeholder test', inject([], () => { - expect(true).toBe(true); - })); - -}); diff --git a/frontend/browser.d.ts b/frontend/browser.d.ts index f523079..df8a3e6 100644 --- a/frontend/browser.d.ts +++ b/frontend/browser.d.ts @@ -1,9 +1,6 @@ -/// -/// -/// +/// /// /// /// -/// /// diff --git a/frontend/index.ejs b/frontend/index.ejs index 86b3ca0..60f62a8 100644 --- a/frontend/index.ejs +++ b/frontend/index.ejs @@ -9,26 +9,31 @@ + + + + + + + + + + + + + Loading... - - - - - - -