Add morgan and winston loggin

This commit is contained in:
Mike Rode
2019-09-08 17:53:52 -05:00
parent b9231447a5
commit d215ed7f89
13 changed files with 394 additions and 123 deletions
+1
View File
@@ -103,6 +103,7 @@ export const checkPlexPin = createPollingAction(dispatch => {
axios.get('/api/plex/check-plex-pin').then(res => {
if (res.data) {
var highestTimeoutId = setTimeout(';');
console.log('highestTimeoutId', highestTimeoutId)
for (var i = 0; i < highestTimeoutId; i++) {
clearTimeout(i);
}
+1 -1
View File
@@ -8,7 +8,7 @@ import Typography from '@material-ui/core/Typography';
class PlexPin extends Component {
async componentDidMount() {
await this.props.fetchPin();
const check = await this.props.checkPlexPin();
await this.props.checkPlexPin();
}
render() {
if (!this.props) {
+39
View File
@@ -0,0 +1,39 @@
var appRoot = require('app-root-path');
const { createLogger, format, transports } = require('winston');
const {
combine,
timestamp,
label,
prettyPrint,
colorize,
json,
printf,
} = format;
const myFormat = printf(({ level, message, label, timestamp }) => {
return `${timestamp} [${label}] ${level}: ${message}`;
});
const logger = createLogger({
level: 'debug',
format: combine(
colorize(),
prettyPrint(),
json(),
timestamp(),
myFormat,
),
transports: [
new transports.File({ filename: `${appRoot}/logs/app.log` }),
new transports.Console(),
],
exitOnError: false, // do not exit on handled exceptions
});
logger.stream = {
write: function(message, encoding) {
logger.info(message, { label: 'HTTP' });
},
};
module.exports = logger;
+215
View File
File diff suppressed because one or more lines are too long
+4 -1
View File
@@ -19,7 +19,7 @@
"dev": "concurrently \"npm run server\" \"npm run client\"",
"debug": "nodemon --exec babel-node --inspect index.js",
"db:reset": "NODE_ENV=test npx sequelize db:migrate:undo:all && NODE_ENV=test npx sequelize db:migrate && npx sequelize db:migrate:undo:all && npx sequelize db:migrate",
"prod:dump": "heroku pg:backups:capture && heroku pg:backups:download",
"prod:dump": "rm latest.dump && heroku pg:backups:capture && heroku pg:backups:download && pg_restore --verbose --clean --no-acl --no-owner -h localhost -U postgres -d recommend_development latest.dump",
"start": "babel-node index.js",
"server": "nodemon --exec babel-node index.js",
"client": "npm run start --prefix client",
@@ -42,6 +42,7 @@
"@babel/preset-env": "^7.5.5",
"@babel/register": "^7.5.5",
"@babel/runtime": "^7.5.5",
"app-root-path": "^2.2.1",
"axios": "^0.19.0",
"babel-plugin-istanbul": "^5.2.0",
"babel-preset-node8": "^1.2.0",
@@ -82,6 +83,8 @@
"tdaw": "^1.3.0",
"uuid": "^3.3.3",
"whatwg-url": "^7.0.0",
"winston": "^3.2.1",
"winston-daily-rotate-file": "^4.0.0",
"xml2json": "^0.11.2",
"yarn": "^1.17.3"
},
+29 -1
View File
@@ -4,6 +4,7 @@ import { json, urlencoded } from 'body-parser';
import passport from 'passport';
import cookieSession from 'cookie-session';
import cookieParser from 'cookie-parser';
import morgan from 'morgan';
import models from './db/models';
import keys from '../config';
import plex from './routes/plex.route';
@@ -13,6 +14,8 @@ import sonarr from './routes/sonarr.route';
import auth from './routes/auth.route';
import admin from './routes/admin.route';
import recommend from './routes/recommend.route';
import winston from '../config/winston';
require('./services/auth/passport');
export default () => {
@@ -39,6 +42,13 @@ export default () => {
server.use(passport.initialize());
server.use(passport.session());
server.use(
morgan(
'Method: :method URL: :url Status: :status Content Length: :res[content-length] Request Header: :req[header] Response Header: :res[header] Response Time: :response-time ms',
{ stream: winston.stream },
),
);
// Set up routes
server.use('/api/plex', plex);
server.use('/api/tdaw', tdaw);
@@ -66,6 +76,15 @@ export default () => {
}
server.get('*', function(req, res, next) {
res.locals.message = err.message;
res.locals.error =
req.app.get('env') === 'development' ? err : {};
winston.error(
`${err.status || 500} - ${err.message} - ${
req.originalUrl
} - ${req.method} - ${req.ip}`,
);
const err = new Error(
`Page Not Found at route ${req.originalUrl}`,
);
@@ -75,7 +94,16 @@ export default () => {
// eslint-disable-next-line no-unused-vars
server.use(function(err, req, res, next) {
console.error('error caught in server/index', err.message); // Log error message in our server's console
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error =
req.app.get('env') === 'development' ? err : {};
winston.error(
`${err.status || 500} - ${err.message} - ${
req.originalUrl
} - ${req.method} - ${req.ip}`,
);
// eslint-disable-next-line no-param-reassign
if (!err.statusCode) err.statusCode = 500; // If err has no specified error code, set error code to 'Internal Server Error (500)'
+23 -21
View File
@@ -6,6 +6,23 @@ import models from '../../db/models';
const rxAuthToken = /authenticationToken="([^"]+)"/;
const encryptUserCreds = (username, password) => {
const creds = `${username}:${password}`;
return btoa(creds);
};
const fetchToken = async (username, password) => {
try {
const res = await request.post(
tokenUrlParams(username, password),
);
const token = res.match(rxAuthToken)[1];
return token;
} catch (error) {
return error.message;
}
};
const tokenUrlParams = (username, password) => ({
url: 'https://plex.tv/users/sign_in.xml',
headers: {
@@ -14,25 +31,10 @@ const tokenUrlParams = (username, password) => ({
},
});
const encryptUserCreds = (username, password) => {
const creds = `${username}:${password}`;
return btoa(creds);
};
const fetchToken = async (username, password) => {
try {
const res = await request.post(tokenUrlParams(username, password));
const token = res.match(rxAuthToken)[1];
return token;
} catch (error) {
return error.message;
}
};
const plexUrlParams = (plexToken, user) => ({
url: 'https://plex.tv/pms/servers.xml',
headers: {
'X-Plex-Client-Identifier': user.googleId,
'X-Plex-Client-Identifier': user.user.email,
'X-Plex-Token': plexToken,
},
});
@@ -42,7 +44,7 @@ const getPlexPin = async user => {
const params = {
url: 'https://plex.tv/pins.xml',
headers: {
'X-Plex-Client-Identifier': user.googleId,
'X-Plex-Client-Identifier': user.email,
},
};
const res = await request.post(params);
@@ -79,8 +81,8 @@ const checkPlexPin = async (pinId, user) => {
const getPlexUrl = async (plexToken, user) => {
try {
const res = await request.get(plexUrlParams(plexToken, user));
let formattedResponse = JSON.parse(parser.toJson(res)).MediaContainer
.Server;
let formattedResponse = JSON.parse(parser.toJson(res))
.MediaContainer.Server;
if (!Array.isArray(formattedResponse)) {
formattedResponse = [formattedResponse];
@@ -96,7 +98,7 @@ const getPlexUrl = async (plexToken, user) => {
plexToken: plexToken.trim(),
plexUrl: `http://${server.address}:${server.port}`.trim(),
},
{where: {googleId: user.googleId}},
{ where: { googleId: user.googleId } },
);
console.log('server--', server);
return `http://${server.address}:${server.port}`;
@@ -106,4 +108,4 @@ const getPlexUrl = async (plexToken, user) => {
}
};
export default {fetchToken, getPlexPin, checkPlexPin, getPlexUrl};
export default { fetchToken, getPlexPin, checkPlexPin, getPlexUrl };
-1
View File
@@ -154,7 +154,6 @@ const importMostWatchedData = async (sectionKey, user) => {
{ sectionKey },
user,
);
console.log('most watched data', mostWatchedData);
const mostWatchedDbData = await updateLibrary(
mostWatchedData,
+2 -2
View File
@@ -3,14 +3,14 @@ import importData from './importData';
import auth from './auth';
import models from '../../db/models';
import helpers from '../helpers';
import request from 'request-promise';
import { Op } from 'sequelize';
const getAuthToken = async (req, res) => {
try {
const { sonarrUrl, sonarrApiKey } = req.query;
const [rowsUpdate, updatedUser] = await models.User.update(
{ sonarrUrl, sonarrApiKey },
{ returning: true, where: { googleId: req.user.googleId } },
{ returning: true, where: { googleId: req.user.email } },
);
return res.json(updatedUser);
+75 -76
View File
@@ -1,54 +1,6 @@
import config from '../../../config';
import helpers from '../helpers';
const getUsersUrlParams = function(user) {
return {
host: user.plexUrl,
path: '/users',
queryParams: {
'X-Plex-Token': user.plexToken,
},
};
};
const getSectionsUrlParams = function(user) {
return {
host: user.plexUrl,
path: '/library/sections',
queryParams: {
'X-Plex-Token': user.plexToken,
},
};
};
const mostWatchedUrlParams = function(
accountId,
sectionKey,
limit = 10,
user,
) {
return {
host: user.plexUrl,
path: '/library/all/top',
queryParams: {
...(accountId && { accountId }),
...(sectionKey && { type: sectionKey }),
...(limit && { limit }),
'X-Plex-Token': user.plexToken,
},
};
};
const getLibraryDataBySectionUrlParams = function(sectionId, user) {
return {
host: user.plexUrl,
path: `/library/sections/${sectionId}/all`,
queryParams: {
'X-Plex-Token': user.plexToken,
},
};
};
const getUsers = async function(user) {
try {
const urlParams = getUsersUrlParams(user);
@@ -60,34 +12,14 @@ const getUsers = async function(user) {
}
};
const getMostWatched = async function(
{ accountId, sectionKey, limit = 10 },
user,
) {
try {
console.log('section key mike --', sectionKey);
const urlParams = mostWatchedUrlParams(
accountId,
sectionKey,
limit,
user,
);
const mostWatchedUrl = helpers.buildUrl(urlParams);
const response = await helpers.request(mostWatchedUrl);
console.log('most-watched-raw-response---', response);
if (response.MediaContainer.Metadata) {
return response.MediaContainer.Metadata;
} else {
return [];
}
} catch (error) {
console.log('getMostWatched plexAPI error', error);
return {
code: error.status,
message: error.statusText,
url: error.config.url,
};
}
const getUsersUrlParams = function(user) {
return {
host: user.plexUrl,
path: '/users',
queryParams: {
'X-Plex-Token': user.plexToken,
},
};
};
const getSections = async function(user) {
@@ -104,6 +36,16 @@ const getSections = async function(user) {
}
};
const getSectionsUrlParams = function(user) {
return {
host: user.plexUrl,
path: '/library/sections',
queryParams: {
'X-Plex-Token': user.plexToken,
},
};
};
const getLibraryDataBySection = async function({ sectionKey }, user) {
try {
const urlParams = getLibraryDataBySectionUrlParams(
@@ -125,6 +67,63 @@ const getLibraryDataBySection = async function({ sectionKey }, user) {
}
};
const getLibraryDataBySectionUrlParams = function(sectionId, user) {
return {
host: user.plexUrl,
path: `/library/sections/${sectionId}/all`,
queryParams: {
'X-Plex-Token': user.plexToken,
},
};
};
const getMostWatched = async function(
{ accountId, sectionKey, limit = 10 },
user,
) {
try {
console.log('section key mike --', sectionKey);
const urlParams = mostWatchedUrlParams(
accountId,
sectionKey,
limit,
user,
);
const mostWatchedUrl = helpers.buildUrl(urlParams);
const response = await helpers.request(mostWatchedUrl);
if (response.MediaContainer.Metadata) {
return response.MediaContainer.Metadata;
} else {
return [];
}
} catch (error) {
console.log('getMostWatched plexAPI error', error);
return {
code: error.status,
message: error.statusText,
url: error.config.url,
};
}
};
const mostWatchedUrlParams = function(
accountId,
sectionKey,
limit = 10,
user,
) {
return {
host: user.plexUrl,
path: '/library/all/top',
queryParams: {
...(accountId && { accountId }),
...(sectionKey && { type: sectionKey }),
...(limit && { limit }),
'X-Plex-Token': user.plexToken,
},
};
};
export default {
getUsers,
getMostWatched,
+5 -2
View File
@@ -5,9 +5,12 @@ import { Op } from 'sequelize';
const getMostWatched = async (req, res) => {
try {
const mostWatched = await models.PlexLibrary.findAll({
where: { UserId: req.user.id, type: 'show', views: { [Op.gt]: 0 } },
where: {
UserId: req.user.id,
type: 'show',
views: { [Op.gt]: 0 },
},
});
console.log('TCL: getMostWatched -> mostWatched', mostWatched);
res.json(mostWatched);
} catch (error) {
res.json(error.message);
@@ -14,24 +14,6 @@ const generateHash = password => {
return bCrypt.hashSync(password, bCrypt.genSaltSync(8), null);
};
const userProfile = () => {
return {
firstName: 'Michael',
lastName: 'Rode',
email: 'michaelrode44@gmail.com',
googleId: '103913097386807680151',
updatedAt: '2012-03-02T11:38:49.321Z',
createdAt: '2012-03-02T11:38:49.321Z',
plexUrl: null,
plexToken: null,
plexPinId: null,
sonarrUrl: null,
sonarrApiKey: null,
admin: null,
password: null,
};
};
const fetchUserAndFormat = email => {
return models.User.findOne({
where: { email },