12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528 |
- package student
- import (
- "bufio"
- "bytes"
- "encoding/base64"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "io/ioutil"
- "math/rand"
- "net/http"
- "os"
- "ouchn/config"
- "regexp"
- "runtime"
- "strconv"
- "strings"
- "sync"
- "time"
- "github.com/tebeka/selenium/chrome"
- "github.com/google/uuid"
- "github.com/go-vgo/robotgo"
- "github.com/syndtr/goleveldb/leveldb"
- "github.com/tebeka/selenium"
- "github.com/tidwall/gjson"
- )
- func GetRecord(filename string) map[string]bool {
- ret := map[string]bool{}
- fi, err := os.Open(filename)
- if err != nil {
- return ret
- }
- defer fi.Close()
- br := bufio.NewReader(fi)
- for {
- a, _, c := br.ReadLine()
- //fmt.Printf("xx:%s\n", a)
- if c == io.EOF {
- break
- }
- array := strings.Split(string(a), " ")
- if len(array) != 3 {
- continue
- }
- ret[array[0]] = true
- }
- return ret
- }
- func GetAcounts(filename string) ([][]string, error) {
- visited := GetRecord("record.txt")
- fi, err := os.Open(filename)
- if err != nil {
- return nil, err
- }
- defer fi.Close()
- ret := [][]string{}
- br := bufio.NewReader(fi)
- for {
- a, _, c := br.ReadLine()
- if c == io.EOF {
- break
- }
- array := strings.Split(string(a), ";")
- if len(array) != 3 {
- continue
- }
- if visited[array[0]] {
- //fmt.Printf("visited:%v\n", array[2])
- continue
- }
- item := []string{array[0], array[1], array[2]}
- ret = append(ret, item)
- }
- return ret, nil
- }
- func Displayed(by, elementName string) func(selenium.WebDriver) (bool, error) {
- return func(wd selenium.WebDriver) (ok bool, err error) {
- var el selenium.WebElement
- el, err = wd.FindElement(by, elementName)
- if err != nil {
- ok = false
- err = nil
- return
- }
- ok, err = el.IsDisplayed()
- return
- }
- }
- func Check415Error(wd selenium.WebDriver) error {
- e, err := wd.FindElement(selenium.ByTagName, "body")
- if err != nil {
- return err
- }
- text, _ := e.Text()
- str := "错误代码:415"
- if len(text) <= len(str) {
- return nil
- }
- if text[:len(str)] == str {
- return errors.New("访问受限")
- }
- return nil
- }
- func commonVerify(image string) string {
- //# 数英汉字类型
- //# 通用数英1-4位 10110
- //# 通用数英5-8位 10111
- //# 通用数英9~11位 10112
- //# 通用数英12位及以上 10113
- //# 通用数英1~6位plus 10103
- //# 定制-数英5位~qcs 9001
- //# 定制-纯数字4位 193
- //# 中文类型
- //# 通用中文字符1~2位 10114
- //# 通用中文字符 3~5位 10115
- //# 通用中文字符6~8位 10116
- //# 通用中文字符9位及以上 10117
- //# 定制-XX西游苦行中文字符 10107
- //# 计算类型
- //# 通用数字计算题 50100
- //# 通用中文计算题 50101
- //# 定制-计算题 cni 452
- config := map[string]interface{}{}
- config["image"] = image
- config["type"] = "30009"
- //config["extra"] = "click"
- config["token"] = "2EEYFMjDVpMTky-Z_BCgt_I14g4qq_D63S3NsQesfMc"
- configData, _ := json.Marshal(config)
- body := bytes.NewBuffer([]byte(configData))
- resp, err := http.Post("http://api.jfbym.com/api/YmServer/customApi", "application/json;charset=utf-8", body)
- defer resp.Body.Close()
- if err != nil {
- return ""
- }
- data, _ := ioutil.ReadAll(resp.Body)
- fmt.Println(string(data), err)
- return string(data)
- }
- func codeGetNew(data []byte, account string, token string) string {
- name := account + ".png"
- ioutil.WriteFile(name, data, 0666)
- //fmt.Println(name)
- defer func() {
- os.Remove(name)
- }()
- /* bodyBuffer := &bytes.Buffer{}
- bodyWriter := multipart.NewWriter(bodyBuffer)
- bodyWriter.WriteField("token", token)
- bodyWriter.WriteField("type", "local")
- fileWriter, _ := bodyWriter.CreateFormFile("file", name)
- */
- file, _ := os.Open(name)
- defer file.Close()
- fileInfo, _ := file.Stat()
- imageSize := fileInfo.Size()
- imageData := make([]byte, imageSize)
- _, err := file.Read(imageData)
- if err != nil {
- fmt.Println("保存文件失败")
- }
- base64Data := base64.StdEncoding.EncodeToString(imageData)
- respData := commonVerify(base64Data)
- fmt.Println("验证码识别结果:", respData)
- code := gjson.Get(respData, "code").Int()
- if code != 10000 {
- fmt.Println("验证码识别失败:", gjson.Get(respData, "msg").String())
- return ""
- }
- return gjson.Get(respData, "data.data").String()
- }
- /*
- func codeGet(data []byte, account string, token string) (bool, string) {
- name := account + ".png"
- ioutil.WriteFile(name, data, 0666)
- defer func() {
- os.Remove(name)
- }()
- bodyBuffer := &bytes.Buffer{}
- bodyWriter := multipart.NewWriter(bodyBuffer)
- bodyWriter.WriteField("token", token)
- bodyWriter.WriteField("type", "local")
- fileWriter, _ := bodyWriter.CreateFormFile("file", name)
- file, _ := os.Open(name)
- defer file.Close()
- io.Copy(fileWriter, file)
- contentType := bodyWriter.FormDataContentType()
- bodyWriter.Close()
- resp, err := http.Post("http://www.bhshare.cn/imgcode/", contentType, bodyBuffer)
- fmt.Println("验证码识别 err :", err)
- defer resp.Body.Close()
- resp_body, _ := ioutil.ReadAll(resp.Body)
- defer resp.Body.Close()
- fmt.Printf("验证码识别响应 %s\n", resp_body)
- timesExist := gjson.GetBytes(resp_body, "times").Exists()
- //fmt.Printf("%v,%v\n", gjson.GetBytes(resp_body, "times").Exists(),gjson.GetBytes(resp_body, "times").Int())
- if !timesExist {
- return false, ""
- }
- times := gjson.GetBytes(resp_body, "times").Int()
- if times < 1 {
- return true, ""
- }
- return false, gjson.GetBytes(resp_body, "data").String()
- }
- */
- var dbMutex sync.Mutex
- var db *leveldb.DB
- func TokenDbOpen() {
- dbMutex.Lock()
- defer dbMutex.Unlock()
- if db != nil {
- return
- }
- db, _ = leveldb.OpenFile("tokens", nil)
- }
- func TokenDbClear() {
- dbMutex.Lock()
- defer dbMutex.Unlock()
- if db == nil {
- return
- }
- for _, v := range config.Conf.CodeTokens {
- _ = db.Delete([]byte(v), nil)
- }
- }
- func TokenDbClose() {
- dbMutex.Lock()
- defer dbMutex.Unlock()
- if db == nil {
- return
- }
- db.Close()
- db = nil
- }
- func TokenDbGet(token string) string {
- dbMutex.Lock()
- defer dbMutex.Unlock()
- if db == nil {
- return ""
- }
- bytes, _ := db.Get([]byte(token), nil)
- return string(bytes)
- }
- func TokenDbPut(token string, value string) {
- dbMutex.Lock()
- defer dbMutex.Unlock()
- if db == nil {
- return
- }
- _ = db.Put([]byte(token), []byte(value), nil)
- }
- func codeGetHandle(data []byte, account string, tokens []string) string {
- //return "77,173|75,115|183,180"
- return codeGetNew(data, account, "")
- /*now := time.Now()
- day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
- dayStr := fmt.Sprintf("%d", day.Unix())
- for _, token := range tokens {
- if db != nil {
- str := TokenDbGet(token)
- if str == dayStr {
- continue
- }
- }
- timesIsLimit, code := codeGet(data, account, token)
- if timesIsLimit {
- TokenDbPut(token, dayStr)
- }
- if code != "" && code[0] >= '0' && code[0] <= '9' {
- return code
- }
- }
- return ""*/
- }
- func StartOneStudent(usernameText string, passwordText string, realName string) (service *selenium.Service, wd selenium.WebDriver, err error) {
- defer func() {
- if r := recover(); r != nil {
- err = errors.New(fmt.Sprintf("panic error %v-%v", err, r))
- }
- }()
- service, wd, err = StartOneStudentHandle(usernameText, passwordText, usernameText)
- return service, wd, err
- }
- func nextPage(wd selenium.WebDriver) []selenium.WebElement {
- next, err := wd.FindElement(selenium.ByXPATH, "//button[@class='btn-next']")
- if err != nil {
- return nil
- }
- disable, _ := next.GetAttribute("disabled")
- fmt.Printf("disable:%v\n", disable)
- if disable == "disabled" || disable == "true" {
- return nil
- }
- tryClick(wd, next)
- time.Sleep(5 * time.Second)
- buttons, _ := wd.FindElements(selenium.ByXPATH, "//a[text()='去学习']")
- if len(buttons) == 0 {
- return nil
- }
- return buttons
- }
- func tryChangePassSure(wd selenium.WebDriver) bool {
- act, err := wd.ActiveElement()
- if err != nil {
- fmt.Printf("find active element\n")
- return false
- }
- _, err = act.FindElement(selenium.ByXPATH, "//div[contains(text(), '请尽快修改密码')]")
- if err != nil {
- fmt.Printf("find active element to change pass\n")
- return false
- }
- sure, err := act.FindElement(selenium.ByXPATH, "//span[text()='确定']")
- if err != nil {
- fmt.Printf("find active element to change pass sure\n")
- return false
- }
- err = tryClick(wd, sure)
- if err != nil {
- fmt.Printf("find active element to click\n")
- return false
- }
- return true
- }
- func generateMoodleSession() string {
- // 生成随机的UUID作为moodleSession值
- id := uuid.New()
- return id.String()
- }
- func StartOneStudentHandle(usernameText string, passwordText string, realName string) (*selenium.Service, selenium.WebDriver, error) {
- var (
- //driverPath = `C:\Users\lqzlt\AppData\Local\Google\Chrome\Application\chromedriver.exe`
- driverPath = `./chromedriver.exe`
- port = 60002
- )
- // chrome服务
- service, err := selenium.NewChromeDriverService(driverPath, port, []selenium.ServiceOption{}...)
- if nil != err {
- return nil, nil, err
- }
- defer func() {
- //_ = service.Stop()
- }()
- // Connect to the WebDriver instance running locally.
- caps := selenium.Capabilities{"browserName": "chrome"}
- imagCaps := map[string]interface{}{
- "profile.managed_default_content_settings.cookies": 1,
- "same-site-by-default-cookies": 2,
- "cookies-without-same-site-must-be-secure": 2,
- "search_engine_is_default": false,
- }
- chromeCaps := chrome.Capabilities{
- Prefs: imagCaps,
- Path: "",
- ExcludeSwitches: []string{"enable-automation"},
- Args: []string{
- "--start-maximized",
- "--disable-blink-features=AutomationControlled",
- //"--no-sandbox",
- //"--disable-gpu-sandbox",
- "--accept-encoding=gzip, deflate, br",
- "--accept-language=zh-CN,zh;q=0.9",
- // "--cache-control=max-age=0",
- //"--abc=d",
- //"--load-extention=D:\\sql2struct",
- //fmt.Sprintf("--moodleSession=%s", generateMoodleSession()),
- //"--upgrade-insecure-requests=1",
- "--connection=keep-alive",
- "--accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
- "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
- },
- }
- caps.AddChrome(chromeCaps)
- wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", port))
- if err != nil {
- return service, nil, errors.New(fmt.Sprintf("connect to the webDriver failed:%v\n", err))
- }
- //wd.MaximizeWindow("test")
- defer func() {
- //_ = wd.Close()
- }()
- //wd.Get("file:///C:/Users/lqzlt/Desktop/1.html")
- //time.Sleep(1*time.Second)
- //handleQuestionWebTest(wd)
- //time.Sleep(1000*time.Second)
- //return service, wd, nil
- //err = wd.Get("https://menhu.pt.ouchn.cn/")
- //err = wd.Get("https://iam.pt.ouchn.cn/am/UI/Login?realm=%2F&service=initService&goto=https%3A%2F%2Fiam.pt.ouchn.cn%2Fam%2Foauth2%2Fauthorize%3Fservice%3DinitService%26response_type%3Dcode%26client_id%3D345fcbaf076a4f8a%26scope%3Dall%26redirect_uri%3Dhttps%253A%252F%252Fmenhu.pt.ouchn.cn%252Fouchnapp%252Fwap%252Flogin%252Findex%26decision%3DAllow")
- err = wd.Get("https://iam.pt.ouchn.cn/am/UI/Login")
- if err != nil {
- return service, wd, err
- }
- if config.Conf.Timeout == 0 {
- config.Conf.Timeout = 20
- }
- if config.Conf.QuestionCount == 0 {
- config.Conf.QuestionCount = 2
- }
- //time.Sleep(2 * time.Second)
- fmt.Printf("查找登录按钮\n")
- // 进入登录页面
- err = wd.WaitWithTimeout(Displayed(selenium.ByID, "form_button"), time.Duration(config.Conf.Timeout)*time.Second)
- if err != nil {
- return service, wd, errors.New(fmt.Sprintf("获取登录页面失败:%v\n", err))
- }
- fmt.Printf("开始获取用户名按钮\n")
- username, err := wd.FindElement(selenium.ByID, "loginName")
- if err != nil {
- return service, wd, errors.New(fmt.Sprintf("获取用户名按钮:%v\n", err))
- }
- fmt.Printf("开始获取密码按钮\n")
- password, err := wd.FindElement(selenium.ByID, "password")
- if err != nil {
- return service, wd, errors.New(fmt.Sprintf("获取密码按钮:%v\n", err))
- }
- fmt.Printf("开始获取登录按钮\n")
- submit, err := wd.FindElement(selenium.ByID, "form_button")
- if err != nil {
- return service, wd, errors.New(fmt.Sprintf("获取登录按钮:%v\n", err))
- }
- fmt.Println("填充用户名:", usernameText)
- err = username.SendKeys(usernameText)
- if err != nil {
- return service, wd, errors.New(fmt.Sprintf("填充用户名:%v\n", err))
- }
- fmt.Println("填充密码:", passwordText)
- err = password.SendKeys(passwordText)
- if err != nil {
- return service, wd, errors.New(fmt.Sprintf("填充密码:%v\n", err))
- }
- /*fmt.Printf("开始获取验证码按钮\n")
- verifyCode, err := wd.FindElement(selenium.ByID, "captcha")
- if err != nil {
- return service, wd, errors.New(fmt.Sprintf("获取验证码按钮失败:%v\n", err))
- }
- fmt.Printf("点击验证码按钮\n")
- err = verifyCode.Click()
- if err != nil {
- return service, wd, errors.New(fmt.Sprintf("点击验证码按钮失败:%v\n", err))
- }*/
- err = tryClick(wd, submit)
- if err != nil {
- return service, wd, errors.New(fmt.Sprintf("点击登录:%v\n", err))
- }
- innerHeight, err := wd.ExecuteScript("return window.innerHeight", nil)
- if err != nil {
- }
- //fmt.Println("INNERhEIG:", innerHeight)
- fheight := innerHeight.(float64)
- aheight := int(fheight)
- //fmt.Println("addressBarHeight:", innerHeight, aheight)
- outerHeight, err := wd.ExecuteScript("return window.outerHeight", nil)
- if err != nil {
- }
- fheight = outerHeight.(float64)
- aheight = int(fheight) - aheight
- fmt.Println("addressBarHeight:", innerHeight, outerHeight, aheight)
- if config.Conf.CodeManual {
- time.Sleep(1 * time.Hour)
- /*count := 0
- for count < 60 {
- time.Sleep(1 * time.Second)
- value, _ := verifyCode.GetAttribute("value")
- if len(value) < 4 {
- continue
- }
- break
- }
- if count >= 60 {
- return service, wd, errors.New("未输入验证码")
- }*/
- } else {
- time.Sleep(1 * time.Second)
- // //div[@class='geetest_box_f3dbc8bc geetest_box']
- //image, err := wd.FindElement(selenium.ByXPATH, "//img[@id='kaptchaImage']")
- // time.Sleep(10 * time.Second)
- fmt.Println("获取验证码")
- err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "/html/body/div[4]/div[1]/div[1]"), time.Duration(config.Conf.Timeout)*time.Second)
- if err != nil {
- return service, wd, errors.New("验证码获取失败1111111")
- }
- image, err := wd.FindElement(selenium.ByXPATH, "/html/body/div[4]/div[1]/div[1]")
- if err != nil {
- return service, wd, errors.New("验证码获取失败")
- }
- fmt.Println("验证码获取成功")
- data, _ := image.Screenshot(false)
- code := codeGetHandle(data, usernameText, config.Conf.CodeTokens)
- if code == "" {
- return service, wd, errors.New("验证码识别失败\n")
- }
- //codeData := gjson.Get(code, "data").String()
- fmt.Println("CODE data:", code)
- codeList := strings.Split(code, "|")
- for _, v := range codeList {
- codeX := strings.Split(v, ",")
- if len(codeX) < 2 {
- break
- }
- x, _ := strconv.Atoi(codeX[0])
- y, _ := strconv.Atoi(codeX[1])
- point, _ := image.Location()
- robotgo.Move(x+point.X, y+point.Y+aheight)
- robotgo.Click("left")
- time.Sleep(1 * time.Second)
- }
- /*time.Sleep(time.Minute)
- os.Exit(1)*/
- /*err = verifyCode.SendKeys(code)
- if err != nil {
- return service, wd, errors.New(fmt.Sprintf("填充验证码:%v\n", err))
- }*/
- }
- imageSubmitButton, err := wd.FindElement(selenium.ByXPATH, "/html/body/div[4]/div[1]/div[1]/div[2]/div/div/div[2]")
- //err = submit.Click()
- err = tryClick(wd, imageSubmitButton)
- if err != nil {
- return service, wd, errors.New(fmt.Sprintf("点击提交失败:%v\n", err))
- }
- //time.Sleep(1200 *time.Second)
- //return service, wd, errors.New("登录测试")
- time.Sleep(2 * time.Second)
- tryChangePassSure(wd)
- // 进入学生主页
- err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//a[text()='去学习']"), time.Duration(config.Conf.Timeout)*time.Second)
- if err != nil {
- if !tryChangePassSure(wd) {
- return service, wd, errors.New(fmt.Sprintf("进入学生主页失败:%v\n", err))
- }
- time.Sleep(2 * time.Second)
- err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//a[text()='去学习']"), time.Duration(config.Conf.Timeout)*time.Second)
- if err != nil {
- fmt.Printf("find active element to find page\n")
- return service, wd, errors.New(fmt.Sprintf("进入学生主页失败:%v\n", err))
- }
- }
- fmt.Printf("进入学生主页\n")
- buttons, _ := wd.FindElements(selenium.ByXPATH, "//a[text()='去学习']")
- currentWindow, err := wd.CurrentWindowHandle()
- if err != nil {
- return service, wd, errors.New(fmt.Sprintf("获取当前窗口失败:%v\n", err))
- }
- for buttons != nil {
- for i := 0; i < len(buttons); i++ {
- button := buttons[i]
- text, _ := button.Text()
- if text != "去学习" {
- continue
- }
- if true {
- ptag, err := button.FindElement(selenium.ByXPATH, "./preceding-sibling::div/p")
- if err != nil {
- fmt.Printf("查找课程失败:%v\n", err)
- return service, wd, err
- }
- txt, _ := ptag.Text()
- array := strings.Split(txt, " ")
- if len(array) > 1 {
- txt = array[1]
- }
- txt = strings.TrimSpace(txt)
- if !checkCourseExist(config.Conf.Courses, txt) {
- fmt.Println("不执行课程:", txt)
- continue
- }
- fmt.Println("要执行课程:", txt)
- }
- //button.Click()
- tryClick(wd, button)
- //time.Sleep(60*time.Second)
- count := 0
- handled := ""
- // 等待新页面弹出
- for count < 5 {
- time.Sleep(1 * time.Second)
- handles, _ := wd.WindowHandles()
- if len(handles) > 1 {
- handled = handles[len(handles)-1]
- //
- wd.SwitchWindow(handled)
- break
- }
- count++
- }
- if count > 5 {
- continue
- }
- if err := Check415Error(wd); err != nil {
- return service, wd, err
- }
- // 处理课程
- //time.Sleep(4000 * time.Second)
- err = CourseHandle(wd, realName)
- if err != nil {
- return service, wd, err
- }
- //fmt.Printf("xxxxerr:%v\n", err)
- // 关闭当前课程窗口
- wd.CloseWindow(handled)
- // 切换到学生主页窗口(有进入学习按钮的窗口)
- wd.SwitchWindow(currentWindow)
- runtime.GC()
- }
- buttons = nextPage(wd)
- }
- return service, wd, err
- }
- // 等待url变化
- func waitUrl(wd selenium.WebDriver, url1 string, url2 string, count int) string {
- for count >= 0 {
- time.Sleep(100 * time.Millisecond)
- url, _ := wd.CurrentURL()
- if url != url1 && url != url2 {
- return url
- }
- count--
- }
- return ""
- }
- func getCookies(wd selenium.WebDriver) (string, error) {
- cookies, err := wd.GetCookies()
- if err != nil {
- return "", errors.New(fmt.Sprintf("获取cookie 失败,%v\n", err))
- }
- if len(cookies) == 0 {
- return "", errors.New(fmt.Sprintf("获取cookie 失败,%v\n", "cookie为空"))
- }
- ret := ""
- for _, v := range cookies {
- item := fmt.Sprintf("%s=%s", v.Name, v.Value)
- if ret == "" {
- ret = item
- continue
- }
- ret = ret + ";"
- ret = ret + item
- }
- return ret, nil
- }
- func checkCourseExist(courses []string, course string) bool {
- for _, v := range courses {
- if v == course {
- return true
- }
- }
- return false
- }
- type ElementInfo struct {
- Element selenium.WebElement
- }
- type AnswerInfo struct {
- Text string
- Radio *ElementInfo
- Ptag *ElementInfo
- }
- type QuestionInfo struct {
- Text string
- Tag int
- Number string
- AnswerArray []*AnswerInfo
- ChoosedAnswer []int
- }
- func GenerateRandom(length int) int {
- time.Sleep(1 * time.Microsecond)
- rand.Seed(time.Now().UnixNano())
- return rand.Intn(length)
- }
- // 计算题
- func shortAnswer(question QuestionInfo, questionM map[string][]string) error {
- if len(question.AnswerArray) == 0 {
- return errors.New(fmt.Sprintf("%s 选项为空", question.Text))
- }
- //fmt.Println("收集的答案000000000000000000000000:", questionM)
- str := TrimSpace(question.Text)
- str = ParseHan(str)
- str = fmt.Sprintf("%d-", question.Tag) + str
- //fmt.Println("问答题目1111111111111111111111111:", str)
- answerstrs, _ := questionM[str]
- //fmt.Println("问答答案2222222222222222222222222:", answerstrs)
- if len(answerstrs) == 0 {
- str = strings.TrimRight(str, "分")
- answerstrs, _ = questionM[str]
- if len(answerstrs) == 0 {
- return errors.New("没有答案")
- }
- }
- index := GenerateRandom(len(answerstrs))
- question.AnswerArray[0].Ptag.Element.Clear()
- question.AnswerArray[0].Ptag.Element.SendKeys(answerstrs[index])
- //fmt.Println("问答选择答案2222222222222222222222222:", answerstrs[index])
- time.Sleep(500 * time.Millisecond)
- return nil
- }
- func tryClick(wd selenium.WebDriver, element selenium.WebElement) error {
- array := []interface{}{element}
- _, err := wd.ExecuteScript("arguments[0].click()", array)
- if err != nil {
- fmt.Printf("按钮点击失败:%v\n", err)
- }
- return err
- }
- var questionTagM = map[int]string{
- 1: "单选题",
- 2: "判断题",
- 3: "多选题",
- 4: "计算题/简答题",
- }
- func getTagName(tag int) string {
- ret := questionTagM[tag]
- if ret == "" {
- return "未知题型"
- }
- return ret
- }
- // 题目号个数-本来就随机的题数, 再随机生成错误个数, 根据错误个数随机选择题号
- func getRandErrorNumber(emptyCount int, originNumber map[int]bool, maxNumber int) map[int]bool {
- questionCount := len(originNumber) - emptyCount
- if questionCount <= 2 || maxNumber <= 2 {
- return map[int]bool{}
- }
- count := 0
- if questionCount < 5 {
- count = 1
- } else {
- rand.Seed(time.Now().UnixNano())
- count = rand.Intn(3)
- if count == 0 {
- count = 1
- }
- }
- m := map[int]bool{}
- for len(m) < count {
- number := rand.Intn(maxNumber + 1)
- if originNumber[number] {
- m[number] = true
- }
- }
- return m
- }
- func random(count int) int {
- rand.Seed(time.Now().UnixNano())
- return rand.Intn(count)
- }
- func chooseAnswer2(wd selenium.WebDriver, questions []QuestionInfo, questionM map[string][]string) error {
- if config.Conf.NewStyle {
- return chooseAnswer2New(wd, questions, questionM)
- }
- emptyCount := 0
- if false {
- emptyCount = 3
- }
- // 选择或判断题目号
- originNumber := map[int]bool{}
- // 选择或判断最大题目号
- maxNumber := 0
- // 先收集答案
- for i, _ := range questions {
- questions[i].ChoosedAnswer = []int{}
- fmt.Printf("\n题目类型:%s\n", getTagName(questions[i].Tag))
- fmt.Printf("题目:%s\n", questions[i].Text)
- for _, v := range questions[i].AnswerArray {
- fmt.Printf("选项:%s\n", v.Text)
- }
- if questions[i].Tag == 4 {
- shortAnswer(questions[i], questionM)
- continue
- }
- if len(questions[i].AnswerArray) == 0 {
- return errors.New(fmt.Sprintf("%s 选项为空", questions[i].Text))
- }
- str := TrimSpace(questions[i].Text)
- str = ParseHan(str)
- //str = trimQuestionPrefix(str)
- str = fmt.Sprintf("%d-", questions[i].Tag) + str
- answerstrs, _ := questionM[str]
- if len(answerstrs) == 0 || answerstrs[0] == "" {
- emptyCount++
- if emptyCount > config.Conf.QuestionCount {
- return errors.New(fmt.Sprintf("%s 题库答案为空", questions[i].Text))
- }
- fmt.Printf("%s 题库答案为空, 空答案数小于%d,进行随机选择", questions[i].Text, config.Conf.QuestionCount)
- questions[i].ChoosedAnswer = append(questions[i].ChoosedAnswer, random(len(questions[i].AnswerArray)))
- continue
- }
- find := 0
- // 单选
- if questions[i].Tag == 1 {
- //answerstrs = answerstrs[:1]
- }
- if questions[i].Tag == 3 {
- //fmt.Printf("*****************************************:%s,%v\n", questions[i].Text,answerstrs)
- }
- for _, answerstr := range answerstrs {
- if answerstr == "" {
- continue
- }
- for j, v := range questions[i].AnswerArray {
- if questions[i].Tag == 1 && find > 0 {
- break
- }
- right := false
- if questions[i].Tag == 3 {
- right = TrimSpace(answerstr) == TrimSpace(v.Text)
- } else {
- right = tryEqual(answerstr, TrimSpace(v.Text))
- }
- if right {
- fmt.Printf("选择答案:%s\n", answerstr)
- questions[i].ChoosedAnswer = append(questions[i].ChoosedAnswer, j)
- originNumber[i] = true
- maxNumber = i
- //ppp, _ := v.Radio.Element.FindElement(selenium.ByXPATH, "./following-sibling::span")
- //txt, _ := ppp.Text()
- //fmt.Printf("kkkkkkkkkkkkkkkkkkk:%s,%s\n", txt, answerstr)
- if questions[i].Tag == 3 {
- //time.Sleep(10*time.Second)
- }
- find++
- //time.Sleep(1 * time.Second)
- break
- }
- }
- }
- if find == 0 {
- emptyCount++
- if emptyCount > config.Conf.QuestionCount {
- return errors.New(fmt.Sprintf("%s 题库答案为空2", questions[i].Text))
- }
- fmt.Printf("未找到匹配答案,题库中的答案有:%v\n", answerstrs)
- questions[i].ChoosedAnswer = append(questions[i].ChoosedAnswer, random(len(questions[i].AnswerArray)))
- continue
- //return errors.New(fmt.Sprintf("%s 未找到匹配答案", questions[i].Text))
- }
- }
- // 选择答案, 先随机生成需故意填错的错误题号
- errorNumber := getRandErrorNumber(emptyCount, originNumber, maxNumber)
- defer func() {
- errorNumber = nil
- }()
- for i, _ := range questions {
- if len(questions[i].ChoosedAnswer) == 0 {
- continue
- }
- // 不需要故意填错
- if !errorNumber[i] {
- for _, v := range questions[i].ChoosedAnswer {
- err := tryClick(wd, questions[i].AnswerArray[v].Radio.Element)
- if err != nil {
- fmt.Printf("点击答案错误:%v\n", err)
- return err
- }
- time.Sleep(1 * time.Second)
- }
- continue
- }
- // 需要故意填错时,随机选择错误答案
- // 正确答案map
- cm := map[int]bool{}
- for _, j := range questions[i].ChoosedAnswer {
- cm[j] = true
- }
- // 可供选择的错误答案
- array := []int{}
- for j, _ := range questions[i].AnswerArray {
- if !cm[j] {
- array = append(array, j)
- }
- }
- // 随机生成索引
- arrayIndex := random(len(array))
- // 获取错误答案索引
- errorIndex := 0
- if len(array) > 0 {
- errorIndex = array[arrayIndex]
- } else {
- errorIndex = random(len(questions[i].AnswerArray))
- }
- err := tryClick(wd, questions[i].AnswerArray[errorIndex].Radio.Element)
- if err != nil {
- fmt.Printf("点击答案错误:%v\n", err)
- return err
- }
- time.Sleep(1 * time.Second)
- }
- return nil
- }
- func chooseAnswer2New(wd selenium.WebDriver, questions []QuestionInfo, questionM map[string][]string) error {
- emptyCount := 0
- if false {
- emptyCount = 3
- }
- // 选择或判断题目号
- originNumber := map[int]bool{}
- // 选择或判断最大题目号
- maxNumber := 0
- // 先收集答案
- for i, _ := range questions {
- questions[i].ChoosedAnswer = []int{}
- fmt.Printf("\n题目类型:%s\n", getTagName(questions[i].Tag))
- fmt.Printf("题目:%s\n", questions[i].Text)
- for _, v := range questions[i].AnswerArray {
- fmt.Printf("选项:%s\n", v.Text)
- }
- if questions[i].Tag == 4 {
- shortAnswer(questions[i], questionM)
- continue
- }
- if len(questions[i].AnswerArray) == 0 {
- return errors.New(fmt.Sprintf("%s 选项为空", questions[i].Text))
- }
- str := TrimSpace(questions[i].Text)
- str = ParseHan(str)
- //str = trimQuestionPrefix(str)
- str = fmt.Sprintf("%d-", questions[i].Tag) + str
- answerstrs, _ := questionM[str]
- if len(answerstrs) == 0 || answerstrs[0] == "" {
- emptyCount++
- if emptyCount > config.Conf.QuestionCount {
- return errors.New(fmt.Sprintf("%s 题库答案为空", questions[i].Text))
- }
- fmt.Printf("%s 题库答案为空, 空答案数小于%d,进行随机选择", questions[i].Text, config.Conf.QuestionCount)
- questions[i].ChoosedAnswer = append(questions[i].ChoosedAnswer, random(len(questions[i].AnswerArray)))
- continue
- }
- find := 0
- // 单选
- if questions[i].Tag == 1 {
- //answerstrs = answerstrs[:1]
- }
- if questions[i].Tag == 3 {
- //fmt.Printf("*****************************************:%s,%v\n", questions[i].Text,answerstrs)
- }
- for _, answerstr := range answerstrs {
- if answerstr == "" {
- continue
- }
- for j, _ := range questions[i].AnswerArray {
- if questions[i].Tag == 1 && find > 0 {
- break
- }
- right := false
- if questions[i].Tag == 1 || questions[i].Tag == 3 {
- //right = TrimSpace(answerstr) == TrimSpace(v.Text)
- right = j == SelectAnswerFlagMap[answerstr]
- } else {
- //right = tryEqual(answerstr, TrimSpace(v.Text))
- right = j == JudgeAnswerMap[answerstr]
- }
- if right {
- fmt.Printf("选择答案:%s\n", answerstr)
- questions[i].ChoosedAnswer = append(questions[i].ChoosedAnswer, j)
- originNumber[i] = true
- maxNumber = i
- //ppp, _ := v.Radio.Element.FindElement(selenium.ByXPATH, "./following-sibling::span")
- //txt, _ := ppp.Text()
- //fmt.Printf("kkkkkkkkkkkkkkkkkkk:%s,%s\n", txt, answerstr)
- if questions[i].Tag == 3 {
- //time.Sleep(10*time.Second)
- }
- find++
- //time.Sleep(1 * time.Second)
- break
- }
- }
- }
- if find == 0 {
- emptyCount++
- if emptyCount > config.Conf.QuestionCount {
- return errors.New(fmt.Sprintf("%s 题库答案为空2", questions[i].Text))
- }
- fmt.Printf("未找到匹配答案,题库中的答案有:%v\n", answerstrs)
- questions[i].ChoosedAnswer = append(questions[i].ChoosedAnswer, random(len(questions[i].AnswerArray)))
- continue
- //return errors.New(fmt.Sprintf("%s 未找到匹配答案", questions[i].Text))
- }
- }
- // 选择答案, 先随机生成需故意填错的错误题号
- errorNumber := getRandErrorNumber(emptyCount, originNumber, maxNumber)
- defer func() {
- errorNumber = nil
- }()
- for i, _ := range questions {
- if len(questions[i].ChoosedAnswer) == 0 {
- continue
- }
- // 不需要故意填错
- if !errorNumber[i] {
- for _, v := range questions[i].ChoosedAnswer {
- err := tryClick(wd, questions[i].AnswerArray[v].Radio.Element)
- if err != nil {
- fmt.Printf("点击答案错误:%v\n", err)
- return err
- }
- time.Sleep(1 * time.Second)
- }
- continue
- }
- // 需要故意填错时,随机选择错误答案
- // 正确答案map
- cm := map[int]bool{}
- for _, j := range questions[i].ChoosedAnswer {
- cm[j] = true
- }
- // 可供选择的错误答案
- array := []int{}
- for j, _ := range questions[i].AnswerArray {
- if !cm[j] {
- array = append(array, j)
- }
- }
- // 随机生成索引
- arrayIndex := random(len(array))
- // 获取错误答案索引
- errorIndex := 0
- if len(array) > 0 {
- errorIndex = array[arrayIndex]
- } else {
- errorIndex = random(len(questions[i].AnswerArray))
- }
- err := tryClick(wd, questions[i].AnswerArray[errorIndex].Radio.Element)
- if err != nil {
- fmt.Printf("点击答案错误:%v\n", err)
- return err
- }
- time.Sleep(1 * time.Second)
- }
- return nil
- }
- func chooseAnswer(wd selenium.WebDriver, questions []QuestionInfo, questionM map[string][]string) error {
- // 正常选择答案
- if !config.Conf.QuestionRandom {
- return chooseAnswer2(wd, questions, questionM)
- }
- // 全部随机选
- for i, _ := range questions {
- fmt.Printf("\n题目类型:%s\n", getTagName(questions[i].Tag))
- fmt.Printf("题目:%s\n", questions[i].Text)
- for _, v := range questions[i].AnswerArray {
- fmt.Printf("选项:%s\n", v.Text)
- }
- if questions[i].Tag == 4 {
- shortAnswer(questions[i], questionM)
- continue
- }
- if len(questions[i].AnswerArray) == 0 {
- return errors.New(fmt.Sprintf("%s 选项为空", questions[i].Text))
- }
- str := TrimSpace(questions[i].Text)
- str = ParseHan(str)
- //str = trimQuestionPrefix(str)
- str = fmt.Sprintf("%d-", questions[i].Tag) + str
- answerstrs, _ := questionM[str]
- if len(answerstrs) == 0 || answerstrs[0] == "" {
- er := tryClick(wd, questions[i].AnswerArray[random(len(questions[i].AnswerArray))].Radio.Element)
- if er != nil {
- fmt.Printf("radio click:%v\n", er)
- return er
- }
- time.Sleep(1 * time.Second)
- continue
- }
- find := 0
- // 单选
- if questions[i].Tag == 1 {
- //answerstrs = answerstrs[:1]
- }
- if questions[i].Tag == 3 {
- //fmt.Printf("*****************************************:%s,%v\n", questions[i].Text,answerstrs)
- }
- for _, answerstr := range answerstrs {
- if answerstr == "" {
- continue
- }
- for _, v := range questions[i].AnswerArray {
- if questions[i].Tag == 1 && find > 0 {
- break
- }
- right := false
- if questions[i].Tag == 3 {
- right = TrimSpace(answerstr) == TrimSpace(v.Text)
- } else {
- right = tryEqual(answerstr, TrimSpace(v.Text))
- }
- if right {
- fmt.Printf("选择答案:%s\n", answerstr)
- er := tryClick(wd, v.Radio.Element)
- if er != nil {
- fmt.Printf("radio click:%v\n", er)
- return er
- }
- //ppp, _ := v.Radio.Element.FindElement(selenium.ByXPATH, "./following-sibling::span")
- //txt, _ := ppp.Text()
- //fmt.Printf("kkkkkkkkkkkkkkkkkkk:%s,%s\n", txt, answerstr)
- if questions[i].Tag == 3 {
- //time.Sleep(10*time.Second)
- }
- find++
- time.Sleep(1 * time.Second)
- break
- }
- }
- }
- if find == 0 {
- er := tryClick(wd, questions[i].AnswerArray[random(len(questions[i].AnswerArray))].Radio.Element)
- if er != nil {
- fmt.Printf("radio click:%v\n", er)
- return er
- }
- //fmt.Printf("未找到匹配答案,题库中的答案有:%v\n", answerstrs)
- continue
- //return errors.New(fmt.Sprintf("%s 未找到匹配答案", questions[i].Text))
- }
- }
- return nil
- }
- func getCourseId(src string) string {
- array := strings.Split(src, "/")
- if len(array) < 5 {
- return ""
- }
- return array[4]
- }
- type CourseModule struct {
- Name string
- ModuleId string
- }
- func getUploadIds(moduleId string, cookie string) ([]int64, error) {
- url := fmt.Sprintf("https://lms.ouchn.cn/api/activities/%s", moduleId)
- request, err := http.NewRequest("GET", url, nil)
- if err != nil {
- return nil, err
- }
- request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- request.Header.Set("Cookie", cookie)
- request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
- //request.Header.Set("Host", "chengdu.ouchn.cn")
- client := http.Client{}
- resp, err := client.Do(request)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
- respBytes, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
- ret := []int64{}
- uploads := gjson.GetBytes(respBytes, "uploads").Array()
- for _, upload := range uploads {
- id := upload.Get("id").Int()
- ret = append(ret, id)
- }
- return ret, nil
- }
- func getCourseModules(courceId string, cookie string, specialCourse bool) ([]CourseModule, error) {
- url := fmt.Sprintf("https://lms.ouchn.cn/api/courses/%s/modules", courceId)
- request, err := http.NewRequest("GET", url, nil)
- if err != nil {
- return nil, err
- }
- request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- request.Header.Set("Cookie", cookie)
- request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
- //request.Header.Set("Host", "chengdu.ouchn.cn")
- client := http.Client{}
- resp, err := client.Do(request)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
- respBytes, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
- ret := []CourseModule{}
- mos := gjson.GetBytes(respBytes, "modules").Array()
- for _, mo := range mos {
- if (len(mo.Get("syllabuses").Array())) == 0 && !specialCourse {
- continue
- }
- item := CourseModule{}
- item.ModuleId = fmt.Sprintf("%d", mo.Get("id").Int())
- item.Name = mo.Get("name").String()
- ret = append(ret, item)
- }
- return ret, nil
- }
- type ModuleSubInfo struct {
- Name string
- Id string
- Stype string
- SyllabusId int64
- Type int // 1 page,2 vedio
- }
- type ModuleInfo struct {
- TxtInfos []ModuleSubInfo
- ExamInfos []ModuleSubInfo
- VedioInfos []ModuleSubInfo
- }
- func GetModuleInfo(courseId string, moduleId string, cookie string) (*ModuleInfo, error) {
- url := fmt.Sprintf("https://lms.ouchn.cn/api/course/%s"+
- "/all-activities?module_ids=[%s]"+
- "&activity_types=learning_activities,exams,classrooms,"+
- "live_records,rollcalls&no-loading-animation=true", courseId, moduleId)
- request, err := http.NewRequest("GET", url, nil)
- if err != nil {
- return nil, err
- }
- request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- request.Header.Set("Cookie", cookie)
- request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
- //request.Header.Set("Host", "chengdu.ouchn.cn")
- client := http.Client{Timeout: 60 * time.Second}
- resp, err := client.Do(request)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
- respBytes, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
- ret := &ModuleInfo{}
- // 试题
- exams := []ModuleSubInfo{}
- examsArray := gjson.GetBytes(respBytes, "exams").Array()
- for _, v := range examsArray {
- item := ModuleSubInfo{}
- item.Name = v.Get("title").String()
- unikey := v.Get("unique_key").String()
- array := strings.Split(unikey, "-")
- if len(array) < 2 {
- continue
- }
- item.Id = array[1]
- exams = append(exams, item)
- }
- // 文档和视频
- texts := []ModuleSubInfo{}
- vedios := []ModuleSubInfo{}
- array := gjson.GetBytes(respBytes, "learning_activities").Array()
- for _, v := range array {
- stype := v.Get("type").String()
- syllabusId := v.Get("syllabus_id").Int()
- item := ModuleSubInfo{}
- item.Name = v.Get("title").String()
- item.SyllabusId = syllabusId
- item.Stype = stype
- unikey := v.Get("unique_key").String()
- array := strings.Split(unikey, "-")
- if len(array) < 2 {
- continue
- }
- item.Id = array[1]
- if stype == "page" {
- item.Type = 1
- texts = append(texts, item)
- vedios = append(vedios, item)
- } else if stype == "online_video" || (stype == "web_link" && strings.Contains(item.Name, "视频")) || stype == "material" {
- index := -1
- item.Type = 2
- for i := len(vedios) - 1; i >= 0; i-- {
- if item.SyllabusId == vedios[i].SyllabusId {
- index = i
- break
- }
- }
- if index == -1 || index == len(vedios)-1 {
- vedios = append(vedios, item)
- } else {
- tmp := []ModuleSubInfo{}
- tmp = append(tmp, vedios[:index+1]...)
- tmp = append(tmp, item)
- tmp = append(tmp, vedios[index+1:]...)
- vedios = tmp
- }
- }
- }
- ret.ExamInfos = exams
- ret.TxtInfos = texts
- ret.VedioInfos = vedios
- return ret, nil
- }
- func MakeTxtUrl(courseId string, moduleId string, id string) string {
- return fmt.Sprintf("https://lms.ouchn.cn/course/%s/learning-activity/full-screen#/%s", courseId, id)
- }
- func MakeExamUrl(courseId string, moduleId string, id string) string {
- return fmt.Sprintf("https://lms.ouchn.cn/course/%s/learning-activity/full-screen#/exam/%s", courseId, id)
- }
- func VedioCompleteHandle(cookie string, id string) error {
- count := 0
- start, end := int64(0), int64(1000)
- for count < 5 {
- finish, err := VedioComplete(cookie, id, start, end)
- if err != nil {
- return err
- }
- if finish < 100 {
- start = end
- end += 1000
- count++
- continue
- }
- return nil
- }
- return errors.New("视频处理失败")
- }
- func VedioComplete(cookie string, id string, start, end int64) (int64, error) {
- url := fmt.Sprintf("https://lms.ouchn.cn/api/course/activities-read/%s", id)
- //fmt.Printf("get sections:%v,%v\n", str, cookie)
- m := map[string]interface{}{
- "start": start,
- "end": end,
- }
- content, _ := json.Marshal(m)
- reader := bytes.NewReader(content)
- fmt.Printf("post data:%s\n", content)
- request, err := http.NewRequest("POST", url, reader)
- if err != nil {
- return 0, err
- }
- request.Header.Set("Content-Type", "application/json")
- request.Header.Set("Cookie", cookie)
- request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
- client := http.Client{}
- resp, err := client.Do(request)
- if err != nil {
- return 0, err
- }
- defer resp.Body.Close()
- respBytes, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return 0, err
- }
- fmt.Printf("get bytes:%s\n", respBytes)
- if gjson.GetBytes(respBytes, "activity_id").Int() == 0 {
- return 0, errors.New("视频处理失败")
- }
- str := gjson.GetBytes(respBytes, "data").Get("completeness").String()
- if str == "full" {
- return 100, nil
- }
- if str == "part" {
- return 10, nil
- }
- return gjson.GetBytes(respBytes, "data").Get("completeness").Int(), nil
- }
- func examHandleJump(wd selenium.WebDriver, courseId, moduleId, id string) error {
- curl, _ := wd.CurrentURL()
- fmt.Printf("url1:%s\n", curl)
- url := MakeExamUrl(courseId, moduleId, id)
- wd.Get(url)
- time.Sleep(2 * time.Second)
- curl, _ = wd.CurrentURL()
- fmt.Printf("url2:%s\n", curl)
- return nil
- }
- func examHandleStart(wd selenium.WebDriver) error {
- // 点击答题按钮
- err := wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//a[@class='button button-green take-exam ng-scope']"), time.Duration(config.Conf.Timeout)*time.Second)
- if err != nil && strings.Contains(err.Error(), "timeout") {
- curl, _ := wd.CurrentURL()
- fmt.Printf("再次尝试:%s\n", curl)
- wd.Get(curl)
- time.Sleep(2 * time.Second)
- err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//a[@class='button button-green take-exam ng-scope']"), time.Duration(config.Conf.Timeout)*time.Second)
- }
- if err != nil {
- return err
- }
- button, err := wd.FindElement(selenium.ByXPATH, "//a[@class='button button-green take-exam ng-scope']")
- if err != nil {
- return err
- }
- //button.Click()
- tryClick(wd, button)
- fmt.Printf("点击答题按钮\n")
- time.Sleep(2 * time.Second)
- active, _ := wd.ActiveElement()
- // 勾选同意框
- chbox, err := active.FindElement(selenium.ByXPATH, "//input[@type='checkbox' and @name='confirm']")
- if err != nil {
- fmt.Printf("未找到同意勾选框:%v\n", err)
- return err
- }
- //err = chbox.Click()
- err = tryClick(wd, chbox)
- if err != nil {
- fmt.Printf("同意勾选框:%v\n", err)
- return err
- }
- fmt.Printf("勾选同意框\n")
- time.Sleep(1 * time.Second)
- // 点击答题
- button, err = active.FindElement(selenium.ByXPATH, "//button[text()='开始答题' or text()='继续答题']")
- if err != nil {
- fmt.Printf("未找到开始答题按钮:%v\n", err)
- return err
- }
- //err = button.Click()
- err = tryClick(wd, button)
- if err != nil {
- fmt.Printf("开始答题按钮:%v\n", err)
- return err
- }
- fmt.Printf("弹窗中点击答题按钮\n")
- time.Sleep(3 * time.Second)
- return nil
- }
- func examHandleSimpleAnswer(wd selenium.WebDriver) ([]QuestionInfo, error) {
- p, err := wd.FindElement(selenium.ByXPATH, "//div[@class='exam-subjects']/ol[@class='subjects-jit-display']")
- if err != nil {
- return nil, err
- }
- path := fmt.Sprintf("./following-sibling::li[@class='subject ng-scope short_answer']")
- ret := []QuestionInfo{}
- count := 0
- for {
- if count == 0 {
- path = fmt.Sprintf("./li[@class='subject ng-scope short_answer']")
- }
- p, err = p.FindElement(selenium.ByXPATH, path)
- if err != nil {
- break
- }
- div, err := p.FindElements(selenium.ByXPATH, "./div/div/div/span/p")
- if err != nil {
- fmt.Printf("简答题目:%v\n", err)
- break
- }
- txt, err := div[len(div)-1].Text()
- fmt.Printf("简答题:%s,%v\n", txt, err)
- item := QuestionInfo{Text: txt, Tag: 4}
- ptag, err := p.FindElement(selenium.ByXPATH, "./div/div/div/div/div/div/div/p")
- if err != nil {
- fmt.Printf("简答题框未找到:%v\n", err)
- break
- }
- if false {
- ptag.Clear()
- err = ptag.SendKeys("test test")
- fmt.Printf("sendkeys error:%v\n", err)
- }
- anserItem := AnswerInfo{Ptag: &ElementInfo{Element: ptag}}
- item.AnswerArray = append(item.AnswerArray, &anserItem)
- ret = append(ret, item)
- count++
- }
- if len(ret) == 0 {
- return nil, errors.New("未找到题")
- }
- //fmt.Printf("yyyyyyyy:%v\n", ret)
- return ret, nil
- }
- func examHandleSpecialQuestion(wd selenium.WebDriver) ([]QuestionInfo, error) {
- fmt.Printf("正在搜集题目和选项请等待\n")
- err := wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//div[@class='exam-subjects']/ol[@class='subjects-jit-display']"), time.Duration(config.Conf.Timeout)*time.Second)
- if err != nil {
- return nil, err
- }
- ol, err := wd.FindElement(selenium.ByXPATH, "//div[@class='exam-subjects']/ol[@class='subjects-jit-display']")
- if err != nil {
- return nil, err
- }
- time.Sleep(2 * time.Second)
- lis1, _ := ol.FindElements(selenium.ByXPATH, "./li")
- if len(lis1) == 0 {
- return nil, errors.New("未找到题")
- }
- ret := []QuestionInfo{}
- for _, li1 := range lis1 {
- attr, _ := li1.GetAttribute("class")
- tag := 0
- if strings.Contains(attr, "true_or_false") {
- tag = 2
- }
- if strings.Contains(attr, "single_selection") {
- tag = 1
- }
- if strings.Contains(attr, "multiple_selection") {
- tag = 3
- }
- if strings.Contains(attr, "short_answer") {
- tag = 4
- }
- if tag == 0 {
- continue
- }
- item := QuestionInfo{Tag: tag}
- p, err := li1.FindElement(selenium.ByXPATH, "./div/div/div/span/p")
- if err != nil {
- return nil, err
- }
- txt, _ := p.Text()
- item.Text = trimQuestionPrefix(txt)
- //fmt.Println("1111111111111111112222222222222222222222222222222 text:", txt, item.Text)
- if tag == 4 {
- ptag, err := li1.FindElement(selenium.ByXPATH, "./div/div/div/div/div/div/div/p")
- if err != nil {
- fmt.Printf("简单题err:%v\n", err)
- break
- }
- item.Text = TrimSpace(item.Text)
- item.Text = ParseHan(item.Text)
- /*itemTxt := ""
- itemList := strings.Split(item.Text, ".")
- if len(itemList) > 1 {
- for index, v := range itemList {
- if index == 0 {
- continue
- }
- itemTxt = itemTxt + v
- }
- item.Text = strings.TrimSpace(itemTxt)
- }
- */
- //fmt.Println("1111111111111111112222222222222222222222222222222 text finishi:", item.Text)
- anserItem := &AnswerInfo{Ptag: &ElementInfo{Element: ptag}}
- item.AnswerArray = append(item.AnswerArray, anserItem)
- ret = append(ret, item)
- continue
- } else {
- // 题目选项
- ol, _ := li1.FindElement(selenium.ByXPATH, "./div/div/ol")
- lis, _ := ol.FindElements(selenium.ByXPATH, "./li")
- for _, li := range lis {
- answerIterm := AnswerInfo{}
- if tag == 2 {
- radio, err := li.FindElement(selenium.ByXPATH, "./label/span/input")
- if err != nil {
- return nil, err
- }
- answerIterm.Radio = &ElementInfo{Element: radio}
- answer, err := li.FindElement(selenium.ByXPATH, "./label/div/span")
- if err != nil {
- return nil, err
- }
- txt, _ := answer.Text()
- answerIterm.Text = txt
- //fmt.Printf("收集题目答案:%s\n", txt)
- } else if tag == 1 || tag == 3 {
- radio, err := li.FindElement(selenium.ByXPATH, "./label/span/input")
- if err != nil {
- return nil, err
- }
- answerIterm.Radio = &ElementInfo{Element: radio}
- answer, err := li.FindElement(selenium.ByXPATH, "./label/div/span")
- if err != nil {
- return nil, err
- }
- txt, _ := answer.Text()
- answerIterm.Text = txt
- //fmt.Printf("收集题目答案:%s\n", txt)
- if tag == 3 {
- txt, _ := radio.GetAttribute("class")
- if strings.Contains(txt, "ng-not-empty") {
- //radio.Click()
- tryClick(wd, radio)
- }
- }
- //ppp, _ := radio.FindElement(selenium.ByXPATH, "./following-sibling::span")
- //txt, _ = ppp.Text()
- //fmt.Printf("kkkkkkkkkkkkkkkkkkkaa:%s,%s\n", txt, answerIterm.Text)
- }
- item.AnswerArray = append(item.AnswerArray, &answerIterm)
- }
- }
- ret = append(ret, item)
- }
- return ret, nil
- }
- func trimQuestionPrefix(txt string) string {
- if len(txt) < 2 {
- return txt
- }
- regstr := `^[1-9][0-9]*(\.|、|.)`
- //regstr := `^[1-9][0-9]*、`
- reg := regexp.MustCompile(regstr)
- prefix := reg.FindString(txt)
- return txt[len(prefix):]
- }
- func examHandleQuestion(wd selenium.WebDriver, specialCourse bool) ([]QuestionInfo, error) {
- if specialCourse {
- return examHandleSpecialQuestion(wd)
- }
- err := wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//li[@class='subject ng-scope text']"), time.Duration(config.Conf.Timeout)*time.Second)
- if err != nil {
- return examHandleSimpleAnswer(wd)
- }
- questionClasses, _ := wd.FindElements(selenium.ByXPATH, "//li[@class='subject ng-scope text']")
- ret := []QuestionInfo{}
- for _, v := range questionClasses {
- p, err := v.FindElement(selenium.ByXPATH, "./div/div/div/span/p[@class='ng-scope']")
- if err != nil {
- return nil, err
- }
- txt, _ := p.Text()
- //fmt.Printf("题类%s\n", txt)
- className := ""
- tag := 0
- // 题目类型
- if strings.Contains(txt, "单项选择") || strings.Contains(txt, "单选") {
- className = "subject ng-scope single_selection"
- tag = 1
- } else if strings.Contains(txt, "判断") {
- className = "subject ng-scope true_or_false"
- tag = 2
- } else if strings.Contains(txt, "多项选择题") || strings.Contains(txt, "多选") {
- tag = 3
- className = "subject ng-scope multiple_selection"
- } else if strings.Contains(txt, "计算题") || strings.Contains(txt, "简答题") {
- tag = 4
- className = "subject ng-scope short_answer"
- }
- if className == "" {
- continue
- }
- p = v
- path := fmt.Sprintf("./following-sibling::li[@class='%s']", className)
- for {
- item := QuestionInfo{Tag: tag}
- // 题目
- p, err = p.FindElement(selenium.ByXPATH, path)
- if err != nil {
- //fmt.Printf("err:%v\n", err)
- break
- }
- x, err := p.FindElement(selenium.ByXPATH, "./div/div/div/span/p[@class='ng-scope']")
- if err != nil {
- break
- }
- txt, _ := x.Text()
- // 题目描述
- txt = strings.TrimSpace(txt)
- item.Text = trimQuestionPrefix(txt)
- if tag == 4 {
- ptag, err := p.FindElement(selenium.ByXPATH, "./div/div/div/div/div/div/div/p")
- if err != nil {
- fmt.Printf("计算题err:%v\n", err)
- break
- }
- anserItem := &AnswerInfo{Ptag: &ElementInfo{Element: ptag}}
- item.AnswerArray = append(item.AnswerArray, anserItem)
- ret = append(ret, item)
- continue
- }
- // 题目选项
- ol, _ := p.FindElement(selenium.ByXPATH, "./div/div/ol")
- lis, _ := ol.FindElements(selenium.ByXPATH, "./li")
- for _, li := range lis {
- answerIterm := AnswerInfo{}
- if tag == 2 {
- radio, err := li.FindElement(selenium.ByXPATH, "./label/span/input")
- if err != nil {
- return nil, err
- }
- answerIterm.Radio = &ElementInfo{Element: radio}
- answer, err := li.FindElement(selenium.ByXPATH, "./label/div/span")
- if err != nil {
- return nil, err
- }
- txt, _ := answer.Text()
- answerIterm.Text = txt
- } else if tag == 1 || tag == 3 {
- radio, err := li.FindElement(selenium.ByXPATH, "./label/span/input")
- if err != nil {
- return nil, err
- }
- answerIterm.Radio = &ElementInfo{Element: radio}
- answer, err := li.FindElement(selenium.ByXPATH, "./label/div/span/p")
- if err != nil {
- return nil, err
- }
- txt, _ := answer.Text()
- answerIterm.Text = txt
- if tag == 3 {
- txt, _ := radio.GetAttribute("class")
- if strings.Contains(txt, "ng-not-empty") {
- //radio.Click()
- tryClick(wd, radio)
- }
- }
- //ppp, _ := radio.FindElement(selenium.ByXPATH, "./following-sibling::span")
- //txt, _ = ppp.Text()
- //fmt.Printf("kkkkkkkkkkkkkkkkkkkaa:%s,%s\n", txt, answerIterm.Text)
- }
- item.AnswerArray = append(item.AnswerArray, &answerIterm)
- }
- ret = append(ret, item)
- }
- }
- return ret, nil
- }
- func examHandleQuestion2(wd selenium.WebDriver, specialCourse bool) ([]QuestionInfo, error) {
- if specialCourse {
- return examHandleSpecialQuestion(wd)
- }
- fmt.Printf("xxxxxx1\n")
- err := wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//li[contains(@class, 'subject ng-scope short_answer')]"), time.Duration(config.Conf.Timeout)*time.Second)
- if err == nil {
- return examHandleSimpleAnswer(wd)
- }
- err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//li[contains(@class, 'subject ng-scope ')]"), time.Duration(config.Conf.Timeout)*time.Second)
- if err != nil {
- return nil, errors.New("未找到题")
- }
- fmt.Printf("xxxx2\n")
- questionClasses, _ := wd.FindElements(selenium.ByXPATH, "//li[contains(@class, 'subject ng-scope ')]")
- ret := []QuestionInfo{}
- fmt.Printf("count:%v\n", len(questionClasses))
- for _, v := range questionClasses {
- attr, _ := v.GetAttribute("class")
- fmt.Printf("attr:%v\n", attr)
- tag := 0
- if strings.Contains(attr, "single_selection") {
- tag = 1
- } else if strings.Contains(attr, "true_or_false") {
- tag = 2
- } else if strings.Contains(attr, "multiple_selection") {
- tag = 3
- } else if strings.Contains(attr, "short_answer") {
- tag = 4
- }
- if tag == 0 {
- continue
- }
- item := QuestionInfo{Tag: tag}
- // 题目
- p := v
- x, err := p.FindElement(selenium.ByXPATH, "./div/div/div/span/p[@class='ng-scope']")
- if err != nil {
- x, err = p.FindElement(selenium.ByXPATH, "./div/div/div/span/p[@class='MsoNormal ng-scope']")
- if err != nil {
- break
- }
- }
- txt, _ := x.Text()
- // 题目描述
- txt = strings.TrimSpace(txt)
- item.Text = trimQuestionPrefix(txt)
- fmt.Printf("题目描述:%v\n", txt)
- if tag == 4 {
- ptag, err := p.FindElement(selenium.ByXPATH, "./div/div/div/div/div/div/div/p")
- if err != nil {
- fmt.Printf("计算题err:%v\n", err)
- break
- }
- anserItem := &AnswerInfo{Ptag: &ElementInfo{Element: ptag}}
- item.AnswerArray = append(item.AnswerArray, anserItem)
- ret = append(ret, item)
- continue
- }
- // 题目选项
- ol, _ := p.FindElement(selenium.ByXPATH, "./div/div/ol")
- lis, _ := ol.FindElements(selenium.ByXPATH, "./li")
- for _, li := range lis {
- answerIterm := AnswerInfo{}
- if tag == 2 {
- radio, err := li.FindElement(selenium.ByXPATH, "./label/span/input")
- if err != nil {
- return nil, err
- }
- answerIterm.Radio = &ElementInfo{Element: radio}
- answer, err := li.FindElement(selenium.ByXPATH, "./label/div/span")
- if err != nil {
- return nil, err
- }
- txt, _ := answer.Text()
- answerIterm.Text = txt
- fmt.Printf("选项:%v\n", answerIterm.Text)
- } else if tag == 1 || tag == 3 {
- radio, err := li.FindElement(selenium.ByXPATH, "./label/span/input")
- if err != nil {
- return nil, err
- }
- answerIterm.Radio = &ElementInfo{Element: radio}
- answer, err := li.FindElement(selenium.ByXPATH, "./label/div/span/p")
- if err != nil {
- return nil, err
- }
- txt, _ := answer.Text()
- answerIterm.Text = txt
- if tag == 3 {
- txt, _ := radio.GetAttribute("class")
- if strings.Contains(txt, "ng-not-empty") {
- //radio.Click()
- tryClick(wd, radio)
- }
- }
- fmt.Printf("选项:%v\n", answerIterm.Text)
- //ppp, _ := radio.FindElement(selenium.ByXPATH, "./following-sibling::span")
- //txt, _ = ppp.Text()
- //fmt.Printf("kkkkkkkkkkkkkkkkkkkaa:%s,%s\n", txt, answerIterm.Text)
- }
- item.AnswerArray = append(item.AnswerArray, &answerIterm)
- }
- ret = append(ret, item)
- }
- return ret, nil
- }
- func examHandleMatch(wd selenium.WebDriver, questions []QuestionInfo, m map[string][]string) error {
- err := chooseAnswer(wd, questions, m)
- if err != nil {
- if false {
- fmt.Printf("err:%v\n", err)
- c := ""
- fmt.Printf("等待输入\n")
- fmt.Scanln(&c)
- m, _ = LoadXlsx(fmt.Sprintf("%s.xlsx", "思想道德修养与法律基础"))
- return examHandleMatch(wd, questions, m)
- }
- return err
- }
- return nil
- }
- func tryEqual(a string, b string) bool {
- if a == b {
- return true
- }
- if !strings.Contains(a, b) {
- return false
- }
- index := strings.Index(a, b)
- for i := 0; i < index; i++ {
- if (a[i] <= 'z' && a[i] >= 'a') || (a[i] >= '0' && a[i] <= '1') || (a[i] <= 'Z' && a[i] >= 'A') {
- return false
- }
- }
- for i := index + len(b); i < len(a); i++ {
- if (a[i] <= 'z' && a[i] >= 'a') || (a[i] >= '0' && a[i] <= '1') || (a[i] <= 'Z' && a[i] >= 'A') {
- return false
- }
- }
- return true
- }
- func examHandleSubmit(wd selenium.WebDriver) error {
- // 交卷
- button1, err := wd.FindElement(selenium.ByXPATH, "//a[@class='button button-green ng-scope' and text()='交卷']")
- if err != nil {
- return err
- }
- //button1.Click()
- tryClick(wd, button1)
- time.Sleep(2 * time.Second)
- // 弹窗中的确定
- active, _ := wd.ActiveElement()
- button2s, err := active.FindElements(selenium.ByXPATH, "//button[text()='确定']")
- if err != nil {
- return err
- }
- for _, button2 := range button2s {
- txt, _ := button2.Text()
- if txt == "确定" {
- //button2.Click()
- tryClick(wd, button2)
- time.Sleep(2 * time.Second)
- return nil
- }
- }
- return errors.New("交卷未找到确定按钮")
- }
- func examHandle(wd selenium.WebDriver, courseId, moduleId, id string, qustionM map[string][]string, specialCourse bool) error {
- cookie, _ := getCookies(wd)
- finsh, submited, noScore := checkExamFinish(id, cookie)
- if noScore {
- fmt.Printf("不计分,该试题不做\n")
- return nil
- }
- if finsh {
- fmt.Printf("试题达到最大提交次数\n")
- return nil
- }
- if submited {
- isFinsh := checkExamScore(id, cookie)
- if isFinsh {
- fmt.Printf("已完成该试题,并满足分数\n")
- return nil
- } else {
- fmt.Printf("已完成该试题,不满足分数,继续答题\n")
- }
- }
- // 跳转页面
- if err := examHandleJump(wd, courseId, moduleId, id); err != nil {
- return err
- }
- // 点击答题按钮
- if err := examHandleStart(wd); err != nil {
- return err
- }
- // 收集题目和答案选项
- questions, err := examHandleQuestion2(wd, specialCourse)
- if err != nil {
- fmt.Printf("examhandleQuestion:%v\n")
- if strings.Contains(err.Error(), "未找到题") {
- url, _ := wd.CurrentURL()
- wd.Get(url)
- fmt.Printf("再次尝试:%s\n", url)
- questions, err = examHandleQuestion(wd, specialCourse)
- if err != nil {
- return err
- }
- }
- }
- if true {
- //time.Sleep(4000 * time.Second)
- }
- fmt.Println("--------------------------------------------------------题目和答案:", questions)
- // 匹配题库并选择答案
- fmt.Printf("*****************开始匹配答案\n")
- if err := examHandleMatch(wd, questions, qustionM); err != nil {
- return err
- }
- fmt.Printf("examHandleMatch:%v\n", err)
- if false {
- //time.Sleep(4000*time.Second)
- fmt.Println("请输入:")
- sal := ""
- fmt.Scanln(&sal)
- //return nil
- }
- // 提交试卷
- fmt.Printf("开始提交\n")
- if config.Conf.SleepTime > 0 {
- fmt.Printf("等待%d秒提交\n", config.Conf.SleepTime)
- time.Sleep(time.Duration(config.Conf.SleepTime) * time.Second)
- }
- err = examHandleSubmit(wd)
- fmt.Printf("examHandleSubmit:%v\n", err)
- if false {
- //time.Sleep(4000*time.Second)
- fmt.Println("请输入2:")
- sal := ""
- fmt.Scanln(&sal)
- }
- return err
- }
- func checkExamScore(id string, cookie string) (finish bool) {
- url := fmt.Sprintf("https://lms.ouchn.cn/api/exams/%s/submissions", id)
- request, err := http.NewRequest("GET", url, nil)
- if err != nil {
- return false
- }
- request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- request.Header.Set("Cookie", cookie)
- request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
- //request.Header.Set("Host", "chengdu.ouchn.cn")
- client := http.Client{}
- resp, err := client.Do(request)
- if err != nil {
- return false
- }
- defer resp.Body.Close()
- respBytes, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return false
- }
- examScore := gjson.GetBytes(respBytes, "exam_score").Int()
- fmt.Println("分数:", examScore, " 最低要求分数:", config.Conf.MinScore)
- if int(examScore) >= config.Conf.MinScore {
- return true
- }
- return false
- }
- func checkExamFinish(id string, cookie string) (finish bool, submited bool, noScore bool) {
- url := fmt.Sprintf("https://lms.ouchn.cn/api/exams/%s", id)
- request, err := http.NewRequest("GET", url, nil)
- if err != nil {
- return false, false, false
- }
- request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- request.Header.Set("Cookie", cookie)
- request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
- //request.Header.Set("Host", "chengdu.ouchn.cn")
- client := http.Client{}
- resp, err := client.Do(request)
- if err != nil {
- return false, false, false
- }
- defer resp.Body.Close()
- respBytes, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return false, false, false
- }
- scorePercentage := gjson.GetBytes(respBytes, "score_percentage").String()
- if scorePercentage == "0" || scorePercentage == "0.0" || scorePercentage == "0.00" {
- return true, false, true
- }
- submitTimes := gjson.GetBytes(respBytes, "submit_times").Int()
- submittedTimes := gjson.GetBytes(respBytes, "submitted_times").Int()
- if submittedTimes > 0 {
- submited = true
- }
- if submitTimes == submittedTimes && submitTimes > 0 {
- return true, submited, false
- }
- return false, submited, false
- }
- func isSpecialCourse(title string) bool {
- if title == "斜弱视技术" || title == "常见眼病诊断与处理" || title == "角膜接触镜并发症处理" {
- return true
- }
- for _, v := range config.Conf.SpecialCourses {
- if v == title {
- return true
- }
- }
- return false
- }
- func finishUploadId(uploadId int64, moduleId string, cookie string) error {
- rBody := make(map[string]int64)
- rBody["upload_id"] = uploadId
- rByte, _ := json.Marshal(rBody)
- url := fmt.Sprintf("https://lms.ouchn.cn/api/course/activities-read/%s", moduleId)
- request, err := http.NewRequest("POST", url, bytes.NewBuffer(rByte))
- if err != nil {
- return err
- }
- request.Header.Set("Content-Type", "application/json")
- request.Header.Set("Cookie", cookie)
- request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36")
- //request.Header.Set("Host", "chengdu.ouchn.cn")
- client := http.Client{}
- resp, err := client.Do(request)
- if err != nil {
- return err
- }
- defer resp.Body.Close()
- respBytes, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return err
- }
- if true {
- fmt.Println("do material resp:", string(respBytes))
- }
- return nil
- }
- func finishMaterial(uploadIds []int64, moduleId string, cookie string) {
- for _, v := range uploadIds {
- finishUploadId(v, moduleId, cookie)
- time.Sleep(time.Duration(config.Conf.VideoInterval) * time.Second)
- }
- }
- func doMaterial(moduleId string, cookie string) {
- uploadIds, _ := getUploadIds(moduleId, cookie)
- if len(uploadIds) > 0 {
- finishMaterial(uploadIds, moduleId, cookie)
- }
- }
- func CourseHandle(wd selenium.WebDriver, username string) error {
- title, err := wd.Title()
- if title == "" {
- return nil
- }
- array := strings.Split(title, "-")
- title = array[0]
- title = strings.TrimSpace(title)
- cookie, err := getCookies(wd)
- if err != nil {
- return err
- }
- fmt.Printf("***************正在处理%s课程%s\n", username, title)
- specialCourse := isSpecialCourse(title)
- fmt.Printf("is special:%v\n", specialCourse)
- questionM, _ := LoadXlsx(fmt.Sprintf("%s.xlsx", title))
- // 获取课程id
- time.Sleep(2 * time.Second)
- src, _ := wd.CurrentURL()
- courseId := getCourseId(src)
- if courseId == "" {
- return errors.New("课程id获取失败")
- }
- fmt.Printf("课程id:%s\n", courseId)
- // 获取课程所有栏目
- modules, err := getCourseModules(courseId, cookie, specialCourse)
- if err != nil {
- return errors.New(fmt.Sprintf("获取module信息失败:%s", err.Error()))
- }
- fmt.Printf("modules:%v\n", modules)
- examCount := 0
- for _, module := range modules {
- fmt.Printf("***课程:%s 栏目:%s\n", title, module.Name)
- /*if specialCourse && (config.Conf.Target == 1 || config.Conf.Target == 3) && (!strings.Contains(module.Name, "形考任务") &&
- !strings.Contains(module.Name, "形成性考核") &&
- !strings.Contains(module.Name, "形考作业") &&
- !strings.Contains(module.Name, "课程考核") &&
- !strings.Contains(module.Name, "大作业") &&
- !strings.Contains(module.Name, "考试考核")) {
- fmt.Println("module name:", module.Name)
- continue
- }*/
- if strings.Contains(module.Name, "专题一") ||
- strings.Contains(module.Name, "专题二") ||
- strings.Contains(module.Name, "专题三") ||
- strings.Contains(module.Name, "专题四") ||
- strings.Contains(module.Name, "专题五") ||
- strings.Contains(module.Name, "总论 ") {
- //continue
- }
- if false {
- if !strings.Contains(module.Name, "专题三") {
- continue
- }
- }
- // 获取某栏目下的试题和视频数据
- moduleInfo, err := GetModuleInfo(courseId, module.ModuleId, cookie)
- if err != nil {
- return errors.New(fmt.Sprintf("获取module(%s)详细信息失败:%s", module.Name, err.Error()))
- }
- //fmt.Println("2222222222222:", moduleInfo)
- // 处理网页数据
- if false {
- for _, info := range moduleInfo.TxtInfos {
- fmt.Printf("*****正在处理网页数据:%s\n", info.Name)
- url := MakeTxtUrl(courseId, module.ModuleId, info.Id)
- wd.Get(url)
- count := 0
- for count < 10 {
- curl, _ := wd.CurrentURL()
- if strings.Contains(curl, info.Id) {
- time.Sleep(5 * time.Second)
- break
- }
- count++
- time.Sleep(1 * time.Second)
- }
- }
- }
- if (config.Conf.Target == 1 || config.Conf.Target == 2) && !strings.Contains(title, "国家开放大学学习指南") {
- // 处理视频数据
- for _, info := range moduleInfo.VedioInfos {
- if config.Conf.HandlePage {
- if info.Type == 1 {
- fmt.Printf("*****正在处理网页数据:%s\n", info.Name)
- url := MakeTxtUrl(courseId, module.ModuleId, info.Id)
- wd.Get(url)
- count := 0
- for count < 10 {
- curl, _ := wd.CurrentURL()
- if strings.Contains(curl, info.Id) {
- time.Sleep(5 * time.Second)
- break
- }
- count++
- time.Sleep(1 * time.Second)
- }
- }
- }
- if info.Type == 2 {
- fmt.Printf("*****正在处理视频数据:%s\n", info.Name)
- if info.Stype == "material" {
- doMaterial(info.Id, cookie)
- continue
- }
- url := MakeTxtUrl(courseId, module.ModuleId, info.Id)
- wd.Get(url)
- cookie, _ := getCookies(wd)
- // 特殊视频
- if info.Stype == "web_link" {
- array := strings.Split(info.Name, ":")
- if len(array) > 1 {
- array[0] = array[1]
- }
- str := fmt.Sprintf("//iframe[contains(@ng-src, '%s')]", array[0])
- wd.WaitWithTimeout(Displayed(selenium.ByXPATH, str), time.Duration(config.Conf.Timeout)*time.Second)
- continue
- }
- err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//button[@class='mvp-toggle-play mvp-first-btn-margin']"), time.Duration(config.Conf.Timeout)*time.Second)
- if err != nil {
- wd.Get(url)
- err = wd.WaitWithTimeout(Displayed(selenium.ByXPATH, "//button[@class='mvp-toggle-play mvp-first-btn-margin']"), time.Duration(config.Conf.Timeout)*time.Second)
- if err != nil {
- fmt.Printf("获取播放按钮失败\n")
- }
- continue
- //return err
- }
- playButton, _ := wd.FindElement(selenium.ByXPATH, "//button[@class='mvp-toggle-play mvp-first-btn-margin']")
- er := playButton.Click()
- //er := tryClick(wd, playButton)
- if er != nil {
- fmt.Printf("播放点击失败:%v\n", er)
- return er
- }
- //fmt.Printf("cookie:%s\n", cookie)
- time.Sleep(time.Duration(config.Conf.VideoInterval) * time.Second)
- //er = tryClick(wd, playButton)
- //if er != nil {
- // fmt.Printf("停止播放点击失败:%v\n", er)
- //}
- //wd.Get(fmt.Sprintf("https://lms.ouchn.cn/course/%s/ng#/my-stat", courseId))
- //time.Sleep(2*time.Second)
- err := VedioCompleteHandle(cookie, info.Id)
- if err != nil {
- fmt.Printf(" 视频%s处理失败(%s)\n", info.Name, err.Error())
- return err
- }
- //time.Sleep(10000*time.Second)
- }
- }
- }
- if config.Conf.Target == 1 || config.Conf.Target == 3 {
- // 处理试题数据
- for _, info := range moduleInfo.ExamInfos {
- fmt.Printf("*****正在处理试题数据:%s\n", info.Name)
- if len(questionM) == 0 && !config.Conf.QuestionRandom {
- fmt.Printf("无法处理试题,课程%s未提供答案\n", title)
- break
- }
- //if !strings.Contains(info.Name, "考试任务二") {
- // continue
- //}
- examCount++
- fmt.Printf("count:%d\n", examCount)
- // 测试用的
- if examCount < 0 {
- continue
- }
- err := examHandle(wd, courseId, module.ModuleId, info.Id, questionM, specialCourse)
- if err != nil {
- fmt.Printf(" 试题%s处理失败(%s)\n", info.Name, err.Error())
- //time.Sleep(1000 * time.Second)
- if strings.Contains(err.Error(), "选项为空") ||
- strings.Contains(err.Error(), "答案为空") {
- continue
- }
- return err
- }
- time.Sleep(1 * time.Second)
- //time.Sleep(1000*time.Second)
- }
- //time.Sleep(1000*time.Second)
- }
- // 再次处理网页数据
- if true {
- for i := 0; i < config.Conf.VisitCount; i++ {
- for _, info := range moduleInfo.TxtInfos {
- fmt.Printf("*****正在点击网页数据:%s\n", info.Name)
- url := MakeTxtUrl(courseId, module.ModuleId, info.Id)
- wd.Get(url)
- count := 0
- for count < 10 {
- curl, _ := wd.CurrentURL()
- if strings.Contains(curl, info.Id) {
- time.Sleep(2 * time.Second)
- break
- }
- count++
- time.Sleep(1 * time.Second)
- }
- }
- }
- }
- }
- if true {
- //time.Sleep(1000*time.Second)
- }
- return nil
- }
|