rm unused after migrate to api

This commit is contained in:
tmshv committed 2020-02-15 04:35:19 +03:00
1 parent f3febbe3a9
commit 4de352e2df
25 files changed
-1149

No files matched your search

-36
View File
@@ -1,36 +0,0 @@
import ImageArtifactType from '../core/ImageArtifactType'
const sizes = [
ImageArtifactType.MEDIUM,
ImageArtifactType.BIG,
ImageArtifactType.ORIGIN,
]
export function encodeFilePreview(file, sizes) {
const preview = file.preview
if (!preview) return null
const image = preview.findArtifact(sizes)
if (!image) return null
return image.url
}
export function encodeFile(file) {
const imageUrl = encodeFilePreview(file, sizes)
const category = (file.category || '')
.replace('Documents/', '')
.replace('Pages/', '')
.replace('Albums/', '')
.replace('Articles /', '')
return {
imageUrl,
category,
title: file.title,
fileName: file.fileInfo.name,
fileSize: file.fileInfo.size,
fileUrl: file.url,
url: file.viewUrl,
}
}
-24
View File
@@ -1,24 +0,0 @@
import ImageArtifactType from '../core/ImageArtifactType'
export function encodeImage(image) {
const artifacts = [
ImageArtifactType.SMALL,
ImageArtifactType.MEDIUM,
ImageArtifactType.BIG,
ImageArtifactType.LARGE,
ImageArtifactType.ORIGIN,
ImageArtifactType.ORIGINAL,
ImageArtifactType.FACEBOOK = 'fb'
].reduce((acc, size) => {
return {
...acc,
[size]: image.getPicture(size),
}
}, {})
return {
artifacts,
hash: image.hash,
file: image.file,
}
}
-12
View File
@@ -1,12 +0,0 @@
import { encodeImage } from './image'
export function encodePage(page) {
return {
id: page.id,
title: page.title,
url: page.url,
data: page.data,
preview: encodeImage(page.preview),
tokens: page.tokens,
}
}
-13
View File
@@ -1,13 +0,0 @@
import ImageArtifactType from '../core/ImageArtifactType'
import { encodeImage } from './image'
const profilePicture = profile => profile.picture.getPicture(ImageArtifactType.BIG)
export function encodePerson(person) {
return {
...person,
shortName: person.shortName(),
name: person.splitName(),
picture: profilePicture(person),
preview: encodeImage(person.picture),
}
}
-63
View File
@@ -1,63 +0,0 @@
import Data from './Data'
import Image from './Image'
import ImageArtifactType from './ImageArtifactType'
import { find, findOne } from '../lib/store'
const previewTypes = [
ImageArtifactType.SMALL,
ImageArtifactType.MEDIUM,
ImageArtifactType.BIG,
ImageArtifactType.ORIGIN,
]
const store = () => Data.getStore('Album')
export default class Album {
static async find(query, options = {}) {
const items = await find(store(), query, options as any)
return Promise.all(items.map(processAlbum))
}
static async findById(id) {
const item = await findOne(store(), { id })
return !item
? null
: processAlbum(item)
}
}
const previewFromImage = (imgs = []) => imgs.length
? imgs[0]
: null
const processAlbum = async album => {
let preview = {}
// {
// data: [
// {
// url: null,
// width: 0,
// height: 0,
// }
// ]
// }
const previewImageId = album.preview ? album.preview : previewFromImage(album.images)
if (previewImageId) {
const image = await Image.findById(previewImageId)
if (image) {
// const imageArtifacts = image.findArtifact(previewTypes)
// if (imageArtifacts) {
// preview = imageArtifacts
// }
preview = image.getPicture(ImageArtifactType.SMALL)
}
}
return {
...album,
preview,
url: `/album/${album.id}`,
}
}
-134
View File
@@ -1,134 +0,0 @@
import Data from './Data'
import Image from './Image'
import Config from './Config'
import { find, findOne, total } from '../lib/store'
const store = () => Data.getStore<Article>('Article')
function make(C) {
return x => new C(x)
}
export default class Article {
static async find(query, options = {}): Promise<Article[]> {
const items = await find(store(), query, options as any)
return Promise.all(items.map(processArticle))
}
static async findById(id) {
const item = await findOne(store(), { id })
return !item
? null
: processArticle(item)
}
static async total(query = {}) {
return total(store(), query)
}
static async findPinned() {
const now = new Date()
const query = { until: { $gte: now } }
return Article.find(query, {
sort: { date: -1 },
})
}
public id: any
public images: any
public post: any
public folder: any
public date: any
public title: any
public until: any
public tags: any
public content: any
public hash: any
public type: any
public origin: any
public file: any
public version: any
public preview: any
public url: any
constructor(data) {
this.id = data.id
this.images = data.images
this.post = data.post
this.folder = data.folder
this.date = data.date
this.title = data.title
this.until = data.until
this.tags = (data.tags || []).map(make(Tag))
this.content = data.content
this.hash = data.hash
this.type = data.type
this.origin = data.origin
this.file = data.file
this.version = data.version
this.preview = data.preview
this.url = `/article/${this.id}`
}
plain() {
return {
id: this.id,
images: this.images,
post: this.post,
folder: this.folder,
date: this.date,
title: this.title,
until: this.until,
tags: this.tags,
content: this.content,
hash: this.hash,
type: this.type,
origin: this.origin,
file: this.file,
version: this.version,
preview: this.preview,
url: this.url,
}
}
}
class Tag {
public name: string
constructor(tag) {
this.name = tag;
}
}
const previewFromImage = (imgs = []) => imgs.length
? imgs[0]
: null
async function resolveDefaultPreview() {
const config = await Config.findConfig()
if (!config) return null
return Image.findByFile(config.articleCardDefaultPreview)
}
async function processArticle(article) {
let preview = null
const previewId = article.preview
? article.preview
: previewFromImage(article.images)
if (previewId) {
preview = await Image.findById(previewId)
} else {
preview = await resolveDefaultPreview()
}
return new Article({
...article,
preview,
})
}
-42
View File
@@ -1,42 +0,0 @@
import Data from './Data'
import { findOne } from '../lib/store'
const store = () => Data.getStore('Settings')
export default class Config {
static async findConfig() {
const config = await Config.findById('settings')
return config || new Config({} as any)
}
static async findById(id: string) {
const data = await findOne(store(), { id })
if (!data) return null
return new Config(data)
}
public hash: any
public file: any
public server: any
public articlesPerPage: any
public collectiveOrder: any
public articleCardDefaultPreview: any
public collectiveImage: any
public redirect: any
constructor({ hash, file, ...data }) {
this.hash = hash
this.file = file
this.server = data.server
this.articlesPerPage = data.articlesPerPage || 5
this.collectiveOrder = data.collectiveOrder || []
this.articleCardDefaultPreview = data.articleCardDefaultPreview
this.collectiveImage = data.collectiveImage
const redirect = data.redirect || {}
this.redirect = new Map(Object
.entries(redirect)
)
}
}
-18
View File
@@ -1,18 +0,0 @@
import { Collection } from 'mongodb'
import * as db from './db'
const store = new Map<string, Collection>()
export default class Data {
static setStore(key: string, collection: Collection) {
store.set(key, collection)
}
static getStore<T>(key: string): Collection<T> {
return store.get(key)
}
static getCollection(name: string): Collection {
return db.collection(name)
}
}
-68
View File
@@ -1,68 +0,0 @@
import Data from './Data'
import Image from './Image'
import { find, findOne } from '../lib/store'
const store = () => Data.getStore('Document')
export default class Document {
static async find(query, options = {}) {
const items = await find(store(), query, options as any)
return Promise.all(items.map(processDocument))
}
static async findById(id) {
const data = await findOne(store(), { id })
if (!data) return null
return processDocument(data)
}
public id: any
public hash: any
public file: any
public fileInfo: any
public type: any
public title: any
public category: any
public url: any
public preview: any
public viewUrl: any
constructor(data) {
this.id = data.id
this.hash = data.hash
this.file = data.file
// In the future: use fileInfo only
this.fileInfo = data.fileInfo
? new DocumentFile(data.fileInfo)
: new DocumentFile(data.file)
this.type = data.type
this.title = data.title
this.category = data.category
this.url = data.url
this.preview = data.preview
this.viewUrl = `/document/${this.id}`
}
}
class DocumentFile {
public name: any
public size: any
constructor(data) {
this.name = data.name
this.size = data.size
}
}
const processDocument = async data => {
const imageId = data.preview
const preview = await Image.findById(imageId)
return new Document({
...data,
preview,
})
}
-81
View File
@@ -1,81 +0,0 @@
import Data from './Data'
import ImageArtifactType from './ImageArtifactType'
import { findOne } from '../lib/store'
import { mapOf } from '../server/lib'
const store = () => Data.getStore('Image')
export default class Image {
static async findById(id) {
const data = await findOne(store(), { _id: id })
if (!data) return null
const artifacts = data.data
return new Image({ ...data, artifacts })
}
static async findByFile(file: string) {
const data = await findOne(store(), { file })
if (!data) return null
const artifacts = data.data
return new Image({ ...data, artifacts })
}
public hash: any
public file: any
public artifacts: any
constructor({ hash, file, artifacts }) {
this.hash = hash
this.file = file
this.artifacts = mapOf(ImageArtifact, artifacts)
}
getArtifact(size) {
return this.artifacts.get(size)
}
findArtifact(sizes) {
for (let size of sizes) {
const a = this.getArtifact(size)
if (a) return a
}
return null
}
getPicture(size) {
const retinaSize = ImageArtifactType.retina(size)
const a = this.getArtifact(size)
const a2 = this.getArtifact(retinaSize)
const srcset = !a2
? []
: [{
url: a2.url,
density: ImageArtifactType.RETINA_DENSITY,
}]
return {
src: a.url,
width: a.width,
height: a.height,
set: srcset,
}
}
}
class ImageArtifact {
public url: any
public size: any
public width: any
public height: any
constructor({ url, size, width, height }) {
this.url = url
this.size = size
this.width = width
this.height = height
}
}
-104
View File
@@ -1,104 +0,0 @@
import Data from './Data'
import { find as storeFind, findOne, total } from '../lib/store'
import Image from './Image'
import Config from './Config'
const store = () => Data.getStore('Page')
export default class Page {
static async find(query, options = {}): Promise<Page[]> {
const items = await storeFind(store(), query, options as any)
return Promise.all(items.map(processPage))
}
static async findById(id) {
const item = await findOne(store(), { id })
return !item
? null
: processPage(item)
}
static async findByUrl(url) {
const item = await findOne(store(), { url })
return !item
? null
: processPage(item)
}
static async total(query = {}) {
return total(store(), query)
}
public id: any
public hash: any
public file: any
public url: string
public content: any
public title: any
public data: any
public images: any
public documents: any
public preview: any
public tokens: any[]
constructor(data) {
this.id = data.id
this.hash = data.hash
this.file = data.file
this.url = data.url
this.content = data.content
this.title = data.title
this.data = data.data
this.images = data.images
this.documents = data.documents
this.preview = data.preview
this.tokens = data.tokens
}
plain() {
return {
id: this.id,
images: this.images,
documents: this.documents,
data: this.data,
title: this.title,
content: this.content,
hash: this.hash,
file: this.file,
preview: this.preview,
url: this.url,
}
}
}
const previewFromImage = (imgs = []) => imgs.length
? imgs[0]
: null
async function resolveDefaultPreview() {
const config = await Config.findConfig()
if (!config) return null
return Image.findByFile(config.articleCardDefaultPreview)
}
async function processPage(article) {
let preview = null
const previewId = article.preview
? article.preview
: previewFromImage(article.images)
if (previewId) {
preview = await Image.findById(previewId)
} else {
preview = await resolveDefaultPreview()
}
return new Page({
...article,
preview,
})
}
-87
View File
@@ -1,87 +0,0 @@
import Data from './Data'
import Image from './Image'
import { find, findOne } from '../lib/store'
const store = () => Data.getStore('Teacher')
export default class Teacher {
static async find(query, options = {}) {
const items = await find(store(), query, options as any)
return Promise.all(items.map(processProfile))
}
static async findById(id) {
const data = await findOne(store(), { id })
if (!data) return null
return processProfile(data)
}
public id: any
public post: any
public file: any
public edu: any
public picture: any
public preview: any
public diploma: any
public position: any
public name: any
public status: any
public hash: any
public url: any
constructor(data) {
this.id = data.id
this.post = data.post
this.file = data.file
this.edu = data.edu
this.picture = data.picture
this.preview = data.preview
this.diploma = data.diploma
this.position = data.position
this.name = data.name
this.status = data.status
this.hash = data.hash
this.url = `/teacher/${this.id}`
}
/**
*
* "First Middle Last" -> "F. M. Last"
*
* @returns {string}
*/
shortName() {
const f = i => i.replace(/^(.).+/, '$1')
const [first, middle, last] = this.splitName()
return `${f(first)}. ${f(middle)}. ${last}`
}
/**
*
* "First Middle Last" -> ["First", "Middle", "Last"]
*
* @returns {Array|{index: number, input: string}}
*/
splitName() {
const name = this.name
const m = /(.+)\s(.+)\s(.+)/.exec(name)
return m.slice(1)
}
}
const processProfile = async profile => {
const imageId = profile.picture
const previewId = profile.preview
const picture = await Image.findById(imageId)
const preview = await Image.findById(previewId)
return new Teacher({
...profile,
picture,
preview,
})
}
-48
View File
@@ -1,48 +0,0 @@
import Data from './Data'
import Page from './Page'
import Article from './Article'
const Album = require('./Album')
const Teacher = require('./Teacher')
const Document = require('./Document')
const Image = require('./Image')
import Settings from './Config'
const getConfig = require('next/config').default
const { MongoClient, ObjectId } = require('mongodb')
var db
export async function connect() {
if (db) {
return db
}
const mongoUri = getConfig().serverRuntimeConfig.dbUri
const connection = await MongoClient.connect(mongoUri)
db = init(connection)
return db
}
export function collection(name) {
return db.collection(name)
}
export function id(i) {
if (typeof i === 'string') return ObjectId(i)
else if (i instanceof ObjectId) return i
else if (i instanceof Object) return '_id' in i ? ObjectId(i._id) : null
return null
}
function init(db) {
console.log('INIT DB')
Data.setStore('Page', db.collection('pages'))
Data.setStore('Article', db.collection('articles'))
Data.setStore('Album', db.collection('albums'))
Data.setStore('Image', db.collection('images'))
Data.setStore('Teacher', db.collection('collective'))
Data.setStore('Document', db.collection('documents'))
Data.setStore('Settings', db.collection('settings'))
return db
}
-19
View File
@@ -1,19 +0,0 @@
import {c} from '../core/db';
const PAGES = 'pages';
export async function getPageUrls() {
return await c(PAGES)
.find({}, {url: 1})
.toArray();
}
/**
* Find a person by it's id
*
* @param {string} url
* @returns {Promise|*}
*/
export async function getPage(url) {
return await c(PAGES).findOne({url: url});
}
-20
View File
@@ -1,20 +0,0 @@
/**
*
* @param redirectMap
* [{String url, String redirect}, ...]
* @returns {*}
*/
function redirect(redirectMap) {
return async (ctx, next) => {
const path = ctx.request.path
if (redirectMap.has(path)) {
const url = redirectMap.get(path)
ctx.redirect(url)
} else {
await next()
}
}
}
module.exports = redirect
-20
View File
@@ -1,20 +0,0 @@
// import { MongoClient } from 'mongodb';
// const { connect, collection } = require('../../src/core/db')
import {collection, connect} from '../core/db'
// const client = new MongoClient(process.env.MONGODB_URI, { useNewUrlParser: true });
export const withCollection = handler => async (req, res) => {
await connect()
req.collection = collection
// if (!client.isConnected()) {
// return client.connect().then(() => {
// req.db = client.db('nextjsmongodbapp');
// return handler(req, res);
// });
// }
// req.db = client.db('nextjsmongodbapp');
return handler(req, res)
}
-6
View File
@@ -1,6 +0,0 @@
import { withCollection } from './withCollection'
import { NextApiRequest, NextApiResponse } from 'next'
export type Handler = (req: NextApiRequest, res: NextApiResponse) => void
export const withMiddleware = (handler: Handler) => withCollection(handler)
-22
View File
@@ -1,22 +0,0 @@
const courses = {
painting: ['Живопись', ''],
drawing: ['Рисунок', '/courses/drawing'],
sculpting: ['Скульптура', ''],
sculpture: ['Скульптура', ''],
ceramic: ['Керамика', '/courses/ceramics'],
ceramics: ['Керамика', '/courses/ceramics'],
composition: ['Композиция', ''],
'easel-composition': ['Станковая композиция', ''],
dpi: ['ДПИ', ''],
'art-talks': ['Беседа по искусству', ''],
history: ['История искусства', '/courses/art-history'],
cg: ['Комп. графика', '/courses/cg'],
}
export function getCourse(id) {
const course = id in courses ? courses[id] : null
if (!course) return null
const [title, url] = course
return {id, title, url}
}
-44
View File
@@ -1,44 +0,0 @@
export const autumnMonth = 8;
export const springMonth = 0;
export function scheduleDate(schedule){
let {period, semester} = schedule;
let i = semester === 'spring' ? 1 : 0;
let year = getPeriod(period)[i];
return new Date(
year,
i ? springMonth : autumnMonth,
1
);
}
/**
*
* f("2012-2015") -> [2012, 2015]
* f(["2012", "2015"]) -> [2012, 2015]
* f([2012, 2015]) -> [2012, 2015]
*
* @param i
* @returns {*}
*/
export function getPeriod(i){
if (typeof i === 'string') return getPeriod(i.split('-'));
return i.map(Number);
}
/**
*
* f("2012-2015") -> "2012-2015"
* f(["2012", "2015"]) -> "2012-2015"
* f([2012, 2015]) -> "2012-2015"
*
* @param i
* @returns {*}
*/
export function getPeriodString(i) {
return getPeriod(i)
.join('-')
}
-19
View File
@@ -34,22 +34,3 @@ export function wrapInitialProps(fn: (ctx: NextPageContext) => void) {
export function createApiUrl(path: string) {
return `https://api.tmshv.com/hudozka${path}`
}
function absoluteUrl(req, defaultLocalhost) {
let protocol = 'https:'
let host = req
? (req.headers['x-forwarded-host'] || req.headers['host'])
: window.location.host
host = host || defaultLocalhost
if (host.indexOf('localhost') > -1) {
if (defaultLocalhost) host = defaultLocalhost
protocol = 'http:'
}
const origin = protocol + '//' + host
return {
protocol,
host,
origin,
}
}
-71
View File
@@ -1,71 +0,0 @@
import Article from '../core/Article'
import ImageArtifactType from '../core/ImageArtifactType'
import { sortBy } from '../utils/sort'
import { timestamp } from '../lib/date'
import { encodeImage } from '../api/image'
export const sortArticleByDate = sortBy(
x => timestamp(new Date(x.date))
)
export async function findArticlesNin(nin, skip, limit, sort) {
const query = {
_id: { $nin: nin }
}
return Article.find(query, {
sort,
skip,
limit,
})
}
export async function findArticles(page: number, pageSize: number) {
const limit = pageSize
const skip = (page - 1) * pageSize
const pinnedArticles = page === 1
? await Article.findPinned()
: []
const total = await Article.total()
const totalPages = Math.ceil(total / pageSize)
const id = i => i._id
const pinnedIds = pinnedArticles.map(id)
const articles = await findArticlesNin(pinnedIds, skip, limit, { date: -1 })
const prevPage = page > 1
? page - 1
: null
const nextPage = page < totalPages
? page + 1
: null
const items = [
...pinnedArticles.sort(sortArticleByDate),
...articles
]
.map(x => x.plain())
.map(x => ({
...x,
preview: !x.preview ? null : (
x.preview.getPicture(ImageArtifactType.MEDIUM)
)
}))
return {
items,
prevPage,
nextPage,
totalPages,
}
}
export function encodeArticle(article) {
return {
...article,
preview: encodeImage(article.preview),
}
}
-18
View File
@@ -1,18 +0,0 @@
const { collection } = require('../core/db')
// import { collection } from '../core/db'
export async function getCollective(query = {}) {
return await collection('collective')
.find(query)
.toArray();
}
/**
* Find a person by it's id
*
* @param id
* @returns {Promise|*}
*/
export async function getPerson(id) {
return await collection('collective').findOne({ id: id });
}
-14
View File
@@ -1,14 +0,0 @@
/**
*
* {a: {}, b: {}, ...} -> Map (a: Class, b: Class)
*
* @param Class
* @param object
*/
export function mapOf(Class, object) {
return Object
.entries(object)
.reduce((map, i) => (
map.set(i[0], new Class(i[1]))
), new Map())
}
-149
View File
@@ -1,149 +0,0 @@
// import {collection} from '../core/db'
// const {collection} = require('../core/db')
import {createMap} from '../utils/common'
import {getCollective} from './collective'
import {scheduleDate, getPeriod as schedulePeriod, getPeriodString} from '../models/schedule'
import {getCourse} from '../models/course'
const last = require('../lib/array').last
const sortBy = require('../lib/sort').sortBy
const SCHEDULES = 'schedules'
export async function findSchedule(collection, period, semester) {
const schedule = await collection(SCHEDULES).findOne({
$or: [
{period: period},
{period: schedulePeriod(period)}
],
semester: semester
})
return schedule ? migrate(schedule) : null
}
async function findAllScheduleParams() {
const schedules = await collection(SCHEDULES)
.find({}, {
period: 1,
semester: 1,
_id: 0,
})
.toArray()
return schedules
.map(i => ({
...i,
period: schedulePeriod(i.period),
}))
.sort(sortBy(
i => scheduleDate(i).getTime(),
true,
))
}
async function findDefaultScheduleParams() {
const schedules = await findAllScheduleParams()
return last(schedules
.map(i => ({
...i,
period: getPeriodString(i.period),
}))
)
}
function text({semester, period}) {
const word = semester => [['spring', 'Весна'], ['autumn', 'Осень']]
.find(i => i[0] === semester)
[1]
const periodIndex = semester === 'spring' ? 1 : 0
const year = period[periodIndex]
return `${word(semester)} ${year} года`
}
async function migrate(schedule) {
const versions = {
'1.0': migrate10to20,
'2.0': migrate20to30,
}
const version = schedule.version
const update = versions[version]
return version in versions ? migrate(update(schedule)) : schedule
}
function migrate10to20(schedule) {
const dayNames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
const time = time => time
.map(i => i.split(' '))
const week = days => days.reduce((week, lesson, index) => {
if (lesson) {
const day = dayNames[index]
week[day] = [Object.assign(lesson, {
time: time(lesson.time)
})]
}
return week
}, {})
return Object.assign(schedule, {
version: '2.0',
period: schedulePeriod(schedule.period),
groups: schedule.schedule
.map(group => ({
name: group.group,
time: group.time,
week: week(group.week)
}))
})
}
async function migrate20to30(schedule) {
const days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat']//, 'sun']
const persons = await getCollective()
const person = createMap(i => i.id, persons)
const week = week => days
.map(day => week[day] || [])
.map(lessons => lessons.map(lesson))
const lesson = i => ({
time: i.time,
course: getCourse(i.lesson),
teacher: person.has(i.teacher) ? teacher(i.teacher) : teacherDummy(i.teacher)
})
const teacher = id => ({
id: id,
url: `/teacher/${id}`,
name: personName(id)
})
const teacherDummy = name => ({
id: name,
url: null,
name: name
})
const personName = id => person.has(id) ? person.get(id).name : null
return Object.assign(schedule, {
version: '3.0',
groups: schedule.groups
.map(group => ({
name: group.name,
time: group.time,
week: week(group.week)
}))
})
}
// exports.findSchedule = findSchedule
// exports.findAllScheduleParams = findAllScheduleParams
// exports.findDefaultScheduleParams = findDefaultScheduleParams
// exports.text = text
-17
View File
@@ -1,17 +0,0 @@
import {getPeriod} from '../../src/models/schedule';
describe('models', () => {
describe('schedule.js', () => {
describe('getPeriod', () => {
it('should accept a string and return an array', () => {
getPeriod('2016-2017').should.be.Array;
});
it('should accept a string "XXXX-YYYY" and return an array [XXXX, YYYY]', () => {
const sample = '2016-2017';
const result = getPeriod(sample);
result.should.be.eql([2016, 2017]);
});
});
});
});