All files / lib/models backlink.ts

79.03% Statements 49/62
63.64% Branches 7/11
81.25% Functions 13/16
78.95% Lines 45/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166                                                16x 16x   16x             16x                                                             16x       16x 6x       6x     16x 6x           6x     16x 9x   9x     9x   9x     16x 84x 78x     6x   6x   6x 6x   6x   3x               6x 6x     16x 1x 1x   1x 6x   1x       1x   1x   15x 3x   3x 3x   3x   3x               3x 3x         16x   16x    
import Crowi from 'server/crowi'
import { Types, Document, Model, Schema, model } from 'mongoose'
import Debug from 'debug'
import LinkDetector from '../util/linkDetector'
import { PageDocument } from './page'
 
export interface BacklinkDocument extends Document {
  _id: Types.ObjectId
  page: Types.ObjectId | any
  fromPage: Types.ObjectId | any
  fromRevision: Types.ObjectId | any
  updatedAt: Date
}
 
export interface BacklinkModel extends Model<BacklinkDocument> {
  findByPageId(pageId: Types.ObjectId, limit: any, offset: any): Promise<BacklinkDocument[]>
  removeByPageId(pageId: Types.ObjectId): any
  removeBySavedPage(savedPage: any)
  createByParameters(parameters: any): Promise<BacklinkDocument>
  createBySavedPage(savedPage: any): Promise<BacklinkDocument[]>
  createByAllPages(): Promise<BacklinkDocument[][]>
}
 
export default (crowi: Crowi) => {
  const debug = Debug('crowi:models:backlink')
  const linkDetector = LinkDetector(crowi)
 
  const backlinkSchema = new Schema<BacklinkDocument, BacklinkModel>({
    page: { type: Schema.Types.ObjectId, ref: 'Page', index: true },
    fromPage: { type: Schema.Types.ObjectId, ref: 'Page' },
    fromRevision: { type: Schema.Types.ObjectId, ref: 'Revision' },
    updatedAt: { type: Date, default: Date.now, index: true },
  })
 
  backlinkSchema.statics.findByPageId = async function(pageId, limit, offset) {
    limit = limit || 10
    offset = offset || 0
 
    limit = parseInt(limit, 10)
    offset = parseInt(offset, 10)
 
    const conditions = { page: pageId }
    const projection = { fromPage: 1, fromRevision: 1, updatedAt: 1 }
    const options = { limit, skip: offset, sort: { updatedAt: -1 } }
 
    const backlinks = await Backlink.find(conditions, projection, options)
      .populate('fromPage')
      .populate('fromRevision')
 
    // populate author
    const populateOptions = {
      path: 'fromRevision.author',
      model: 'User',
      select: {
        username: 1,
        name: 1,
        image: 1,
      },
    }
 
    const populatedBacklinks = await Backlink.populate(backlinks, populateOptions)
 
    return populatedBacklinks
  }
 
  backlinkSchema.statics.removeByPageId = function(pageId) {
    return Backlink.remove({ fromPage: pageId })
  }
 
  backlinkSchema.statics.removeBySavedPage = async function(savedPage) {
    const conditions = {
      fromPage: savedPage._id,
    }
 
    await Backlink.remove(conditions)
  }
 
  backlinkSchema.statics.createByParameters = async function(parameters) {
    const data = {
      page: parameters.page,
      fromPage: parameters.fromPage,
      fromRevision: parameters.fromRevision,
      updatedAt: Date.now(),
    }
    return Backlink.create(data)
  }
 
  const convertLinksToPageIds = async (page, { paths, objectIds }) => {
    const Page = crowi.model('Page')
 
    let ids = await Promise.all([...paths.map(path => Page.isExistByPath(path)), ...objectIds.map(id => Page.isExistById(id))])
 
    // Make unique and remove own page
    ids = ids.filter((id, index, array) => array.indexOf(id) === index && id.toString() !== page._id.toString() && id !== false)
 
    return ids
  }
 
  backlinkSchema.statics.createBySavedPage = async function(savedPage) {
    if (!(savedPage.revision && savedPage.revision.body)) {
      throw new Error('no revision/body in savedPage')
    }
 
    const body = savedPage.revision.body
 
    await Backlink.removeBySavedPage(savedPage)
 
    const links = linkDetector.search(body)
    const ids = await convertLinksToPageIds(savedPage, links)
 
    const backlinks = await Promise.all(
      ids.map(id =>
        Backlink.createByParameters({
          page: id,
          fromPage: savedPage._id,
          fromRevision: savedPage.revision._id,
        }),
      ),
    )
 
    debug('All backlinks saved')
    return backlinks
  }
 
  backlinkSchema.statics.createByAllPages = async function() {
    const Page = crowi.model('Page')
    const Revision = crowi.model('Revision')
 
    const pages = await Page.find({}).select('_id revision')
    const latestRevisionIds = pages.map(({ revision }) => revision)
 
    const revisions = await Revision.find({ _id: { $in: latestRevisionIds } }).and({
      $or: [{ body: linkDetector.getLinkRegexp() }, { body: linkDetector.getPathRegexps()[0] }, { body: linkDetector.getPathRegexps()[1] }],
    } as any)
 
    await Backlink.remove({})
 
    return Promise.all(
      revisions.map(async ({ _id: revisionId, body }) => {
        const page = pages.find(({ revision }) => revision.toString() === revisionId.toString()) as PageDocument
        const pageId = page._id
 
        const links = linkDetector.search(body)
        const ids = await convertLinksToPageIds(page, links)
 
        const backlinks = await Promise.all(
          ids.map(id =>
            Backlink.createByParameters({
              page: id,
              fromPage: pageId,
              fromRevision: revisionId,
            }),
          ),
        )
 
        debug('All backlinks saved')
        return backlinks
      }),
    )
  }
 
  const Backlink = model<BacklinkDocument, BacklinkModel>('BackLink', backlinkSchema)
 
  return Backlink
}