Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
14 kB
2
Indexable
Never
const express = require('express');
const bodyParser = require('body-parser');
const pdfP =require('pdf2json');
const app  =express();
const crypto= require('crypto');
const multer=require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override');
const getStream =require('get-stream')
const mysql = require('mysql2');
app.use(express.json());
app.use(express.urlencoded({extended: true}))
app.use(bodyParser.json());
app.use(bodyParser.raw())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static("./files"))
const path =require('path');
const pdfParse= require("pdf-parse");
const user =require("./models/user");
const pdfjs=require("pdfjs-dist/legacy/build/pdf")

async function getContent(src){
  const doc = await pdfjs.getDocument(src).promise
  const page = await doc.getPage(2)
  return await page.getTextContent()
}

async function getItems(src) {
  const content1 = await getContent(src, 1)
  const items1 = content1.items
  const content2 = await getContent(src, 2)
  const items2 = content2.items
  const content3 = await getContent(src, 3)
  const items3 = content3.items
  const content4 = await getContent(src, 4)
  const items4 = content4.items
  const content5 = await getContent(src, 5)
  const items5 = content5.items
  const content6 = await getContent(src, 6)
  const items6 = content6.items
  const content7 = await getContent(src, 7)
  const items7 = content7.items
  const content8 = await getContent(src, 8)
  const items8 = content8.items
  const content9 = await getContent(src, 9)
  const items9 = content9.items
  var page1 = []
  var page2 = []
  var page3 = []
  var page4 = []
  var page5 = []
  var page6 = []
  var page7 = []
  var page8 = []
  var page9 = []

  for (let i = 0; i < items1.length; i++) {
    if (isThereAnyText(items1[i])) {
      page1.push(items1[i].str)
    }
  }
  for (let i = 0; i < items2.length; i++) {
    if (isThereAnyText(items2[i])) {
      page2.push(items2[i].str)
    }
  }
  for (let i = 0; i < items3.length; i++) {
    if (isThereAnyText(items3[i])) {
      page3.push(items3[i].str)
    }
  }
  for (let i = 0; i < items4.length; i++) {
    if (isThereAnyText(items4[i])) {
      page4.push(items4[i].str)
    }
  }
  for (let i = 0; i < items5.length; i++) {
    if (isThereAnyText(items5[i])) {
      page5.push(items5[i].str)
    }
  }
  for (let i = 0; i < items6.length; i++) {
    if (isThereAnyText(items6[i])) {
      page6.push(items6[i].str)
    }
  }
  for (let i = 0; i < items7.length; i++) {
    if (isThereAnyText(items7[i])) {
      page7.push(items7[i].str)
    }
  }
  for (let i = 0; i < items8.length; i++) {
    if (isThereAnyText(items8[i])) {
      page8.push(items8[i].str)
    }
  }
  for (let i = 0; i < items9.length; i++) {
    if (isThereAnyText(items9[i])) {
      page9.push(items9[i].str)
    }
  }
  let pages = []
  pages.push(page1)
  pages.push(page2)
  pages.push(page3)
  pages.push(page4)
  pages.push(page5)
  pages.push(page6)
  pages.push(page7)
  pages.push(page8)
  pages.push(page9)
  return pages
}
let selam = 'aaa1'
let regex1 = new RegExp(/\d/)
console.log(regex1.test(selam)); // true
console.log("afasfsda")
function isThereAnyText(item) {
  let regex = new RegExp(/[a-z]/i)
  let regex1 = new RegExp(/\d/)
  if (regex.test(item.str) || regex1.test(item.str)) {
    return true
  }
  return false
}

async function getAllInfo(pages) {
  let className = getClassName(pages[0])
  let term = getTerm(pages[1])
  let authorInfo = getAuthorInfo(pages[2])
  let projectSummary = getProjectSummary(pages[8])
  let projectTitle = getProjectTitle(pages[0])
  let consultantInfo = getConsultantInfo(pages[1])
  let juryInfo = getJuryInfo(pages[1])
  let keywords = getKeywords(pages[8])

  let allInfo = []
  allInfo[0] = className
  allInfo[1] = term
  allInfo[2] = authorInfo
  allInfo[3] = projectSummary
  allInfo[4] = projectTitle
  allInfo[5] = consultantInfo
  allInfo[6] = juryInfo
  allInfo[7] = keywords
  return await allInfo
}
function getClassName(page1) {
  console.log(page1[3])
  return page1[3]
}
async function getTerm(page2) {
  let x = page2[page2.length - 1]
  let fallOrSpring = ''
  if (x.substring(3, 5) == '01') {
    fallOrSpring = 'Güz'
  }
  else
    fallOrSpring = 'Bahar'
  let year1 = 0
  year1 = parseInt(x.substring(6, 10)) - 1
  let year2 = String(year1)
  console.log(fallOrSpring + " " + year2 + "-" + x.substring(6, 10))
  let term = fallOrSpring + " " + year2 + "-" + x.substring(6, 10)
  return term
}
async function getAuthorInfo(page3) {
  console.log(page3[page3.length - 3])
  console.log(page3[page3.length - 2].substring(13, page3[page3.length - 2].length))
  console.log(page3[page3.length - 3].substring(5, 6))
  let educationType = ''
  if (page3[page3.length - 3].substring(5, 6) == '1') {
    educationType = 'Birinci Öğretim'
  }
  else
    educationType = 'İkinci Öğretim'
  let authorInfo = page3[page3.length - 2].substring(13, page3[page3.length - 2].length) + ' ' + page3[page3.length - 3] + ' ' + educationType
  console.log(authorInfo)
  return authorInfo
}
async function getProjectSummary(page9) {
  console.log(page9)
  let i = 0
  while (page9[i] != 'ÖZET') {
    i++
  }
  console.log(i)
  let summary = ''
  let summary1 = []
  i = i + 1
  while (page9[i] != 'Anahtar ') {
    summary1.push(page9[i])
    i++
  }
  summary = summary1.join(' ')
  console.log(summary)
  return summary
}
async function getProjectTitle(page1) {
  console.log(page1[4])
  return page1[4]
}

async function getConsultantInfo(page2) {
  console.log(page2[6])
}
async function getJuryInfo(page2) {
  console.log(page2[10])
  console.log(page2[15])
}
async function getKeywords(page9) {
  let i = 0
  while (page9[i] != 'Kelimeler: ') {
    i++
  }
  i++
  let keywords = ''
  for (i; i < page9.length; i++) {
    keywords += page9[i]
  }
  console.log(keywords)
  let keywords1 = []
  keywords1 = keywords.split(', ')
  keywords1[keywords1.length - 1] = keywords1[keywords1.length - 1].slice(0, -1)
  console.log(keywords1[keywords1.length - 1])
  console.log(keywords1)
  return keywords1
}
let re;
  var connection = mysql.createConnection({
    connectionLimit:10,
    host: 'localhost',
    user: 'root',
    password: '3005',
    database: 'lib'
  });
  connection.connect(function(error){
    if(error){
      console.log("err")
    }
else{
  console.log('connected')
}  })


var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'models/files');
  },
  filename: function (req, file, cb) {
    var id = file.originalname ;
    cb(null, id);
  }
});
var upload = multer({ storage: storage })



    app.get('/',(req,res)=>{
        res.sendFile(path.join(__dirname,'index.html'));
    });


    app.get('/register',(req,res)=>{
        res.sendFile(path.join(__dirname,'pass.html'));
    });
    app.get('/user',(req,res)=>{
     
      res.sendFile(path.join(__dirname,'user.html'));
  });
  app.get('/admin',(req,res)=>{
    res.sendFile(path.join(__dirname,'admin.html'));
});
var ty,ty1,sr,sr1

app.post("/user", upload.single('file'), async (req, res, next) => {
  ty = req.body.ty
  console.log(ty)
  const file = req.file

  const allInfo = await getItems(file.destination+"/"+file.filename).then(pages => getAllInfo(pages))
  console.log(allInfo)
  console.log('AA')
  
  var sql = "INSERT INTO `files`( `file_name`,`author`,`subject`,`summary`,`year`,`project_name`,`keywords`,`mentor`,`jury`) VALUES (?,?,?,?,?,?,?,?,?)";
  connection.query(sql, [req.file.originalname,allInfo[2],allInfo[0],allInfo[3],allInfo[1],allInfo[4],allInfo[7],allInfo[5],allInfo[6]], function (err, result) {
    if (err) {
      console.log("error")
    }
  })
  res.redirect('/user')
});
 


   app.post("/submit", (req, res, next) => {

    if(req.body.password==" "&& req.body.name==" "){
        return res.status(500).json({
           message:"Make sure there isn't any empty field"
          });
    }
   else if(req.body.password==""|| req.body.name==""){
        return res.status(500).json({
           message:"Make sure there isn't any empty field"
          });
    }
  else{ connection.query('SELECT * FROM `user`' , (err, rows) => {
        if (err) {
      console.log("Error")
      
        }
        else{
          console.log("success")
          for(let i=0;i<rows.length;i++){
            if(rows[i].username==req.body.name && rows[i].password==req.body.password && rows[i].type==req.body.type){
            if (req.body.type=='admin'  ) {
              res.redirect('/admin')}
              else if (req.body.type=='user'  ) {
                re=req.body.name
               res.redirect('/user')
            
            }}
            else {
                
                 res.sendFile(path.join(__dirname,'msg.html'))
                   }} }
                      
                    }) } 
                    })
                    
 app.post("/changepassword", (req, res) => {

               if(req.body.oldP==""|| req.body.username==""|| req.body.email==""||req.body.newP==""){
                       return res.status(500).json({
                          message:"Make sure there isn't any empty field"
                         });
                   }
                   else{
                  connection.query('SELECT * FROM `user`' , (err, rows) => {
                    
                        for(let i=0;i<rows.length;i++){
                          if(rows[i].username==req.body.username && rows[i].email==req.body.email && rows[i].password==req.body.oldP && rows[i].type==req.body.type){
                        
                   const query='UPDATE `user` SET  `password`=? where `username`=?'
                   connection.query(query,[req.body.newP,rows[i].username], (err, rows) => {
                          if(err){
                            console.log("error")}
                            else{
                              console.log("success")
                           } })
                                return res.status(500).json({
                                  message:"Password changed successfully!",})} 
                            else{
                                  return res.json({
                                    message:"Information entered is not correct!",}) 
                                 }
                      
                      }})}})
    
  app.get('/files',(req,res,next)=>{
                          let a                     
                         connection.query('SELECT * FROM `files`' , (err, rows) => {
                             if (err) {
                           console.log("Error")
                           
                             }
                             else{
                               console.log("success")
                                 a= JSON.stringify(rows)
                       
                           }const  t=JSON.parse(a) 
                            
                           res.json(t) 
                         })  })

    app.get("/search", (req, res, next) => { 
     
      if(sr="author"){
        var sql = "SELECT  * FROM `files` where `author`=? ";
         connection.query(sql ,[sr], (err, rows) =>  {
          if(err){
            console.log("error1")
          }
           else{console.log("success1")
          a= JSON.stringify(rows)
        }const  t=JSON.parse(a) 
        console.log(t)
         res.json(t) 
      })
      }
      else  if(sr=='Project Name'){
        var sql = "SELECT  * FROM `files` where `project_name`=? ";
         connection.query(sql ,[sr], (err, rows) =>  {
          if(err){
            console.log("error1")
          }
           else{console.log("success1")
          a= JSON.stringify(rows)
        }const  t=JSON.parse(a) 
        console.log(t)
         res.json(t) 
      })
      }
      else  if(sr="Subject"){
        var sql = "SELECT  * FROM `files` where `subject`=? ";
         connection.query(sql ,[sr], (err, rows) =>  {
          if(err){
            console.log("error1")
          }
           else{console.log("success1")
          a= JSON.stringify(rows)
        }const  t=JSON.parse(a) 
        console.log(t)
         res.json(t) 
      })
      }
      else  if(sr="Keywords"){
        var sql = "SELECT  * FROM `files` where `keywords`=? ";
         connection.query(sql ,[sr], (err, rows) =>  {
          if(err){
            console.log("error1")
          }
           else{console.log("success1")
          a= JSON.stringify(rows)
        }const  t=JSON.parse(a) 
        console.log(t)
         res.json(t) 
      })
      }
      else  if(sr="Program Year"){
        var sql = "SELECT  * FROM `files` where `year`=? ";
         connection.query(sql ,[sr], (err, rows) =>  {
          if(err){
            console.log("error1")
          }
           else{console.log("success1")
          a= JSON.stringify(rows)
        }const  t=JSON.parse(a) 
        console.log(t)
         res.json(t) 
      })
      }
      else  if(sr1="Subject"){
        var sql = "SELECT  * FROM `files` where `year`=?,`subject`=? ";
         connection.query(sql ,[sr,sr1], (err, rows) =>  {
          if(err){
            console.log("error1")
          }
           else{console.log("success1")
          a= JSON.stringify(rows)
        }const  t=JSON.parse(a) 
        console.log(t)
         res.json(t) 
      })
      }
                        });   
                                                                         
   app.listen(3000)