improving types

This commit is contained in:
Patrik J. Braun 2018-11-28 23:49:33 +01:00
parent 987007b7c4
commit 62655eb47f
53 changed files with 262 additions and 214 deletions

View File

@ -13,7 +13,6 @@ import {ProjectPath} from '../ProjectPath';
import {PrivateConfigClass} from '../../common/config/private/PrivateConfigClass'; import {PrivateConfigClass} from '../../common/config/private/PrivateConfigClass';
import {IndexingDTO} from '../../common/entities/settings/IndexingDTO'; import {IndexingDTO} from '../../common/entities/settings/IndexingDTO';
const LOG_TAG = '[AdminMWs]'; const LOG_TAG = '[AdminMWs]';
export class AdminMWs { export class AdminMWs {
@ -347,7 +346,7 @@ export class AdminMWs {
} }
} }
public static async resetIndexes(req: Request, res: Response, next: NextFunction) { public static async resetIndexes(req: Express.Request, res: Response, next: NextFunction) {
try { try {
await ObjectManagerRepository.getInstance().IndexingManager.reset(); await ObjectManagerRepository.getInstance().IndexingManager.reset();
req.resultPipe = 'ok'; req.resultPipe = 'ok';

View File

@ -1,18 +1,28 @@
declare module Express { import {LoginCredential} from '../../../common/entities/LoginCredential';
export interface Request { import {UserEntity} from '../../model/sql/enitites/UserEntity';
resultPipe?: any;
body?: {
loginCredential
};
}
export interface Response {
tpl?: any;
}
export interface Session {
user?;
rememberMe?: boolean; declare global {
namespace Express {
interface Request {
resultPipe?: any;
body?: {
loginCredential: LoginCredential
};
locale?: string;
}
interface Response {
tpl?: any;
}
interface Session {
user?: UserEntity;
rememberMe?: boolean;
}
} }
} }

View File

@ -1,10 +0,0 @@
declare module 'jimp' {
function read(fileName);
const RESIZE_NEAREST_NEIGHBOR;
const RESIZE_BILINEAR;
const RESIZE_BICUBIC;
const RESIZE_HERMITE;
const RESIZE_BEZIER;
const AUTO: any;
}

View File

@ -1,4 +1,3 @@
///<reference path="../customtypings/jimp.d.ts"/>
import * as path from 'path'; import * as path from 'path';
import * as crypto from 'crypto'; import * as crypto from 'crypto';
import * as fs from 'fs'; import * as fs from 'fs';

View File

@ -1,4 +1,4 @@
let bcrypt; let bcrypt: any;
try { try {
bcrypt = require('bcrypt'); bcrypt = require('bcrypt');
} catch (err) { } catch (err) {
@ -6,12 +6,12 @@ try {
} }
export class PasswordHelper { export class PasswordHelper {
public static cryptPassword(password) { public static cryptPassword(password: string) {
const salt = bcrypt.genSaltSync(9); const salt = bcrypt.genSaltSync(9);
return bcrypt.hashSync(password, salt); return bcrypt.hashSync(password, salt);
} }
public static comparePassword(password, encryptedPassword) { public static comparePassword(password: string, encryptedPassword: string) {
return bcrypt.compareSync(password, encryptedPassword); return bcrypt.compareSync(password, encryptedPassword);
} }
} }

View File

@ -31,11 +31,11 @@ export class ConfigDiagnostics {
try { try {
if (videoConfig.enabled === true) { if (videoConfig.enabled === true) {
const ffmpeg = FFmpegFactory.get(); const ffmpeg = FFmpegFactory.get();
ffmpeg().getAvailableCodecs((err) => { ffmpeg().getAvailableCodecs((err: Error) => {
if (err) { if (err) {
return reject(new Error('Error accessing ffmpeg, cant find executable: ' + err.toString())); return reject(new Error('Error accessing ffmpeg, cant find executable: ' + err.toString()));
} }
ffmpeg(__dirname + '/blank.jpg').ffprobe((err2) => { ffmpeg(__dirname + '/blank.jpg').ffprobe((err2: Error) => {
if (err2) { if (err2) {
return reject(new Error('Error accessing ffmpeg-probe, cant find executable: ' + err2.toString())); return reject(new Error('Error accessing ffmpeg-probe, cant find executable: ' + err2.toString()));
} }
@ -60,7 +60,7 @@ export class ConfigDiagnostics {
case ThumbnailProcessingLib.gm: case ThumbnailProcessingLib.gm:
const gm = require('gm'); const gm = require('gm');
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
gm(ProjectPath.FrontendFolder + '/assets/icon.png').size((err, value) => { gm(ProjectPath.FrontendFolder + '/assets/icon.png').size((err: Error) => {
if (err) { if (err) {
return reject(err.toString()); return reject(err.toString());
} }

View File

@ -1,5 +1,5 @@
import {DirectoryDTO} from '../../../common/entities/DirectoryDTO'; import {DirectoryDTO} from '../../../common/entities/DirectoryDTO';
import {IGalleryManager} from '../interfaces/IGalleryManager'; import {IGalleryManager, RandomQuery} from '../interfaces/IGalleryManager';
import * as path from 'path'; import * as path from 'path';
import * as fs from 'fs'; import * as fs from 'fs';
import {DiskManager} from '../DiskManger'; import {DiskManager} from '../DiskManger';
@ -24,7 +24,7 @@ export class GalleryManager implements IGalleryManager {
return DiskManager.scanDirectory(relativeDirectoryName); return DiskManager.scanDirectory(relativeDirectoryName);
} }
getRandomPhoto(RandomQuery): Promise<PhotoDTO> { getRandomPhoto(queryFilter: RandomQuery): Promise<PhotoDTO> {
throw new Error('Random media is not supported without database'); throw new Error('Random media is not supported without database');
} }
} }

View File

@ -9,7 +9,7 @@ import {PasswordHelper} from '../PasswordHelper';
export class UserManager implements IUserManager { export class UserManager implements IUserManager {
private db: { users?: UserDTO[], idCounter?: number } = {}; private db: { users?: UserDTO[], idCounter?: number } = {};
private readonly dbPath; private readonly dbPath: string;
generateId(): string { generateId(): string {
function s4() { function s4() {

View File

@ -121,7 +121,7 @@ export class GalleryManager implements IGalleryManager, ISQLGalleryManager {
} }
public indexDirectory(relativeDirectoryName): Promise<DirectoryDTO> { public indexDirectory(relativeDirectoryName: string): Promise<DirectoryDTO> {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
try { try {
const scannedDirectory = await DiskManager.scanDirectory(relativeDirectoryName); const scannedDirectory = await DiskManager.scanDirectory(relativeDirectoryName);
@ -217,22 +217,22 @@ export class GalleryManager implements IGalleryManager, ISQLGalleryManager {
if (!!currentDir) {// Updated parent dir (if it was in the DB previously) if (!!currentDir) {// Updated parent dir (if it was in the DB previously)
currentDir.lastModified = scannedDirectory.lastModified; currentDir.lastModified = scannedDirectory.lastModified;
currentDir.lastScanned = scannedDirectory.lastScanned; currentDir.lastScanned = scannedDirectory.lastScanned;
// const media: MediaEntity[] = currentDir.media; // const media: MediaEntity[] = currentDir.media;
// delete currentDir.media; // delete currentDir.media;
currentDir = await directoryRepository.save(currentDir); currentDir = await directoryRepository.save(currentDir);
/*if (media) { /*if (media) {
media.forEach(m => m.directory = currentDir); media.forEach(m => m.directory = currentDir);
currentDir.media = await this.saveMedia(connection, media); currentDir.media = await this.saveMedia(connection, media);
}*/ }*/
} else { } else {
// const media = scannedDirectory.media; // const media = scannedDirectory.media;
// delete scannedDirectory.media; // delete scannedDirectory.media;
(<DirectoryEntity>scannedDirectory).lastScanned = scannedDirectory.lastScanned; (<DirectoryEntity>scannedDirectory).lastScanned = scannedDirectory.lastScanned;
currentDir = await directoryRepository.save(<DirectoryEntity>scannedDirectory); currentDir = await directoryRepository.save(<DirectoryEntity>scannedDirectory);
/* if (media) { /* if (media) {
media.forEach(m => m.directory = currentDir); media.forEach(m => m.directory = currentDir);
currentDir.media = await this.saveMedia(connection, media); currentDir.media = await this.saveMedia(connection, media);
}*/ }*/
} }
// save subdirectories // save subdirectories
@ -296,7 +296,7 @@ export class GalleryManager implements IGalleryManager, ISQLGalleryManager {
scannedDirectory.media[i].directory = scannedDirectory; scannedDirectory.media[i].directory = scannedDirectory;
media.directory = currentDir; media.directory = currentDir;
mediaToSave.push(media); mediaToSave.push(media);
}else if (!Utils.equalsFilter(media.metadata, scannedDirectory.media[i].metadata)) { } else if (!Utils.equalsFilter(media.metadata, scannedDirectory.media[i].metadata)) {
media.metadata = scannedDirectory.media[i].metadata; media.metadata = scannedDirectory.media[i].metadata;
mediaToSave.push(media); mediaToSave.push(media);
} }
@ -330,7 +330,7 @@ export class GalleryManager implements IGalleryManager, ISQLGalleryManager {
} }
} }
await fileRepository.save(metaFilesToSave); await fileRepository.save(metaFilesToSave);
// await fileRepository.remove(indexedMetaFiles); // await fileRepository.remove(indexedMetaFiles);
} }
protected async saveMedia(connection: Connection, mediaList: MediaDTO[]): Promise<MediaEntity[]> { protected async saveMedia(connection: Connection, mediaList: MediaDTO[]): Promise<MediaEntity[]> {

View File

@ -1,11 +1,11 @@
import {DirectoryDTO} from '../../../common/entities/DirectoryDTO'; import {DirectoryDTO} from '../../../common/entities/DirectoryDTO';
import {IGalleryManager} from '../interfaces/IGalleryManager'; import {IGalleryManager} from '../interfaces/IGalleryManager';
export interface ISQLGalleryManager extends IGalleryManager{ export interface ISQLGalleryManager extends IGalleryManager {
listDirectory(relativeDirectoryName: string, listDirectory(relativeDirectoryName: string,
knownLastModified?: number, knownLastModified?: number,
knownLastScanned?: number): Promise<DirectoryDTO>; knownLastScanned?: number): Promise<DirectoryDTO>;
indexDirectory(relativeDirectoryName): Promise<DirectoryDTO>; indexDirectory(relativeDirectoryName: string): Promise<DirectoryDTO>;
} }

View File

@ -16,7 +16,7 @@ const LOG_TAG = '[IndexingManager]';
export class IndexingManager implements IIndexingManager { export class IndexingManager implements IIndexingManager {
directoriesToIndex: string[] = []; directoriesToIndex: string[] = [];
indexingProgress = null; indexingProgress: { current: string, left: number, indexed: number } = null;
enabled = false; enabled = false;
private indexNewDirectory = async (createThumbnails: boolean = false) => { private indexNewDirectory = async (createThumbnails: boolean = false) => {
if (this.directoriesToIndex.length === 0) { if (this.directoriesToIndex.length === 0) {

View File

@ -192,7 +192,7 @@ export class SearchManager implements ISearchManager {
} }
private encapsulateAutoComplete(values: string[], type: SearchTypes): Array<AutoCompleteItem> { private encapsulateAutoComplete(values: string[], type: SearchTypes): Array<AutoCompleteItem> {
const res = []; const res: AutoCompleteItem[] = [];
values.forEach((value) => { values.forEach((value) => {
res.push(new AutoCompleteItem(value, type)); res.push(new AutoCompleteItem(value, type));
}); });

View File

@ -9,7 +9,7 @@ export class ThumbnailWorker {
private static imageRenderer: (input: RendererInput) => Promise<void> = null; private static imageRenderer: (input: RendererInput) => Promise<void> = null;
private static videoRenderer: (input: RendererInput) => Promise<void> = null; private static videoRenderer: (input: RendererInput) => Promise<void> = null;
private static rendererType = null; private static rendererType: ThumbnailProcessingLib = null;
public static render(input: RendererInput, renderer: ThumbnailProcessingLib): Promise<void> { public static render(input: RendererInput, renderer: ThumbnailProcessingLib): Promise<void> {
if (input.type === ThumbnailSourceType.Image) { if (input.type === ThumbnailSourceType.Image) {
@ -62,7 +62,7 @@ export class VideoRendererFactory {
if (!!err || data === null) { if (!!err || data === null) {
return reject(err.toString()); return reject(err.toString());
} }
/// console.log(data); /// console.log(data);
let width = null; let width = null;
let height = null; let height = null;
for (let i = 0; i < data.streams.length; i++) { for (let i = 0; i < data.streams.length; i++) {
@ -151,7 +151,7 @@ export class ImageRendererFactory {
image.quality(60); // set JPEG quality image.quality(60); // set JPEG quality
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
image.write(input.thPath, (err) => { // save image.write(input.thPath, (err: Error | null) => { // save
if (err) { if (err) {
return reject(err); return reject(err);
} }

View File

@ -2,16 +2,17 @@ import {AuthenticationMWs} from '../middlewares/user/AuthenticationMWs';
import {UserRoles} from '../../common/entities/UserDTO'; import {UserRoles} from '../../common/entities/UserDTO';
import {RenderingMWs} from '../middlewares/RenderingMWs'; import {RenderingMWs} from '../middlewares/RenderingMWs';
import {AdminMWs} from '../middlewares/AdminMWs'; import {AdminMWs} from '../middlewares/AdminMWs';
import {Express} from 'express';
export class AdminRouter { export class AdminRouter {
public static route(app: any) { public static route(app: Express) {
this.addIndexGallery(app); this.addIndexGallery(app);
this.addSettings(app); this.addSettings(app);
} }
private static addIndexGallery(app) { private static addIndexGallery(app: Express) {
app.get('/api/admin/indexes/job/progress', app.get('/api/admin/indexes/job/progress',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
AuthenticationMWs.authorise(UserRoles.Admin), AuthenticationMWs.authorise(UserRoles.Admin),
@ -38,7 +39,7 @@ export class AdminRouter {
); );
} }
private static addSettings(app) { private static addSettings(app: Express) {
app.get('/api/settings', app.get('/api/settings',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
AuthenticationMWs.authorise(UserRoles.Admin), AuthenticationMWs.authorise(UserRoles.Admin),

View File

@ -3,21 +3,22 @@ import {ErrorCodes, ErrorDTO} from '../../common/entities/Error';
import {Logger} from '../Logger'; import {Logger} from '../Logger';
import Request = Express.Request; import Request = Express.Request;
import Response = Express.Response; import Response = Express.Response;
import {Express} from 'express';
export class ErrorRouter { export class ErrorRouter {
public static route(app: any) { public static route(app: Express) {
this.addApiErrorHandler(app); this.addApiErrorHandler(app);
this.addGenericHandler(app); this.addGenericHandler(app);
} }
private static addApiErrorHandler(app) { private static addApiErrorHandler(app: Express) {
app.use('/api/*', app.use('/api/*',
RenderingMWs.renderError RenderingMWs.renderError
); );
} }
private static addGenericHandler(app) { private static addGenericHandler(app: Express) {
app.use((err: any, req: Request, res: Response, next: Function) => { app.use((err: any, req: Request, res: Response, next: Function) => {
// Flush out the stack to the console // Flush out the stack to the console
Logger.error('Unexpected error:'); Logger.error('Unexpected error:');

View File

@ -1,4 +1,5 @@
import {AuthenticationMWs} from '../middlewares/user/AuthenticationMWs'; import {AuthenticationMWs} from '../middlewares/user/AuthenticationMWs';
import {Express} from 'express';
import {GalleryMWs} from '../middlewares/GalleryMWs'; import {GalleryMWs} from '../middlewares/GalleryMWs';
import {RenderingMWs} from '../middlewares/RenderingMWs'; import {RenderingMWs} from '../middlewares/RenderingMWs';
import {ThumbnailGeneratorMWs} from '../middlewares/thumbnail/ThumbnailGeneratorMWs'; import {ThumbnailGeneratorMWs} from '../middlewares/thumbnail/ThumbnailGeneratorMWs';
@ -6,7 +7,7 @@ import {UserRoles} from '../../common/entities/UserDTO';
import {ThumbnailSourceType} from '../model/threading/ThumbnailWorker'; import {ThumbnailSourceType} from '../model/threading/ThumbnailWorker';
export class GalleryRouter { export class GalleryRouter {
public static route(app: any) { public static route(app: Express) {
this.addGetImageIcon(app); this.addGetImageIcon(app);
this.addGetImageThumbnail(app); this.addGetImageThumbnail(app);
@ -22,7 +23,7 @@ export class GalleryRouter {
this.addAutoComplete(app); this.addAutoComplete(app);
} }
private static addDirectoryList(app) { private static addDirectoryList(app: Express) {
app.get(['/api/gallery/content/:directory(*)', '/api/gallery/', '/api/gallery//'], app.get(['/api/gallery/content/:directory(*)', '/api/gallery/', '/api/gallery//'],
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
AuthenticationMWs.authoriseDirectory, AuthenticationMWs.authoriseDirectory,
@ -34,7 +35,7 @@ export class GalleryRouter {
} }
private static addGetImage(app) { private static addGetImage(app: Express) {
app.get(['/api/gallery/content/:filePath(*\.(jpg|bmp|png|gif|jpeg))'], app.get(['/api/gallery/content/:filePath(*\.(jpg|bmp|png|gif|jpeg))'],
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
// TODO: authorize path // TODO: authorize path
@ -43,7 +44,7 @@ export class GalleryRouter {
); );
} }
private static addGetVideo(app) { private static addGetVideo(app: Express) {
app.get(['/api/gallery/content/:filePath(*\.(mp4|ogg|ogv|webm))'], app.get(['/api/gallery/content/:filePath(*\.(mp4|ogg|ogv|webm))'],
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
// TODO: authorize path // TODO: authorize path
@ -52,7 +53,7 @@ export class GalleryRouter {
); );
} }
private static addGetMetaFile(app) { private static addGetMetaFile(app: Express) {
app.get(['/api/gallery/content/:filePath(*\.(gpx))'], app.get(['/api/gallery/content/:filePath(*\.(gpx))'],
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
// TODO: authorize path // TODO: authorize path
@ -61,7 +62,7 @@ export class GalleryRouter {
); );
} }
private static addRandom(app) { private static addRandom(app: Express) {
app.get(['/api/gallery/random'], app.get(['/api/gallery/random'],
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
AuthenticationMWs.authorise(UserRoles.Guest), AuthenticationMWs.authorise(UserRoles.Guest),
@ -72,7 +73,7 @@ export class GalleryRouter {
); );
} }
private static addGetImageThumbnail(app) { private static addGetImageThumbnail(app: Express) {
app.get('/api/gallery/content/:filePath(*\.(jpg|bmp|png|gif|jpeg))/thumbnail/:size?', app.get('/api/gallery/content/:filePath(*\.(jpg|bmp|png|gif|jpeg))/thumbnail/:size?',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
// TODO: authorize path // TODO: authorize path
@ -82,7 +83,7 @@ export class GalleryRouter {
); );
} }
private static addGetVideoThumbnail(app) { private static addGetVideoThumbnail(app: Express) {
app.get('/api/gallery/content/:filePath(*\.(mp4|ogg|ogv|webm))/thumbnail/:size?', app.get('/api/gallery/content/:filePath(*\.(mp4|ogg|ogv|webm))/thumbnail/:size?',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
// TODO: authorize path // TODO: authorize path
@ -92,7 +93,7 @@ export class GalleryRouter {
); );
} }
private static addGetImageIcon(app) { private static addGetImageIcon(app: Express) {
app.get('/api/gallery/content/:filePath(*\.(jpg|bmp|png|gif|jpeg))/icon', app.get('/api/gallery/content/:filePath(*\.(jpg|bmp|png|gif|jpeg))/icon',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
// TODO: authorize path // TODO: authorize path
@ -102,7 +103,7 @@ export class GalleryRouter {
); );
} }
private static addSearch(app) { private static addSearch(app: Express) {
app.get('/api/search/:text', app.get('/api/search/:text',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
AuthenticationMWs.authorise(UserRoles.Guest), AuthenticationMWs.authorise(UserRoles.Guest),
@ -113,7 +114,7 @@ export class GalleryRouter {
); );
} }
private static addInstantSearch(app) { private static addInstantSearch(app: Express) {
app.get('/api/instant-search/:text', app.get('/api/instant-search/:text',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
AuthenticationMWs.authorise(UserRoles.Guest), AuthenticationMWs.authorise(UserRoles.Guest),
@ -124,7 +125,7 @@ export class GalleryRouter {
); );
} }
private static addAutoComplete(app) { private static addAutoComplete(app: Express) {
app.get('/api/autocomplete/:text', app.get('/api/autocomplete/:text',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
AuthenticationMWs.authorise(UserRoles.Guest), AuthenticationMWs.authorise(UserRoles.Guest),

View File

@ -1,46 +1,55 @@
import {NextFunction, Request, Response} from 'express'; import {Express, NextFunction, Request, Response} from 'express';
import {Logger} from '../Logger'; import {Logger} from '../Logger';
declare global {
namespace Express {
interface Request {
_startTime?: number;
logged?: boolean;
}
}
}
/** /**
* Adds logging to express * Adds logging to express
*/ */
export class LoggerRouter { export class LoggerRouter {
public static route(app: any) { public static route(app: Express) {
app.get('/api*', (req: Request, res: Response, next: NextFunction) => { app.get('/api*', (req: Request, res: Response, next: NextFunction) => {
req['_startTime'] = Date.now(); req._startTime = Date.now();
req['logged'] = true; req.logged = true;
const end = res.end; const end = res.end;
res.end = (a?: any, b?: any, c?: any) => { res.end = (a?: any, b?: any, c?: any) => {
res.end = end; res.end = end;
res.end(a, b, c); res.end(a, b, c);
Logger.verbose(req.method, req.url, res.statusCode, (Date.now() - req['_startTime']) + 'ms'); Logger.verbose(req.method, req.url, res.statusCode, (Date.now() - req._startTime) + 'ms');
}; };
return next(); return next();
}); });
app.get('/node_modules*', (req: Request, res: Response, next: NextFunction) => { app.get('/node_modules*', (req: Request, res: Response, next: NextFunction) => {
req['_startTime'] = Date.now(); req._startTime = Date.now();
req['logged'] = true; req.logged = true;
const end = res.end; const end = res.end;
res.end = (a?: any, b?: any, c?: any) => { res.end = (a?: any, b?: any, c?: any) => {
res.end = end; res.end = end;
res.end(a, b, c); res.end(a, b, c);
Logger.silly(req.method, req.url, res.statusCode, (Date.now() - req['_startTime']) + 'ms'); Logger.silly(req.method, req.url, res.statusCode, (Date.now() - req._startTime) + 'ms');
}; };
return next(); return next();
}); });
app.use((req: Request, res: Response, next: NextFunction) => { app.use((req: Request, res: Response, next: NextFunction) => {
if (req['logged'] === true) { if (req.logged === true) {
return next(); return next();
} }
req['_startTime'] = Date.now(); req._startTime = Date.now();
const end = res.end; const end = res.end;
res.end = (a?: any, b?: any, c?: any) => { res.end = (a?: any, b?: any, c?: any) => {
res.end = end; res.end = end;
res.end(a, b, c); res.end(a, b, c);
Logger.debug(req.method, req.url, res.statusCode, (Date.now() - req['_startTime']) + 'ms'); Logger.debug(req.method, req.url, res.statusCode, (Date.now() - req._startTime) + 'ms');
}; };
return next(); return next();
}); });

View File

@ -2,14 +2,15 @@ import {UserRoles} from '../../common/entities/UserDTO';
import {AuthenticationMWs} from '../middlewares/user/AuthenticationMWs'; import {AuthenticationMWs} from '../middlewares/user/AuthenticationMWs';
import {RenderingMWs} from '../middlewares/RenderingMWs'; import {RenderingMWs} from '../middlewares/RenderingMWs';
import {NotificationMWs} from '../middlewares/NotificationMWs'; import {NotificationMWs} from '../middlewares/NotificationMWs';
import {Express} from 'express';
export class NotificationRouter { export class NotificationRouter {
public static route(app: any) { public static route(app: Express) {
this.addGetNotifications(app); this.addGetNotifications(app);
} }
private static addGetNotifications(app) { private static addGetNotifications(app: Express) {
app.get('/api/notifications', app.get('/api/notifications',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
AuthenticationMWs.authorise(UserRoles.Guest), AuthenticationMWs.authorise(UserRoles.Guest),

View File

@ -1,4 +1,4 @@
import {NextFunction, Request, Response} from 'express'; import {Express, NextFunction, Request, Response} from 'express';
import * as path from 'path'; import * as path from 'path';
import * as fs from 'fs'; import * as fs from 'fs';
import * as ejs from 'ejs'; import * as ejs from 'ejs';
@ -7,13 +7,26 @@ import {Config} from '../../common/config/private/Config';
import {ProjectPath} from '../ProjectPath'; import {ProjectPath} from '../ProjectPath';
import {AuthenticationMWs} from '../middlewares/user/AuthenticationMWs'; import {AuthenticationMWs} from '../middlewares/user/AuthenticationMWs';
import {CookieNames} from '../../common/CookieNames'; import {CookieNames} from '../../common/CookieNames';
import {ErrorDTO} from '../../common/entities/Error'; import {ErrorCodes, ErrorDTO} from '../../common/entities/Error';
declare global {
namespace Express {
interface Request {
locale?: string;
localePath?: string;
tpl?: any;
}
interface Response {
tpl?: any;
}
}
}
export class PublicRouter { export class PublicRouter {
public static route(app) { public static route(app: Express) {
const setLocale = (req: Request, res: Response, next: Function) => { const setLocale = (req: Request, res: Response, next: Function) => {
let localePath = ''; let localePath = '';
let selectedLocale = req['locale']; let selectedLocale = req['locale'];
@ -34,7 +47,7 @@ export class PublicRouter {
ejs.renderFile(path.resolve(ProjectPath.FrontendFolder, req['localePath'], 'index.html'), ejs.renderFile(path.resolve(ProjectPath.FrontendFolder, req['localePath'], 'index.html'),
res.tpl, (err, str) => { res.tpl, (err, str) => {
if (err) { if (err) {
return next(new ErrorDTO(err)); return next(new ErrorDTO(ErrorCodes.GENERAL_ERROR, err.message));
} }
res.send(str); res.send(str);
}); });

View File

@ -1,11 +1,12 @@
import {UserMWs} from '../middlewares/user/UserMWs'; import {UserMWs} from '../middlewares/user/UserMWs';
import {Express} from 'express';
import {UserRoles} from '../../common/entities/UserDTO'; import {UserRoles} from '../../common/entities/UserDTO';
import {AuthenticationMWs} from '../middlewares/user/AuthenticationMWs'; import {AuthenticationMWs} from '../middlewares/user/AuthenticationMWs';
import {UserRequestConstrainsMWs} from '../middlewares/user/UserRequestConstrainsMWs'; import {UserRequestConstrainsMWs} from '../middlewares/user/UserRequestConstrainsMWs';
import {RenderingMWs} from '../middlewares/RenderingMWs'; import {RenderingMWs} from '../middlewares/RenderingMWs';
export class UserRouter { export class UserRouter {
public static route(app) { public static route(app: Express) {
this.addLogin(app); this.addLogin(app);
this.addLogout(app); this.addLogout(app);
this.addGetSessionUser(app); this.addGetSessionUser(app);
@ -18,7 +19,7 @@ export class UserRouter {
this.addChangeRole(app); this.addChangeRole(app);
} }
private static addLogin(app) { private static addLogin(app: Express) {
app.post('/api/user/login', app.post('/api/user/login',
AuthenticationMWs.inverseAuthenticate, AuthenticationMWs.inverseAuthenticate,
AuthenticationMWs.login, AuthenticationMWs.login,
@ -26,7 +27,7 @@ export class UserRouter {
); );
} }
private static addLogout(app) { private static addLogout(app: Express) {
app.post('/api/user/logout', app.post('/api/user/logout',
AuthenticationMWs.logout, AuthenticationMWs.logout,
RenderingMWs.renderOK RenderingMWs.renderOK
@ -34,7 +35,7 @@ export class UserRouter {
} }
private static addGetSessionUser(app) { private static addGetSessionUser(app: Express) {
app.get('/api/user/login', app.get('/api/user/login',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
RenderingMWs.renderSessionUser RenderingMWs.renderSessionUser
@ -42,7 +43,7 @@ export class UserRouter {
} }
private static addChangePassword(app) { private static addChangePassword(app: Express) {
app.post('/api/user/:id/password', app.post('/api/user/:id/password',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
UserRequestConstrainsMWs.forceSelfRequest, UserRequestConstrainsMWs.forceSelfRequest,
@ -52,7 +53,7 @@ export class UserRouter {
} }
private static addCreateUser(app) { private static addCreateUser(app: Express) {
app.put('/api/user', app.put('/api/user',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
AuthenticationMWs.authorise(UserRoles.Admin), AuthenticationMWs.authorise(UserRoles.Admin),
@ -61,7 +62,7 @@ export class UserRouter {
); );
} }
private static addDeleteUser(app) { private static addDeleteUser(app: Express) {
app.delete('/api/user/:id', app.delete('/api/user/:id',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
AuthenticationMWs.authorise(UserRoles.Admin), AuthenticationMWs.authorise(UserRoles.Admin),
@ -72,7 +73,7 @@ export class UserRouter {
} }
private static addListUsers(app) { private static addListUsers(app: Express) {
app.get('/api/user/list', app.get('/api/user/list',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
AuthenticationMWs.authorise(UserRoles.Admin), AuthenticationMWs.authorise(UserRoles.Admin),
@ -81,7 +82,7 @@ export class UserRouter {
); );
} }
private static addChangeRole(app) { private static addChangeRole(app: Express) {
app.post('/api/user/:id/role', app.post('/api/user/:id/role',
AuthenticationMWs.authenticate, AuthenticationMWs.authenticate,
AuthenticationMWs.authorise(UserRoles.Admin), AuthenticationMWs.authorise(UserRoles.Admin),

View File

@ -114,9 +114,9 @@ export class Server {
this.app.use(locale(Config.Client.languages, 'en')); this.app.use(locale(Config.Client.languages, 'en'));
if (Config.Server.database.type !== DatabaseType.memory) { if (Config.Server.database.type !== DatabaseType.memory) {
await ObjectManagerRepository.InitSQLManagers(); await ObjectManagerRepository.InitSQLManagers();
} else { } else {
await ObjectManagerRepository.InitMemoryManagers(); await ObjectManagerRepository.InitMemoryManagers();
} }
PublicRouter.route(this.app); PublicRouter.route(this.app);

View File

@ -1,6 +1,7 @@
{ {
"compileOnSave": true, "compileOnSave": true,
"compilerOptions": { "compilerOptions": {
"noImplicitAny": true,
"module": "commonjs", "module": "commonjs",
"skipLibCheck": true, "skipLibCheck": true,
"sourceMap": false, "sourceMap": false,

View File

@ -5,7 +5,7 @@ export class Utils {
return JSON.parse(JSON.stringify(object)); return JSON.parse(JSON.stringify(object));
} }
static zeroPrefix(value, length: number) { static zeroPrefix(value: string | number, length: number) {
const ret = '00000' + value; const ret = '00000' + value;
return ret.substr(ret.length - length); return ret.substr(ret.length - length);
} }
@ -34,7 +34,6 @@ export class Utils {
} }
/** /**
* *
* @param from * @param from

View File

@ -3,7 +3,7 @@ import {WebConfigLoader} from 'typeconfig/src/WebConfigLoader';
declare module ServerInject { declare module ServerInject {
export const ConfigInject; export const ConfigInject: PublicConfigClass;
} }
export let Config = new PublicConfigClass(); export let Config = new PublicConfigClass();

View File

@ -7,16 +7,18 @@ import {Title} from '@angular/platform-browser';
import {NotificationService} from './model/notification.service'; import {NotificationService} from './model/notification.service';
import {ShareService} from './gallery/share.service'; import {ShareService} from './gallery/share.service';
import 'hammerjs'; import 'hammerjs';
import {Subscription} from 'rxjs';
import {QueryService} from './model/query.service'; import {QueryService} from './model/query.service';
@Component({ @Component({
selector: 'app-pi-gallery2', selector: 'app-pi-gallery2',
template: `<router-outlet></router-outlet>`, template: `
<router-outlet></router-outlet>`,
}) })
export class AppComponent implements OnInit, OnDestroy { export class AppComponent implements OnInit, OnDestroy {
private subscription = null; private subscription: Subscription = null;
constructor(private _router: Router, constructor(private _router: Router,
private _authenticationService: AuthenticationService, private _authenticationService: AuthenticationService,

View File

@ -109,7 +109,7 @@ export class CustomUrlSerializer implements UrlSerializer {
} }
// use the require method provided by webpack // use the require method provided by webpack
declare const require; declare const require: (path: string) => string;
export function translationsFactory(locale: string) { export function translationsFactory(locale: string) {
locale = locale || 'en'; // default to english if no locale locale = locale || 'en'; // default to english if no locale

View File

@ -1,6 +1,15 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {Event} from '../../../common/event/Event'; import {Event} from '../../../common/event/Event';
declare const document: {
fullscreenElement: any;
mozFullScreenElement: any;
webkitFullscreenElement: any;
exitFullscreen: () => void;
mozCancelFullScreen: () => void;
webkitExitFullscreen: () => void;
};
@Injectable() @Injectable()
export class FullScreenService { export class FullScreenService {

View File

@ -11,11 +11,12 @@ import {SearchResultDTO} from '../../../common/entities/SearchResultDTO';
import {ShareService} from './share.service'; import {ShareService} from './share.service';
import {NavigationService} from '../model/navigation.service'; import {NavigationService} from '../model/navigation.service';
import {UserRoles} from '../../../common/entities/UserDTO'; import {UserRoles} from '../../../common/entities/UserDTO';
import {interval} from 'rxjs'; import {interval, Subscription, Observable} from 'rxjs';
import {ContentWrapper} from '../../../common/entities/ConentWrapper'; import {ContentWrapper} from '../../../common/entities/ConentWrapper';
import {PageHelper} from '../model/page.helper'; import {PageHelper} from '../model/page.helper';
import {SortingMethods} from '../../../common/entities/SortingMethods'; import {SortingMethods} from '../../../common/entities/SortingMethods';
import {PhotoDTO} from '../../../common/entities/PhotoDTO'; import {PhotoDTO} from '../../../common/entities/PhotoDTO';
import {QueryService} from '../model/query.service';
@Component({ @Component({
selector: 'app-gallery', selector: 'app-gallery',
@ -33,16 +34,16 @@ export class GalleryComponent implements OnInit, OnDestroy {
public directories: DirectoryDTO[] = []; public directories: DirectoryDTO[] = [];
public isPhotoWithLocation = false; public isPhotoWithLocation = false;
private $counter; private $counter: Observable<number>;
private subscription = { private subscription: { [key: string]: Subscription } = {
content: null, content: null,
route: null, route: null,
timer: null, timer: null,
sorting: null sorting: null
}; };
public countDown = null; public countDown: { day: number, hour: number, minute: number, second: number } = null;
public mapEnabled = true; public mapEnabled = true;
SearchTypes: any = []; readonly SearchTypes: typeof SearchTypes;
constructor(public _galleryService: GalleryService, constructor(public _galleryService: GalleryService,
private _authService: AuthenticationService, private _authService: AuthenticationService,
@ -61,7 +62,7 @@ export class GalleryComponent implements OnInit, OnDestroy {
return; return;
} }
t = Math.floor((this.shareService.sharing.value.expires - Date.now()) / 1000); t = Math.floor((this.shareService.sharing.value.expires - Date.now()) / 1000);
this.countDown = {}; this.countDown = <any>{};
this.countDown.day = Math.floor(t / 86400); this.countDown.day = Math.floor(t / 86400);
t -= this.countDown.day * 86400; t -= this.countDown.day * 86400;
this.countDown.hour = Math.floor(t / 3600) % 24; this.countDown.hour = Math.floor(t / 3600) % 24;
@ -74,21 +75,23 @@ export class GalleryComponent implements OnInit, OnDestroy {
private onRoute = async (params: Params) => { private onRoute = async (params: Params) => {
const searchText = params['searchText']; const searchText = params['searchText'];
if (searchText && searchText !== '') { if (searchText && searchText !== '') {
const typeString = params['type']; const typeString: string = params['type'];
if (typeString && typeString !== '') { if (typeString && typeString !== '') {
const type: SearchTypes = <any>SearchTypes[typeString]; const type: SearchTypes = <any>SearchTypes[<any>typeString];
this._galleryService.search(searchText, type); this._galleryService.search(searchText, type).catch(console.error);
return; return;
} }
this._galleryService.search(searchText); this._galleryService.search(searchText).catch(console.error);
return; return;
} }
if (params['sharingKey'] && params['sharingKey'] !== '') { if (params['sharingKey'] && params['sharingKey'] !== '') {
const sharing = await this.shareService.getSharing(); const sharing = await this.shareService.getSharing();
this._router.navigate(['/gallery', sharing.path], {queryParams: {sk: this.shareService.getSharingKey()}}); const qParams: { [key: string]: any } = {};
qParams[QueryService.SHARING_KEY] = this.shareService.getSharingKey();
this._router.navigate(['/gallery', sharing.path], {queryParams: qParams}).catch(console.error);
return; return;
} }

View File

@ -10,6 +10,7 @@ import {Config} from '../../../common/config/public/Config';
import {ShareService} from './share.service'; import {ShareService} from './share.service';
import {NavigationService} from '../model/navigation.service'; import {NavigationService} from '../model/navigation.service';
import {SortingMethods} from '../../../common/entities/SortingMethods'; import {SortingMethods} from '../../../common/entities/SortingMethods';
import {QueryService} from '../model/query.service';
@Injectable() @Injectable()
@ -46,10 +47,10 @@ export class GalleryService {
this.content.next(content); this.content.next(content);
this.lastRequest.directory = directoryName; this.lastRequest.directory = directoryName;
const params = {}; const params: { [key: string]: any } = {};
if (Config.Client.Sharing.enabled === true) { if (Config.Client.Sharing.enabled === true) {
if (this._shareService.isSharing()) { if (this._shareService.isSharing()) {
params['sk'] = this._shareService.getSharingKey(); params[QueryService.SHARING_KEY] = this._shareService.getSharingKey();
} }
} }
@ -98,7 +99,7 @@ export class GalleryService {
const cw = new ContentWrapper(); const cw = new ContentWrapper();
cw.searchResult = this.galleryCacheService.getSearch(text, type); cw.searchResult = this.galleryCacheService.getSearch(text, type);
if (cw.searchResult == null) { if (cw.searchResult == null) {
const params = {}; const params: { type?: SearchTypes } = {};
if (typeof type !== 'undefined') { if (typeof type !== 'undefined') {
params['type'] = type; params['type'] = type;
} }

View File

@ -51,7 +51,7 @@ export class GalleryGridComponent implements OnChanges, OnInit, AfterViewInit, O
private MAX_ROW_COUNT = 5; private MAX_ROW_COUNT = 5;
private onScrollFired = false; private onScrollFired = false;
private helperTime = null; private helperTime: number = null;
isAfterViewInit = false; isAfterViewInit = false;
private renderedPhotoIndex = 0; private renderedPhotoIndex = 0;
subscriptions: { subscriptions: {
@ -96,7 +96,7 @@ export class GalleryGridComponent implements OnChanges, OnInit, AfterViewInit, O
this.updateContainerDimensions(); this.updateContainerDimensions();
this.sortPhotos(); this.sortPhotos();
this.mergeNewPhotos(); this.mergeNewPhotos();
this.helperTime = setTimeout(() => { this.helperTime = window.setTimeout(() => {
this.renderPhotos(); this.renderPhotos();
if (this.delayedRenderUpToPhoto) { if (this.delayedRenderUpToPhoto) {
this.renderUpToPhoto(this.delayedRenderUpToPhoto); this.renderUpToPhoto(this.delayedRenderUpToPhoto);
@ -147,7 +147,7 @@ export class GalleryGridComponent implements OnChanges, OnInit, AfterViewInit, O
this.updateContainerDimensions(); this.updateContainerDimensions();
this.sortPhotos(); this.sortPhotos();
this.clearRenderedPhotos(); this.clearRenderedPhotos();
this.helperTime = setTimeout(() => { this.helperTime = window.setTimeout(() => {
this.renderPhotos(); this.renderPhotos();
}, 0); }, 0);
this.isAfterViewInit = true; this.isAfterViewInit = true;

View File

@ -27,9 +27,9 @@ export class GalleryPhotoComponent implements IRenderable, OnInit, OnDestroy {
visible: false, visible: false,
background: 'rgba(0,0,0,0.0)' background: 'rgba(0,0,0,0.0)'
}; };
animationTimer = null; animationTimer: number = null;
SearchTypes: any = []; readonly SearchTypes: typeof SearchTypes;
searchEnabled = true; searchEnabled = true;
wasInView: boolean = null; wasInView: boolean = null;
@ -90,10 +90,10 @@ export class GalleryPhotoComponent implements IRenderable, OnInit, OnDestroy {
if (this.animationTimer != null) { if (this.animationTimer != null) {
clearTimeout(this.animationTimer); clearTimeout(this.animationTimer);
} }
this.animationTimer = setTimeout(() => { this.animationTimer = window.setTimeout(() => {
this.infoBar.background = 'rgba(0,0,0,0.8)'; this.infoBar.background = 'rgba(0,0,0,0.8)';
if (!this.infoDiv) { if (!this.infoDiv) {
this.animationTimer = setTimeout(() => { this.animationTimer = window.setTimeout(() => {
if (!this.infoDiv) { if (!this.infoDiv) {
this.infoBar.marginTop = -50; this.infoBar.marginTop = -50;
return; return;
@ -111,13 +111,13 @@ export class GalleryPhotoComponent implements IRenderable, OnInit, OnDestroy {
if (this.animationTimer != null) { if (this.animationTimer != null) {
clearTimeout(this.animationTimer); clearTimeout(this.animationTimer);
} }
this.animationTimer = setTimeout(() => { this.animationTimer = window.setTimeout(() => {
this.infoBar.marginTop = 0; this.infoBar.marginTop = 0;
this.infoBar.background = 'rgba(0,0,0,0.0)'; this.infoBar.background = 'rgba(0,0,0,0.0)';
if (this.animationTimer != null) { if (this.animationTimer != null) {
clearTimeout(this.animationTimer); clearTimeout(this.animationTimer);
} }
this.animationTimer = setTimeout(() => { this.animationTimer = window.setTimeout(() => {
this.infoBar.visible = false; this.infoBar.visible = false;
}, 500); }, 500);
}, 100); }, 100);

View File

@ -51,7 +51,7 @@ export class InfoPanelLightboxComponent {
} }
toFraction(f) { toFraction(f: number) {
if (f > 1) { if (f > 1) {
return f; return f;
} }

View File

@ -41,7 +41,7 @@ export class GalleryLightboxComponent implements OnDestroy, OnInit {
@ViewChild('lightbox') lightboxElement: ElementRef; @ViewChild('lightbox') lightboxElement: ElementRef;
public navigation = {hasPrev: true, hasNext: true}; public navigation = {hasPrev: true, hasNext: true};
public blackCanvasOpacity: any = 0; public blackCanvasOpacity = 0;
private activePhotoId: number = null; private activePhotoId: number = null;
public activePhoto: GalleryPhotoComponent; public activePhoto: GalleryPhotoComponent;
@ -65,8 +65,8 @@ export class GalleryLightboxComponent implements OnDestroy, OnInit {
public infoPanelWidth = 0; public infoPanelWidth = 0;
public animating = false; public animating = false;
startPhotoDimension: Dimension = <Dimension>{top: 0, left: 0, width: 0, height: 0}; startPhotoDimension: Dimension = <Dimension>{top: 0, left: 0, width: 0, height: 0};
iPvisibilityTimer = null; iPvisibilityTimer: number = null;
visibilityTimer = null; visibilityTimer: number = null;
delayedPhotoShow: string = null; delayedPhotoShow: string = null;
@ -326,7 +326,7 @@ export class GalleryLightboxComponent implements OnDestroy, OnInit {
} }
hideInfoPanel(_animate: boolean = true) { hideInfoPanel(_animate: boolean = true) {
this.iPvisibilityTimer = setTimeout(() => { this.iPvisibilityTimer = window.setTimeout(() => {
this.iPvisibilityTimer = null; this.iPvisibilityTimer = null;
this.infoPanelVisible = false; this.infoPanelVisible = false;
}, 1000); }, 1000);
@ -465,7 +465,7 @@ export class GalleryLightboxComponent implements OnDestroy, OnInit {
if (this.visibilityTimer != null) { if (this.visibilityTimer != null) {
clearTimeout(this.visibilityTimer); clearTimeout(this.visibilityTimer);
} }
this.visibilityTimer = setTimeout(this.hideControls, 2000); this.visibilityTimer = window.setTimeout(this.hideControls, 2000);
} }
private hideControls = () => { private hideControls = () => {

View File

@ -16,7 +16,7 @@ export class GalleryLightboxMediaComponent implements OnChanges {
@ViewChild('video') video: ElementRef<HTMLVideoElement>; @ViewChild('video') video: ElementRef<HTMLVideoElement>;
prevGirdPhoto = null; prevGirdPhoto: GridMedia = null;
public imageSize = {width: 'auto', height: '100'}; public imageSize = {width: 'auto', height: '100'};

View File

@ -25,7 +25,7 @@ export class GalleryMapLightboxComponent implements OnChanges, AfterViewInit {
@Input() photos: PhotoDTO[]; @Input() photos: PhotoDTO[];
@Input() gpxFiles: FileDTO[]; @Input() gpxFiles: FileDTO[];
private startPosition = null; private startPosition: Dimension = null;
public lightboxDimension: Dimension = <Dimension>{top: 0, left: 0, width: 0, height: 0}; public lightboxDimension: Dimension = <Dimension>{top: 0, left: 0, width: 0, height: 0};
public mapDimension: Dimension = <Dimension>{top: 0, left: 0, width: 0, height: 0}; public mapDimension: Dimension = <Dimension>{top: 0, left: 0, width: 0, height: 0};
public visible = false; public visible = false;

View File

@ -20,7 +20,7 @@ export class GalleryMapComponent implements OnChanges, IRenderable, AfterViewIni
mapPhotos: Array<{ latitude: number, longitude: number }> = []; mapPhotos: Array<{ latitude: number, longitude: number }> = [];
@ViewChild('map') mapElement: ElementRef; @ViewChild('map') mapElement: ElementRef;
height = null; height: number = null;
constructor(private mapsAPILoader: MapsAPILoader) { constructor(private mapsAPILoader: MapsAPILoader) {

View File

@ -10,6 +10,7 @@ import {BsModalService} from 'ngx-bootstrap/modal';
import {BsModalRef} from 'ngx-bootstrap/modal/bs-modal-ref.service'; import {BsModalRef} from 'ngx-bootstrap/modal/bs-modal-ref.service';
import {OrientationType, RandomQueryDTO} from '../../../../common/entities/RandomQueryDTO'; import {OrientationType, RandomQueryDTO} from '../../../../common/entities/RandomQueryDTO';
import {NetworkService} from '../../model/network/network.service'; import {NetworkService} from '../../model/network/network.service';
import {Subscription} from 'rxjs';
@Component({ @Component({
@ -31,9 +32,9 @@ export class RandomQueryBuilderGalleryComponent implements OnInit, OnDestroy {
toDate: null, toDate: null,
fromDate: null fromDate: null
}; };
contentSubscription = null; contentSubscription: Subscription = null;
OrientationType; readonly OrientationType: typeof OrientationType;
modalRef: BsModalRef; modalRef: BsModalRef;
text = { text = {
@ -71,8 +72,8 @@ export class RandomQueryBuilderGalleryComponent implements OnInit, OnDestroy {
setTimeout(() => { setTimeout(() => {
const data = Utils.clone(this.data); const data = Utils.clone(this.data);
for (const key of Object.keys(data)) { for (const key of Object.keys(data)) {
if (!data[key]) { if (!(<any>data)[key]) {
delete data[key]; delete (<any>data)[key];
} }
} }
this.url = NetworkService.buildUrl(Config.Client.publicUrl + '/api/gallery/random/', data); this.url = NetworkService.buildUrl(Config.Client.publicUrl + '/api/gallery/random/', data);

View File

@ -3,6 +3,7 @@ import {AutoCompleteService} from './autocomplete.service';
import {AutoCompleteItem, SearchTypes} from '../../../../common/entities/AutoCompleteItem'; import {AutoCompleteItem, SearchTypes} from '../../../../common/entities/AutoCompleteItem';
import {ActivatedRoute, Params, RouterLink} from '@angular/router'; import {ActivatedRoute, Params, RouterLink} from '@angular/router';
import {GalleryService} from '../gallery.service'; import {GalleryService} from '../gallery.service';
import {Subscription} from 'rxjs';
import {Config} from '../../../../common/config/public/Config'; import {Config} from '../../../../common/config/public/Config';
@Component({ @Component({
@ -13,16 +14,16 @@ import {Config} from '../../../../common/config/public/Config';
}) })
export class GallerySearchComponent implements OnDestroy { export class GallerySearchComponent implements OnDestroy {
autoCompleteItems: Array<AutoCompleteRenderItem> = []; autoCompleteItems: AutoCompleteRenderItem[] = [];
public searchText = ''; public searchText = '';
private cache = { private cache = {
lastAutocomplete: '', lastAutocomplete: '',
lastInstantSearch: '' lastInstantSearch: ''
}; };
SearchTypes: any = [];
mouseOverAutoComplete = false; mouseOverAutoComplete = false;
private readonly subscription = null;
readonly SearchTypes: typeof SearchTypes;
private readonly subscription: Subscription = null;
constructor(private _autoCompleteService: AutoCompleteService, constructor(private _autoCompleteService: AutoCompleteService,
private _galleryService: GalleryService, private _galleryService: GalleryService,

View File

@ -3,22 +3,23 @@ import {NetworkService} from '../model/network/network.service';
import {CreateSharingDTO, SharingDTO} from '../../../common/entities/SharingDTO'; import {CreateSharingDTO, SharingDTO} from '../../../common/entities/SharingDTO';
import {Router, RoutesRecognized} from '@angular/router'; import {Router, RoutesRecognized} from '@angular/router';
import {BehaviorSubject} from 'rxjs'; import {BehaviorSubject} from 'rxjs';
import {QueryService} from '../model/query.service';
@Injectable() @Injectable()
export class ShareService { export class ShareService {
public sharing: BehaviorSubject<SharingDTO>; public sharing: BehaviorSubject<SharingDTO>;
param = null; param: string = null;
queryParam = null; queryParam: string = null;
sharingKey = null; sharingKey: string = null;
inited = false; inited = false;
public ReadyPR: Promise<void>; public ReadyPR: Promise<void>;
private resolve; private resolve: () => void;
constructor(private _networkService: NetworkService, private router: Router) { constructor(private _networkService: NetworkService, private router: Router) {
this.sharing = new BehaviorSubject(null); this.sharing = new BehaviorSubject(null);
this.ReadyPR = new Promise((resolve) => { this.ReadyPR = new Promise((resolve: () => void) => {
if (this.inited === true) { if (this.inited === true) {
return resolve(); return resolve();
} }
@ -28,7 +29,7 @@ export class ShareService {
this.router.events.subscribe(val => { this.router.events.subscribe(val => {
if (val instanceof RoutesRecognized) { if (val instanceof RoutesRecognized) {
this.param = val.state.root.firstChild.params['sharingKey'] || null; this.param = val.state.root.firstChild.params['sharingKey'] || null;
this.queryParam = val.state.root.firstChild.queryParams['sk'] || null; this.queryParam = val.state.root.firstChild.queryParams[QueryService.SHARING_KEY] || null;
const changed = this.sharingKey !== this.param || this.queryParam; const changed = this.sharingKey !== this.param || this.queryParam;
if (changed) { if (changed) {
this.sharingKey = this.param || this.queryParam; this.sharingKey = this.param || this.queryParam;

View File

@ -10,6 +10,7 @@ import {DirectoryDTO} from '../../../../common/entities/DirectoryDTO';
import {I18n} from '@ngx-translate/i18n-polyfill'; import {I18n} from '@ngx-translate/i18n-polyfill';
import {BsModalService} from 'ngx-bootstrap/modal'; import {BsModalService} from 'ngx-bootstrap/modal';
import {BsModalRef} from 'ngx-bootstrap/modal/bs-modal-ref.service'; import {BsModalRef} from 'ngx-bootstrap/modal/bs-modal-ref.service';
import {Subscription} from 'rxjs';
@Component({ @Component({
@ -32,7 +33,7 @@ export class GalleryShareComponent implements OnInit, OnDestroy {
}; };
currentDir = ''; currentDir = '';
sharing: SharingDTO = null; sharing: SharingDTO = null;
contentSubscription = null; contentSubscription: Subscription = null;
passwordProtection = false; passwordProtection = false;
ValidityTypes: any; ValidityTypes: any;

View File

@ -11,7 +11,7 @@ class MockUserService {
return Promise.resolve(<UserDTO>{name: 'testUserName'}); return Promise.resolve(<UserDTO>{name: 'testUserName'});
} }
public async getSessionUser() { public async getSessionUser(): Promise<UserDTO> {
return null; return null;
} }
} }
@ -34,11 +34,11 @@ describe('AuthenticationService', () => {
it('should call UserDTO service login', inject([AuthenticationService, UserService], it('should call UserDTO service login', inject([AuthenticationService, UserService],
async (authService, userService) => { async (authService: AuthenticationService, userService: UserService) => {
spyOn(userService, 'login').and.callThrough(); spyOn(userService, 'login').and.callThrough();
expect(userService.login).not.toHaveBeenCalled(); expect(userService.login).not.toHaveBeenCalled();
await authService.login(); await authService.login(null);
expect(userService.login).toHaveBeenCalled(); expect(userService.login).toHaveBeenCalled();
})); }));

View File

@ -30,7 +30,7 @@ describe('NetworkService Success tests', () => {
httpMock.verify(); httpMock.verify();
}); });
it('should call GET', inject([NetworkService], (networkService) => { it('should call GET', inject([NetworkService], (networkService: NetworkService) => {
networkService.getJson(testUrl).then((res: string) => { networkService.getJson(testUrl).then((res: string) => {
expect(res).toBe(testResponse); expect(res).toBe(testResponse);
@ -45,7 +45,7 @@ describe('NetworkService Success tests', () => {
mockReq.flush(testResponseMessage); mockReq.flush(testResponseMessage);
})); }));
it('should call POST', inject([NetworkService], (networkService) => { it('should call POST', inject([NetworkService], (networkService: NetworkService) => {
networkService.postJson(testUrl, testData).then((res: string) => { networkService.postJson(testUrl, testData).then((res: string) => {
expect(res).toBe(testResponse); expect(res).toBe(testResponse);
@ -77,7 +77,7 @@ describe('NetworkService Success tests', () => {
})); }));
it('should call DELETE', inject([NetworkService], (networkService) => { it('should call DELETE', inject([NetworkService], (networkService: NetworkService) => {
networkService.deleteJson(testUrl).then((res: any) => { networkService.deleteJson(testUrl).then((res: any) => {
expect(res).toBe(testResponse); expect(res).toBe(testResponse);
@ -89,7 +89,7 @@ describe('NetworkService Success tests', () => {
mockReq.flush(testResponseMessage); mockReq.flush(testResponseMessage);
})); }));
it('should call PUT', inject([NetworkService], (networkService) => { it('should call PUT', inject([NetworkService], (networkService: NetworkService) => {
networkService.putJson(testUrl, testData).then((res: any) => { networkService.putJson(testUrl, testData).then((res: any) => {
expect(res).toBe(testResponse); expect(res).toBe(testResponse);
@ -142,7 +142,7 @@ describe('NetworkService Fail tests', () => {
httpMock.verify(); httpMock.verify();
}); });
it('should call GET with error', inject([NetworkService], (networkService) => { it('should call GET with error', inject([NetworkService], (networkService: NetworkService) => {
networkService.getJson(testUrl).then((res: any) => { networkService.getJson(testUrl).then((res: any) => {
expect(res).toBe(null); expect(res).toBe(null);
@ -157,7 +157,7 @@ describe('NetworkService Fail tests', () => {
mockReq.error(null, {statusText: testError}); mockReq.error(null, {statusText: testError});
})); }));
it('should call POST with error', inject([NetworkService], (networkService) => { it('should call POST with error', inject([NetworkService], (networkService: NetworkService) => {
networkService.postJson(testUrl, testData).then((res: any) => { networkService.postJson(testUrl, testData).then((res: any) => {
expect(res).toBe(null); expect(res).toBe(null);
@ -172,7 +172,7 @@ describe('NetworkService Fail tests', () => {
mockReq.error(null, {statusText: testError}); mockReq.error(null, {statusText: testError});
})); }));
it('should call PUT with error', inject([NetworkService], (networkService) => { it('should call PUT with error', inject([NetworkService], (networkService: NetworkService) => {
networkService.putJson(testUrl, testData).then((res: any) => { networkService.putJson(testUrl, testData).then((res: any) => {
expect(res).toBe(null); expect(res).toBe(null);
@ -189,7 +189,7 @@ describe('NetworkService Fail tests', () => {
})); }));
it('should call DELETE with error', inject([NetworkService], (networkService) => { it('should call DELETE with error', inject([NetworkService], (networkService: NetworkService) => {
networkService.deleteJson(testUrl).then((res: any) => { networkService.deleteJson(testUrl).then((res: any) => {
expect(res).toBe(null); expect(res).toBe(null);

View File

@ -46,7 +46,7 @@ export class NetworkService {
return parser.parseFromString(res, 'text/xml'); return parser.parseFromString(res, 'text/xml');
}; };
const err = (error) => { const err = (error: any) => {
this.slimLoadingBarService.complete(); this.slimLoadingBarService.complete();
return this.handleError(error); return this.handleError(error);
}; };
@ -85,14 +85,14 @@ export class NetworkService {
this.slimLoadingBarService.complete(); this.slimLoadingBarService.complete();
if (!!res.error) { if (!!res.error) {
if (res.error.code) { if (res.error.code) {
res.error['title'] = ErrorCodes[res.error.code]; (<any>res.error)['title'] = ErrorCodes[res.error.code];
} }
throw res.error; throw res.error;
} }
return res.result; return res.result;
}; };
const err = (error) => { const err = (error:any) => {
this.slimLoadingBarService.complete(); this.slimLoadingBarService.complete();
return this.handleError(error); return this.handleError(error);
}; };

View File

@ -32,20 +32,20 @@ describe('UserService', () => {
}); });
it('should call postJson at login', inject([UserService, NetworkService], it('should call postJson at login', inject([UserService, NetworkService],
async (userService, networkService) => { async (userService: UserService, networkService: NetworkService) => {
spyOn(networkService, 'postJson'); spyOn(networkService, 'postJson');
const credential = new LoginCredential('name', 'pass'); const credential = new LoginCredential('name', 'pass');
await userService.login(credential); await userService.login(credential);
expect(networkService.postJson).toHaveBeenCalled(); expect(networkService.postJson).toHaveBeenCalled();
expect(networkService.postJson.calls.argsFor(0)).toEqual(['/user/login', {'loginCredential': credential}]); expect((<any>networkService.postJson).calls.argsFor(0)).toEqual(['/user/login', {'loginCredential': credential}]);
})); }));
it('should call getJson at getSessionUser', inject([UserService, NetworkService], it('should call getJson at getSessionUser', inject([UserService, NetworkService],
async (userService, networkService) => { async (userService: UserService, networkService: NetworkService) => {
spyOn(networkService, 'getJson'); spyOn(networkService, 'getJson');
await userService.getSessionUser(); await userService.getSessionUser();
expect(networkService.getJson).toHaveBeenCalled(); expect(networkService.getJson).toHaveBeenCalled();
expect(networkService.getJson.calls.argsFor(0)).toEqual(['/user/login']); expect((<any>networkService.getJson).calls.argsFor(0)).toEqual(['/user/login']);
})); }));

View File

@ -53,19 +53,19 @@ export class NotificationService {
}); });
} }
success(text, title = null) { success(text: string, title: string = null): void {
this._toastr.success(text, title, this.options); this._toastr.success(text, title, this.options);
} }
error(text, title?) { error(text: string, title?: string): void {
this._toastr.error(text, title, this.options); this._toastr.error(text, title, this.options);
} }
warning(text, title?) { warning(text: string, title?: string): void {
this._toastr.warning(text, title, this.options); this._toastr.warning(text, title, this.options);
} }
info(text, title = null) { info(text: string, title: string = null): void {
this._toastr.info(text, title, this.options); this._toastr.info(text, title, this.options);
} }

View File

@ -7,17 +7,18 @@ import {MediaDTO} from '../../../common/entities/MediaDTO';
export class QueryService { export class QueryService {
public static readonly PHOTO_PARAM = 'p'; public static readonly PHOTO_PARAM = 'p';
public static readonly SHARING_KEY = 'sk';
constructor(private shareService: ShareService) { constructor(private shareService: ShareService) {
} }
getParams(media?: MediaDTO): { [key: string]: string } { getParams(media?: MediaDTO): { [key: string]: string } {
const query = {}; const query: { [key: string]: string } = {};
if (media) { if (media) {
query[QueryService.PHOTO_PARAM] = media.name; query[QueryService.PHOTO_PARAM] = media.name;
} }
if (this.shareService.isSharing()) { if (this.shareService.isSharing()) {
query['sk'] = this.shareService.getSharingKey(); query[QueryService.SHARING_KEY] = this.shareService.getSharingKey();
} }
return query; return query;
} }

View File

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

View File

@ -8,9 +8,10 @@ import {NavigationService} from '../../model/navigation.service';
import {AbstractSettingsService} from './abstract.settings.service'; import {AbstractSettingsService} from './abstract.settings.service';
import {IPrivateConfig} from '../../../../common/config/private/IPrivateConfig'; import {IPrivateConfig} from '../../../../common/config/private/IPrivateConfig';
import {I18n} from '@ngx-translate/i18n-polyfill'; import {I18n} from '@ngx-translate/i18n-polyfill';
import {Subscription} from 'rxjs';
export abstract class SettingsComponent<T, S extends AbstractSettingsService<T> = AbstractSettingsService<T>> export abstract class SettingsComponent<T extends { [key: string]: any }, S extends AbstractSettingsService<T> = AbstractSettingsService<T>>
implements OnInit, OnDestroy, OnChanges { implements OnInit, OnDestroy, OnChanges {
@Input() @Input()
@ -25,8 +26,8 @@ export abstract class SettingsComponent<T, S extends AbstractSettingsService<T>
public inProgress = false; public inProgress = false;
public error: string = null; public error: string = null;
public changed = false; public changed = false;
private _subscription = null; private _subscription: Subscription = null;
private readonly _settingsSubscription = null; private readonly _settingsSubscription: Subscription = null;
public settings: T = <any>{}; public settings: T = <any>{};
public original: T = <any>{}; public original: T = <any>{};
@ -38,7 +39,7 @@ export abstract class SettingsComponent<T, S extends AbstractSettingsService<T>
High: 'High' High: 'High'
}; };
protected constructor(private name, protected constructor(private name: string,
private _authService: AuthenticationService, private _authService: AuthenticationService,
private _navigation: NavigationService, private _navigation: NavigationService,
public _settingsService: S, public _settingsService: S,
@ -55,7 +56,7 @@ export abstract class SettingsComponent<T, S extends AbstractSettingsService<T>
this.text.High = i18n('High'); this.text.High = i18n('High');
} }
onNewSettings = (s) => { onNewSettings = (s: IPrivateConfig) => {
this.settings = Utils.clone(this.sliceFN(s)); this.settings = Utils.clone(this.sliceFN(s));
this.original = Utils.clone(this.settings); this.original = Utils.clone(this.settings);
this.ngOnChanges(); this.ngOnChanges();

View File

@ -28,7 +28,7 @@ export class IndexingSettingsService extends AbstractSettingsService<IndexingCon
return this._settingsService.settings.value.Server.database.type !== DatabaseType.memory; return this._settingsService.settings.value.Server.database.type !== DatabaseType.memory;
} }
public index(createThumbnails) { public index(createThumbnails: boolean) {
return this._networkService.postJson('/admin/indexes/job', <IndexingDTO>{createThumbnails: createThumbnails}); return this._networkService.postJson('/admin/indexes/job', <IndexingDTO>{createThumbnails: createThumbnails});
} }

View File

@ -64,7 +64,9 @@
"@ngx-translate/i18n-polyfill": "1.0.0", "@ngx-translate/i18n-polyfill": "1.0.0",
"@types/bcryptjs": "2.4.2", "@types/bcryptjs": "2.4.2",
"@types/chai": "4.1.7", "@types/chai": "4.1.7",
"@types/cookie-parser": "^1.4.1",
"@types/cookie-session": "2.0.36", "@types/cookie-session": "2.0.36",
"@types/ejs": "^2.6.0",
"@types/express": "4.16.0", "@types/express": "4.16.0",
"@types/fluent-ffmpeg": "^2.1.8", "@types/fluent-ffmpeg": "^2.1.8",
"@types/gm": "1.18.2", "@types/gm": "1.18.2",

View File

@ -16,7 +16,7 @@ describe('Authentication middleware', () => {
describe('authenticate', () => { describe('authenticate', () => {
it('should call next on authenticated', (done) => { it('should call next on authenticated', (done) => {
let req: any = { const req: any = {
session: { session: {
user: 'A user' user: 'A user'
}, },
@ -24,7 +24,7 @@ describe('Authentication middleware', () => {
query: {}, query: {},
params: {} params: {}
}; };
let next: any = (err) => { const next: any = (err: ErrorDTO) => {
expect(err).to.be.undefined; expect(err).to.be.undefined;
done(); done();
}; };
@ -33,15 +33,15 @@ describe('Authentication middleware', () => {
}); });
it('should call next with error on not authenticated', (done) => { it('should call next with error on not authenticated', (done) => {
let req: any = { const req: any = {
session: {}, session: {},
sessionOptions: {}, sessionOptions: {},
query: {}, query: {},
params: {} params: {}
}; };
Config.Client.authenticationRequired = true; Config.Client.authenticationRequired = true;
let res: any = {}; const res: any = {};
let next: any = (err: ErrorDTO) => { const next: any = (err: ErrorDTO) => {
expect(err).not.to.be.undefined; expect(err).not.to.be.undefined;
expect(err.code).to.be.eql(ErrorCodes.NOT_AUTHENTICATED); expect(err.code).to.be.eql(ErrorCodes.NOT_AUTHENTICATED);
done(); done();
@ -54,12 +54,12 @@ describe('Authentication middleware', () => {
describe('inverseAuthenticate', () => { describe('inverseAuthenticate', () => {
it('should call next with error on authenticated', (done) => { it('should call next with error on authenticated', (done) => {
let req: any = { const req: any = {
session: {}, session: {},
sessionOptions: {}, sessionOptions: {},
}; };
let res: any = {}; const res: any = {};
let next: any = (err) => { const next: any = (err:ErrorDTO) => {
expect(err).to.be.undefined; expect(err).to.be.undefined;
done(); done();
}; };
@ -69,14 +69,14 @@ describe('Authentication middleware', () => {
it('should call next error on authenticated', (done) => { it('should call next error on authenticated', (done) => {
let req: any = { const req: any = {
session: { session: {
user: 'A user' user: 'A user'
}, },
sessionOptions: {}, sessionOptions: {},
}; };
let res: any = {}; const res: any = {};
let next: any = (err: ErrorDTO) => { const next: any = (err: ErrorDTO) => {
expect(err).not.to.be.undefined; expect(err).not.to.be.undefined;
expect(err.code).to.be.eql(ErrorCodes.ALREADY_AUTHENTICATED); expect(err.code).to.be.eql(ErrorCodes.ALREADY_AUTHENTICATED);
done(); done();
@ -88,7 +88,7 @@ describe('Authentication middleware', () => {
describe('authorise', () => { describe('authorise', () => {
it('should call next on authorised', (done) => { it('should call next on authorised', (done) => {
let req: any = { const req: any = {
session: { session: {
user: { user: {
role: UserRoles.LimitedGuest role: UserRoles.LimitedGuest
@ -96,7 +96,7 @@ describe('Authentication middleware', () => {
}, },
sessionOptions: {} sessionOptions: {}
}; };
let next: any = (err) => { const next: any = (err:ErrorDTO) => {
expect(err).to.be.undefined; expect(err).to.be.undefined;
done(); done();
}; };
@ -105,7 +105,7 @@ describe('Authentication middleware', () => {
}); });
it('should call next with error on not authorised', (done) => { it('should call next with error on not authorised', (done) => {
let req: any = { const req: any = {
session: { session: {
user: { user: {
role: UserRoles.LimitedGuest role: UserRoles.LimitedGuest
@ -113,7 +113,7 @@ describe('Authentication middleware', () => {
}, },
sessionOptions: {} sessionOptions: {}
}; };
let next: any = (err: ErrorDTO) => { const next: any = (err: ErrorDTO) => {
expect(err).not.to.be.undefined; expect(err).not.to.be.undefined;
expect(err.code).to.be.eql(ErrorCodes.NOT_AUTHORISED); expect(err.code).to.be.eql(ErrorCodes.NOT_AUTHORISED);
done(); done();
@ -130,11 +130,11 @@ describe('Authentication middleware', () => {
describe('should call input ErrorDTO next on missing...', () => { describe('should call input ErrorDTO next on missing...', () => {
it('body', (done) => { it('body', (done) => {
let req: any = { const req: any = {
query: {}, query: {},
params: {} params: {}
}; };
let next: any = (err: ErrorDTO) => { const next: any = (err: ErrorDTO) => {
expect(err).not.to.be.undefined; expect(err).not.to.be.undefined;
expect(err.code).to.be.eql(ErrorCodes.INPUT_ERROR); expect(err.code).to.be.eql(ErrorCodes.INPUT_ERROR);
done(); done();
@ -144,12 +144,12 @@ describe('Authentication middleware', () => {
}); });
it('loginCredential', (done) => { it('loginCredential', (done) => {
let req: any = { const req: any = {
body: {}, body: {},
query: {}, query: {},
params: {} params: {}
}; };
let next: any = (err: ErrorDTO) => { const next: any = (err: ErrorDTO) => {
expect(err).not.to.be.undefined; expect(err).not.to.be.undefined;
expect(err.code).to.be.eql(ErrorCodes.INPUT_ERROR); expect(err.code).to.be.eql(ErrorCodes.INPUT_ERROR);
done(); done();
@ -161,12 +161,12 @@ describe('Authentication middleware', () => {
it('loginCredential content', (done) => { it('loginCredential content', (done) => {
let req: any = { const req: any = {
body: {loginCredential: {}}, body: {loginCredential: {}},
query: {}, query: {},
params: {} params: {}
}; };
let next: any = (err: ErrorDTO) => { const next: any = (err: ErrorDTO) => {
expect(err).not.to.be.undefined; expect(err).not.to.be.undefined;
expect(err.code).to.be.eql(ErrorCodes.INPUT_ERROR); expect(err.code).to.be.eql(ErrorCodes.INPUT_ERROR);
done(); done();
@ -178,7 +178,7 @@ describe('Authentication middleware', () => {
}); });
it('should call next with error on not finding user', (done) => { it('should call next with error on not finding user', (done) => {
let req: any = { const req: any = {
body: { body: {
loginCredential: { loginCredential: {
username: 'aa', username: 'aa',
@ -188,7 +188,7 @@ describe('Authentication middleware', () => {
query: {}, query: {},
params: {} params: {}
}; };
let next: any = (err: ErrorDTO) => { const next: any = (err: ErrorDTO) => {
expect(err).not.to.be.undefined; expect(err).not.to.be.undefined;
expect(err.code).to.be.eql(ErrorCodes.CREDENTIAL_NOT_FOUND); expect(err.code).to.be.eql(ErrorCodes.CREDENTIAL_NOT_FOUND);
done(); done();
@ -204,7 +204,7 @@ describe('Authentication middleware', () => {
}); });
it('should call next with user on the session on finding user', (done) => { it('should call next with user on the session on finding user', (done) => {
let req: any = { const req: any = {
session: {}, session: {},
body: { body: {
loginCredential: { loginCredential: {
@ -215,7 +215,7 @@ describe('Authentication middleware', () => {
query: {}, query: {},
params: {} params: {}
}; };
let next: any = (err: ErrorDTO) => { const next: any = (err: ErrorDTO) => {
expect(err).to.be.undefined; expect(err).to.be.undefined;
expect(req.session.user).to.be.eql('test user'); expect(req.session.user).to.be.eql('test user');
done(); done();
@ -234,14 +234,14 @@ describe('Authentication middleware', () => {
describe('logout', () => { describe('logout', () => {
it('should call next on logout', (done) => { it('should call next on logout', (done) => {
let req: any = { const req: any = {
session: { session: {
user: { user: {
role: UserRoles.LimitedGuest role: UserRoles.LimitedGuest
} }
} }
}; };
let next: any = (err) => { const next: any = (err:ErrorDTO) => {
expect(err).to.be.undefined; expect(err).to.be.undefined;
expect(req.session.user).to.be.undefined; expect(req.session.user).to.be.undefined;
done(); done();

View File

@ -8,7 +8,6 @@ import {
import * as path from 'path'; import * as path from 'path';
import {OrientationTypes} from 'ts-exif-parser'; import {OrientationTypes} from 'ts-exif-parser';
import {DirectoryEntity} from '../../../../../backend/model/sql/enitites/DirectoryEntity'; import {DirectoryEntity} from '../../../../../backend/model/sql/enitites/DirectoryEntity';
import {Utils} from '../../../../../common/Utils';
import {VideoEntity, VideoMetadataEntity} from '../../../../../backend/model/sql/enitites/VideoEntity'; import {VideoEntity, VideoMetadataEntity} from '../../../../../backend/model/sql/enitites/VideoEntity';
import {FileEntity} from '../../../../../backend/model/sql/enitites/FileEntity'; import {FileEntity} from '../../../../../backend/model/sql/enitites/FileEntity';
@ -117,7 +116,7 @@ export class TestHelper {
} }
public static getRandomizedDirectoryEntry(parent: DirectoryEntity = null, forceStr = null) { public static getRandomizedDirectoryEntry(parent: DirectoryEntity = null, forceStr: string = null) {
const dir = new DirectoryEntity(); const dir = new DirectoryEntity();
dir.name = forceStr || Math.random().toString(36).substring(7); dir.name = forceStr || Math.random().toString(36).substring(7);
@ -136,7 +135,7 @@ export class TestHelper {
} }
public static getRandomizedGPXEntry(dir: DirectoryEntity, forceStr = null): FileEntity { public static getRandomizedGPXEntry(dir: DirectoryEntity, forceStr: string = null): FileEntity {
const d = new FileEntity(); const d = new FileEntity();
d.name = forceStr + '_' + Math.random().toString(36).substring(7) + '.gpx'; d.name = forceStr + '_' + Math.random().toString(36).substring(7) + '.gpx';
d.directory = dir; d.directory = dir;
@ -145,7 +144,7 @@ export class TestHelper {
return d; return d;
} }
public static getRandomizedPhotoEntry(dir: DirectoryEntity, forceStr = null) { public static getRandomizedPhotoEntry(dir: DirectoryEntity, forceStr: string = null) {
const rndStr = () => { const rndStr = () => {

View File

@ -1,6 +1,7 @@
{ {
"compileOnSave": true, "compileOnSave": true,
"compilerOptions": { "compilerOptions": {
"noImplicitAny": true,
"sourceMap": true, "sourceMap": true,
"declaration": false, "declaration": false,
"moduleResolution": "node", "moduleResolution": "node",