/* Created by Songzhou Yang */

const rp = require('request-promise')
const ci = require('cheerio')

class LearnHelperUtil {
  constructor(username, password) {
    this.username = username
    this.password = password
    this.j = rp.jar()
    this.prefix = 'https://learn.tsinghua.edu.cn'
  }

  async login() {
    await rp({
      method: 'POST',
      uri: `${this.prefix}/MultiLanguage/lesson/teacher/loginteacher.jsp`,
      form: {
        userid: this.username,
        userpass: this.password
      },
      jar: this.j
    })
  }

  async getCourseList() {
    try {
      const $ = await rp({
        method: 'GET',
        uri: `${this.prefix}/MultiLanguage/lesson/student/MyCourse.jsp?language=cn`,
        jar: this.j,
        transform: (body) => {
          return ci.load(body, {decodeEntities: false})
        }
      })

      const courses = []
      $('.info_tr, .info_tr2').each((i, ele) => {
        const $this = $(ele)
        const course = {}

        course['coursename'] = $this.find('a').text().trim()

        const url = $this.find('a').attr('href')
        if (url.indexOf('learn.cic.tsinghua.edu.cn') !== -1) {
          course['courseid'] = url.split('-').slice(-2).join('-')
        } else {
          course['courseid'] = url.split('=').slice(-1)[0]
        }

        const infos = ['unsubmittedoperations', 'unreadnotice', 'newfile']
        $this.find('.red_text').each((i, ele) => {
          course[infos[i]] = parseInt($(ele).text())
        })

        courses[i] = course
      })
      return courses
    } catch (e) {
      throw e
    }
  }
}

module.exports = LearnHelperUtil

@@ -221,17 +221,23 @@
    this.
-j
+cookies
  = rp.ja
@@ -527,17 +527,23 @@
 r: this.
-j
+cookies
 %0A    %7D)%0A
@@ -736,17 +736,23 @@
 r: this.
-j
+cookies
 ,%0A      
@@ -1538,16 +1538,16 @@
      %7D)%0A
-
       re
@@ -1600,16 +1600,920 @@
    %7D%0A  %7D
+%0A%0A  async getFiles(courseID) %7B%0A    try %7B%0A      const $ = await rp(%7B%0A        method: 'GET',%0A        uri: %60$%7Bthis.prefix%7D/MultiLanguage/lesson/student/download.jsp?course_id=$%7BcourseID%7D%60,%0A        jar: this.cookies,%0A        transform: (body) =%3E %7B%0A          return ci.load(body, %7BdecodeEntities: false%7D)%0A        %7D%0A      %7D)%0A%0A      const files = %5B%5D%0A      $('.tr1, .tr2').each((i, ele) =%3E %7B%0A        const $this = $(ele)%0A        const file = %7B%7D%0A%0A        const infos = %5B'sequenceNum', 'title', 'explanation', 'size', 'updatingTime', 'state'%5D%0A        $this.children().each((i, ele) =%3E %7B%0A          file%5Binfos%5Bi%5D%5D = $(ele).text().replace(/&nbsp;/gi, '').trim()%0A        %7D)%0A%0A        file.url = this.prefix + $this.find('a').attr('href')%0A%0A        file.state = file.state !== '' ? 'new' : 'previous'%0A%0A        console.log(file)%0A        files%5Bi%5D = file%0A      %7D)%0A      return files%0A    %7D catch (e) %7B%0A      throw e%0A    %7D%0A  %7D
 %0A%7D%0A%0Amodu

add files crawler