Skip to content

Commit

Permalink
Merge pull request #53 from far-galaxy/new-ics
Browse files Browse the repository at this point in the history
Добавлено: .ics с синхронизацией
  • Loading branch information
far-galaxy committed Nov 6, 2023
2 parents b25d4e0 + 813fb97 commit 16315de
Show file tree
Hide file tree
Showing 14 changed files with 265 additions and 107 deletions.
14 changes: 11 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,31 @@ require (

require (
github.com/andybalholm/cascadia v1.3.1 // indirect
github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 // indirect
github.com/goccy/go-json v0.8.1 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f // indirect
github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042 // indirect
github.com/lestrrat/go-envload v0.0.0-20180220120943-6ed08b54a570 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pkg/errors v0.8.1 // indirect
github.com/stretchr/testify v1.7.1 // indirect
github.com/syndtr/goleveldb v1.0.0 // indirect
github.com/tebeka/strftime v0.1.5 // indirect
golang.org/x/net v0.7.0 // indirect
)

require (
github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f
github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042 // indirect
github.com/stretchr/testify v1.7.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

require (
github.com/PuerkitoBio/goquery v1.8.1
github.com/gorilla/mux v1.7.3
github.com/mattn/go-sqlite3 v1.14.16 // indirect
github.com/mergestat/timediff v0.0.3
golang.org/x/exp v0.0.0-20230728194245-b0cb94b80691
Expand Down
10 changes: 10 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaB
github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 h1:Ghm4eQYC0nEPnSJdVkTrXpu9KtoVCSo1hg7mtI7G9KU=
github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239/go.mod h1:Gdwt2ce0yfBxPvZrHkprdPPTTS3N5rwmLE8T22KBXlw=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4=
github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20=
Expand Down Expand Up @@ -113,6 +115,7 @@ github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw=
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
Expand Down Expand Up @@ -192,9 +195,12 @@ github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0f
github.com/jackc/puddle v1.1.0/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
github.com/jackc/puddle v1.1.1/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
github.com/jackc/puddle v1.1.3/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 h1:IPJ3dvxmJ4uczJe5YQdrYB16oTJlGSC/OyZDqUk9xX4=
github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869/go.mod h1:cJ6Cj7dQo+O6GJNiMx+Pa94qKj+TG8ONdKHgMNIyyag=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/jonboulle/clockwork v0.1.0 h1:VKV+ZcuP6l3yW9doeqz6ziZGgcynBVQO+obU0+0hcPo=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
Expand All @@ -214,6 +220,8 @@ github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORN
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lestrrat/go-envload v0.0.0-20180220120943-6ed08b54a570 h1:0iQektZGS248WXmGIYOwRXSQhD4qn3icjMpuxwO7qlo=
github.com/lestrrat/go-envload v0.0.0-20180220120943-6ed08b54a570/go.mod h1:BLt8L9ld7wVsvEWQbuLrUZnCMnUmLZ+CGDzKtclrTlE=
github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f h1:sgUSP4zdTUZYZgAGGtN5Lxk92rK+JUFOwf+FT99EEI4=
github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f/go.mod h1:UGmTpUd3rjbtfIpwAPrcfmGf/Z1HS95TATB+m57TPB8=
github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042 h1:Bvq8AziQ5jFF4BHGAEDSqwPW1NJS3XshxbRCxtjFAZc=
Expand Down Expand Up @@ -357,6 +365,8 @@ github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMT
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFdE=
github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpPAyBWyWuQ=
github.com/tebeka/strftime v0.1.5 h1:1NQKN1NiQgkqd/2moD6ySP/5CoZQsKa1d3ZhJ44Jpmg=
github.com/tebeka/strftime v0.1.5/go.mod h1:29/OidkoWHdEKZqzyDLUyC+LmgDgdHo4WAFCDT7D/Ig=
github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
Expand Down
20 changes: 20 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ import (
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"time"

"github.com/gorilla/mux"
"github.com/robfig/cron/v3"
"stud.l9labs.ru/bot/modules/database"
"stud.l9labs.ru/bot/modules/notify"
"stud.l9labs.ru/bot/modules/site"
"stud.l9labs.ru/bot/modules/ssauparser"
"stud.l9labs.ru/bot/modules/tg"
)
Expand Down Expand Up @@ -68,6 +71,23 @@ func main() {
c.Start()
log.Println("Started")
go sheduleCheck()
go handleBot()

router := mux.NewRouter()

router.HandleFunc("/{fileNumber}.ics", site.GetICS).Methods("GET")
server := &http.Server{
Addr: "localhost:8000",
Handler: router,
ReadTimeout: 5 * time.Second,
WriteTimeout: 1 * time.Second,
IdleTimeout: 15 * time.Second,
}

log.Fatal(server.ListenAndServe())
}

func handleBot() {
for update := range *mainbot.Updates {
now := time.Now()
_, err := mainbot.HandleUpdate(update, now)
Expand Down
9 changes: 9 additions & 0 deletions modules/database/database_struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,12 @@ type GroupChatInfo struct {
IsGroup bool
SheduleID int64
}

// .ics календарь
type ICalendar struct {
ID int64 `xorm:"pk"`
IsPersonal bool
L9ID int64 // Используется, если персональное
IsGroup bool
SheduleID int64
}
9 changes: 5 additions & 4 deletions modules/database/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ func Connect(db DB, logger *rotatelogs.RotateLogs) (*xorm.Engine, error) {
&File{},
&TempMsg{},
&GroupChatInfo{},
&ICalendar{},
)
if err != nil {
return nil, err
Expand All @@ -57,17 +58,17 @@ func Connect(db DB, logger *rotatelogs.RotateLogs) (*xorm.Engine, error) {
return engine, nil
}

// Генерация уникального номера для таблицы User
func GenerateID(engine *xorm.Engine) (int64, error) {
// Генерация уникального номера для таблицы table
func GenerateID(engine *xorm.Engine, table any) (int64, error) {
id := rand.Int63n(899999999) + 100000000 // #nosec G404

exists, err := engine.ID(id).Exist(&User{})
exists, err := engine.ID(id).Get(table)
if err != nil {
return 0, err
}

if exists {
return GenerateID(engine)
return GenerateID(engine, table)
}

return id, nil
Expand Down
16 changes: 3 additions & 13 deletions modules/notify/notify.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ func Mailing(bot *tg.Bot, notes []Notify, now time.Time) {
AddTemp(m, tempTime, bot)
}
} else {
if err := sendNextWeek(bot, note, &users[i], now); err != nil {
if err := sendNextWeek(bot, note, &users[i]); err != nil {
log.Println(err)

continue
Expand All @@ -238,24 +238,14 @@ func Mailing(bot *tg.Bot, notes []Notify, now time.Time) {
}

// Рассылка уведомлений о следующей неделе
func sendNextWeek(bot *tg.Bot, note Notify, user *database.TgUser, now time.Time) error {
if err := bot.GetWeekSummary(
func sendNextWeek(bot *tg.Bot, note Notify, user *database.TgUser) error {
return bot.GetWeekSummary(
note.Lesson.Begin,
user,
database.ShedulesInUser{},
-1,
true,
"На этой неделе больше ничего нет\n\nНа фото расписание на следующую неделю",
); err != nil {
return err
}

return bot.CreateICS(
now,
user,
database.ShedulesInUser{},
true,
-1,
)
}

Expand Down
25 changes: 23 additions & 2 deletions modules/notify/shedule_checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,17 +59,38 @@ func CheckGroup(now time.Time, group database.Group, bot *tg.Bot) {
}
}
if len(nAdd) > 0 || len(nDel) > 0 {
tsh := tg.Swap(sh)
var ics []database.ICalendar
q := database.ICalendar{
IsGroup: true,
SheduleID: sh.SheduleID,
}
if err := bot.DB.
Find(&ics, q); err != nil {
log.Println(err)

return
}
for _, i := range ics {
lessons, err := bot.GetSemester(tsh)
if err != nil {
log.Println(err)
}
if err := bot.CreateICSFile(lessons, tsh, i.ID); err != nil {
log.Println(err)
}
}
var str string
str = "‼ Обнаружены изменения в расписании\n"
str = strChanges(nAdd, str, true)
str = strChanges(nDel, str, false)
var users []database.TgUser
if err := bot.DB.
UseBool("isgroup").
UseBool("IsGroup").
Table("ShedulesInUser").
Cols("tgid").
Join("INNER", "TgUser", "TgUser.l9id = ShedulesInUser.l9id").
Find(&users, tg.Swap(sh)); err != nil {
Find(&users, tsh); err != nil {
log.Println(err)
}
for i := range users {
Expand Down
40 changes: 40 additions & 0 deletions modules/site/ics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package site

import (
"fmt"
"net/http"
"os"
"strings"
)

func GetICS(w http.ResponseWriter, r *http.Request) {
path := strings.TrimLeft(r.URL.Path, "/") // Удаление первого слэша

filePath := fmt.Sprintf("./shedules/ics/%s", path)

if _, err := os.Stat(filePath); os.IsNotExist(err) {
http.Error(w, "Файл не найден", http.StatusNotFound)

return
}

fileContent, err := os.ReadFile(filePath)
if err != nil {
http.Error(w, "Ошибка чтения файла", http.StatusInternalServerError)

return
}

w.Header().Set("Content-Type", "text/calendar; charset=utf-8")
w.Header().Set(
"Content-Disposition",
fmt.Sprintf("attachment; filename=\"%s\"", path),
)

// Отправка содержимого файла в ответе
if _, err := w.Write(fileContent); err != nil {
http.Error(w, "", http.StatusInternalServerError)

return
}
}
2 changes: 1 addition & 1 deletion modules/tg/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ func InitUser(db *xorm.Engine, user *tgbotapi.User) (*database.TgUser, error) {

var tgUser database.TgUser
if len(users) == 0 {
l9id, err := database.GenerateID(db)
l9id, err := database.GenerateID(db, &database.User{})
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion modules/tg/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ func (bot *Bot) HandleSummary(user *database.TgUser, query *tgbotapi.CallbackQue
case Week:
err = bot.GetWeekSummary(now[0], user, shedule, dt, isPersonal, "", *query.Message)
case ICS:
err = bot.CreateICS(now[0], user, shedule, isPersonal, dt, *query)
err = bot.CreateICS(user, shedule, isPersonal, *query)
case Connect:
_, err = bot.ConnectShedule(user, shedule, *query.Message)
default:
Expand Down
31 changes: 16 additions & 15 deletions modules/tg/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,23 +89,24 @@ func (bot *Bot) Find(now time.Time, user *database.TgUser, query string) (tgbota
"Вот что я нашёл\nВыбери нужного преподавателя",
GenerateKeyboard(GenerateTeachersArray(allTeachers, user.PosTag == database.Add)),
)
// Если ничего не получено
} else {
var txt string
if siteErr != nil {
bot.Debug.Printf("sasau error: %s", siteErr)
txt = "К сожалению, у меня ничего не нашлось, а на сайте ssau.ru/rasp произошла какая-то ошибка :(\n" +
"Повтори попытку позже"
} else {
txt = "К сожалению, я ничего не нашёл ):\nПроверь свой запрос"
}

return bot.SendMsg(
user,
txt,
nilKey,
)
}
// Если ничего не получено
var txt string
if siteErr != nil {
bot.Debug.Printf("sasau error: %s", siteErr)
txt = "К сожалению, у меня ничего не нашлось, а на сайте ssau.ru/rasp произошла какая-то ошибка :(\n" +
"Повтори попытку позже"
} else {
txt = "К сожалению, я ничего не нашёл ):\nПроверь свой запрос"
}

return bot.SendMsg(
user,
txt,
nilKey,
)

}

// Добавление к результатам поиска в БД результатов поиска на сайте
Expand Down
Loading

0 comments on commit 16315de

Please sign in to comment.