// home.js // Copyright (C) 2021 Digital Telepresence, LLC // License: Apache-2.0 'use strict'; const DTP_COMPONENT_NAME = 'home'; const express = require('express'); const { SiteController, SiteError } = require('../../lib/site-lib'); class HomeController extends SiteController { constructor (dtp) { super(dtp, DTP_COMPONENT_NAME); } async start ( ) { const { dtp } = this; const { limiter: limiterService, sidebar: sidebarService } = dtp.services; const router = this.router = express.Router(); dtp.app.use('/', router); router.param('username', this.populateUsername.bind(this)); router.use(async (req, res, next) => { res.locals.currentView = 'home'; return next(); }); router.get('/:username', limiterService.create(limiterService.config.home.getPublicProfile), this.getPublicProfile.bind(this), ); router.get('/', limiterService.create(limiterService.config.home.getHome), sidebarService.middleware(), this.getHome.bind(this), ); } async populateUsername (req, res, next, username) { const { user: userService } = this.dtp.services; try { res.locals.userProfile = await userService.getPublicProfile(username); return next(); } catch (error) { this.log.error('failed to populate username', { username, error }); return next(error); } } async getPublicProfile (req, res, next) { const { link: linkService, user: userService } = this.dtp.services; try { this.log.debug('profile request', { url: req.url }); if (!res.locals.userProfile) { return next(new SiteError(404, 'Member profile not found')); } res.locals.currentView = 'public-profile'; res.locals.pageTitle = `${res.locals.userProfile.displayName || res.locals.userProfile.username} | ${this.dtp.config.site.name}`; res.locals.pageDescription = res.locals.userProfile.bio || this.dtp.config.site.description; res.locals.pagination = this.getPaginationParameters(req, 20); res.locals.links = await linkService.getForUser(res.locals.userProfile, res.locals.pagination); await userService.recordProfileView(res.locals.userProfile, req); res.render('profile/home'); } catch (error) { this.log.error('failed to display landing page', { error }); return next(error); } } async getHome (req, res, next) { const { link: linkService } = this.dtp.services; try { res.locals.pagination = this.getPaginationParameters(req, 20); if (req.user) { res.locals.links = await linkService.getForUser(req.user, res.locals.pagination); res.render('index-logged-in'); } else { res.render('index'); } } catch (error) { return next(error); } } } module.exports = { slug: 'home', name: 'home', isHome: true, create: async (dtp) => { let controller = new HomeController(dtp); return controller; }, };