1 // mmc -- Mattermost client
2 // Copyright (C) 2023 Sergey Matveev <stargrave@stargrave.org>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU Affero General Public License as
6 // published by the Free Software Foundation, either version 3 of the
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU Affero General Public License for more details.
14 // You should have received a copy of the GNU Affero General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
37 "github.com/davecgh/go-spew/spew"
38 "github.com/mattermost/mattermost-server/v6/model"
39 "go.stargrave.org/mmc"
48 Newwin = flag.String("newwin", "cmd/newwin", "Path to newwin command")
49 DebugFifo = flag.String("debug", "debug", "Path to debug FIFO to be created")
54 func rewriteIfChanged(fn string, data string) {
55 if their, err := os.ReadFile(fn); err != nil ||
56 bytes.Compare([]byte(data), their) != 0 {
57 if err = os.WriteFile(fn, []byte(data), 0o666); err != nil {
64 entrypoint := flag.String("entrypoint", "mm.rnd.stcnet.ru", "Entrypoint")
65 notifyCmd := flag.String("notify", "cmd/notify", "Path to notification handler")
66 heartbeatCh := flag.String("heartbeat-ch", "town-square", "Channel for heartbeating")
68 log.SetFlags(log.Lshortfile)
69 log.SetOutput(os.Stdout)
70 UmaskCur = syscall.Umask(0)
71 syscall.Umask(UmaskCur)
75 DebugFd, err = os.OpenFile(
76 *DebugFifo, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
84 login, password := mmc.FindInNetrc(*entrypoint)
85 if login == "" || password == "" {
86 log.Fatalln("no credentials found for:", *entrypoint)
88 c := model.NewAPIv4Client("https://" + *entrypoint)
89 c.Login(login, password)
90 me, resp, err := c.GetMe("")
93 spew.Fdump(DebugFd, resp)
98 spew.Fdump(DebugFd, me)
100 log.Println("logged in")
102 time.Sleep(mmc.SleepTime)
103 teams, resp, err := c.GetTeamsForUser(me.Id, "")
106 spew.Fdump(DebugFd, resp)
111 spew.Fdump(DebugFd, teams)
115 Users := make(map[string]*model.User)
116 for pageNum := 0; ; pageNum++ {
117 time.Sleep(mmc.SleepTime)
118 page, resp, err := c.GetUsers(pageNum, PerPage, "")
121 spew.Fdump(DebugFd, resp)
126 spew.Fdump(DebugFd, page)
128 for _, u := range page {
131 if len(page) < PerPage {
136 var updateQueue []string
137 LastSent := time.Now()
138 for _, u := range Users {
139 pth := path.Join("users", strings.ReplaceAll(u.Username, ".", "_"))
140 os.MkdirAll(pth, 0777)
142 path.Join(pth, "name"),
143 fmt.Sprintf("%s %s\n", u.FirstName, u.LastName),
145 rewriteIfChanged(path.Join(pth, "email"), u.Email+"\n")
146 rewriteIfChanged(path.Join(pth, "id"), u.Id+"\n")
147 if _, err := os.Stat(path.Join(pth, mmc.OutRec)); err != nil &&
148 errors.Is(err, fs.ErrNotExist) {
149 if _, err = os.OpenFile(
150 path.Join(pth, mmc.OutRec), os.O_WRONLY|os.O_CREATE, 0o666,
155 updateQueue = append(updateQueue,
156 pth, u.Id+"__"+me.Id,
157 pth, me.Id+"__"+u.Id,
160 statusPth := path.Join(pth, "status")
162 if err := syscall.Mkfifo(statusPth, 0666); err != nil {
165 go func(u *model.User) {
167 time.Sleep(mmc.SleepTime)
168 fd, err := os.OpenFile(
169 statusPth, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
172 log.Println("OpenFile:", statusPth, err)
175 status, resp, err := c.GetUserStatus(u.Id, "")
178 spew.Fdump(DebugFd, resp)
180 log.Println("GetUserStatus:", err)
185 spew.Fdump(DebugFd, status)
187 fmt.Fprintf(fd, "%s\n", status.Status)
192 pth = path.Join(pth, "in")
194 if err := syscall.Mkfifo(pth, 0666); err != nil {
197 go func(u *model.User) {
198 var dc *model.Channel
200 fd, err := os.OpenFile(pth, os.O_RDONLY, os.FileMode(0666))
204 data, err := io.ReadAll(fd)
210 dc, resp, err = c.CreateDirectChannel(me.Id, u.Id)
213 spew.Fdump(DebugFd, resp)
215 log.Println("CreateDirectChannel:", err)
219 spew.Fdump(DebugFd, dc)
222 if _, err = makePost(c, dc.Id, string(data)); err != nil {
223 log.Println("makePost:", err)
225 LastSent = time.Now()
230 Chans := make(map[string]*model.Channel)
231 time.Sleep(mmc.SleepTime)
232 page, resp, err := c.GetChannelsForTeamForUser(Team.Id, me.Id, false, "")
235 spew.Fdump(DebugFd, resp)
240 spew.Fdump(DebugFd, page)
242 for _, ch := range page {
247 pth := path.Join("chans", strings.ReplaceAll(ch.Name, ".", "_"))
248 updateQueue = append(updateQueue, pth, ch.Id)
249 os.MkdirAll(pth, 0777)
250 rewriteIfChanged(path.Join(pth, "id"), ch.Id+"\n")
251 rewriteIfChanged(path.Join(pth, "info"), fmt.Sprintf(
257 if _, err := os.Stat(path.Join(pth, mmc.OutRec)); err != nil &&
258 errors.Is(err, fs.ErrNotExist) {
259 if _, err = os.OpenFile(
260 path.Join(pth, mmc.OutRec), os.O_WRONLY|os.O_CREATE, 0o666,
266 usersPth := path.Join(pth, "users")
268 if err := syscall.Mkfifo(usersPth, 0666); err != nil {
271 go func(ch *model.Channel) {
273 time.Sleep(mmc.SleepTime)
274 fd, err := os.OpenFile(
275 usersPth, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
278 log.Println("OpenFile:", usersPth, err)
281 for pageNum := 0; ; pageNum++ {
282 users, resp, err := c.GetUsersInChannel(ch.Id, pageNum, PerPage, "")
285 spew.Fdump(DebugFd, resp)
287 log.Println("GetUsersInChannel:", err)
292 spew.Fdump(DebugFd, users)
294 for _, u := range users {
295 fmt.Fprintf(fd, "%s\n", u.Username)
297 if len(users) < PerPage {
305 pth = path.Join(pth, "in")
307 if err := syscall.Mkfifo(pth, 0666); err != nil {
310 go func(ch *model.Channel) {
312 fd, err := os.OpenFile(pth, os.O_RDONLY, os.FileMode(0666))
316 data, err := io.ReadAll(fd)
321 if _, err = makePost(c, ch.Id, string(data)); err != nil {
322 log.Println("makePost:", err)
324 LastSent = time.Now()
330 log.Println("syncing", len(Chans)+len(Users), "rooms")
331 for len(updateQueue) > 0 {
332 err := updatePosts(c, Users, updateQueue[0], updateQueue[1])
334 log.Println("updatePosts:", err)
336 updateQueue = updateQueue[2:]
338 log.Println("sync done")
342 os.MkdirAll("file", 0777)
343 pthGet := path.Join("file", "get")
345 if err := syscall.Mkfifo(pthGet, 0666); err != nil {
348 pthOut := path.Join("file", "out")
350 if err := syscall.Mkfifo(pthOut, 0666); err != nil {
354 time.Sleep(mmc.SleepTime)
355 fd, err := os.OpenFile(pthGet, os.O_RDONLY, os.FileMode(0666))
359 data, err := io.ReadAll(fd)
364 fileId := strings.TrimRight(string(data), " \n")
365 if len(fileId) == 0 {
368 fi, resp, err := c.GetFileInfo(fileId)
370 spew.Fdump(DebugFd, fi, resp)
380 data, resp, err = c.GetFile(fileId)
383 spew.Fdump(DebugFd, resp)
388 fd, err = os.OpenFile(
389 pthOut, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
395 w := tar.NewWriter(fd)
396 if err = w.WriteHeader(&tar.Header{
397 Format: tar.FormatPAX,
398 Typeflag: tar.TypeReg,
400 Size: int64(len(data)),
402 ModTime: time.Unix(fi.CreateAt/1000, 0),
403 PAXRecords: map[string]string{
405 "MM.MIMEType": fi.MimeType,
412 if _, err = io.Copy(w, bytes.NewReader(data)); err != nil {
425 needsShutdown := make(chan os.Signal)
426 wc, err := model.NewWebSocketClient4("wss://"+*entrypoint, c.AuthToken)
432 t := time.NewTicker(time.Minute)
436 if time.Now().Before(LastSent.Add(time.Minute)) {
439 wc.SendMessage("ping", nil)
440 if *heartbeatCh != "" {
441 if _, _, err = c.ViewChannel(
443 &model.ChannelView{ChannelId: Chans[*heartbeatCh].Id},
445 log.Println("ChannelView:", err)
448 case <-wc.PingTimeoutChannel:
449 log.Println("PING timeout")
450 needsShutdown <- syscall.SIGTERM
451 case e := <-wc.EventChannel:
452 if e == nil || !e.IsValid() {
457 spew.Fdump(DebugFd, e.EventType(), data)
460 if userId, ok := data["user_id"]; ok && userId.(string) != "" {
461 user = Users[userId.(string)]
463 log.Println("unknown user for event:", e)
467 switch eventType := e.EventType(); eventType {
468 case model.WebsocketEventTyping:
469 if *notifyCmd != "" {
470 exec.Command(*notifyCmd, "typing: "+user.Username).Run()
472 case model.WebsocketEventPostEdited,
473 model.WebsocketEventPostDeleted,
474 model.WebsocketEventPosted:
475 chName := data["channel_name"].(string)
477 if err = json.NewDecoder(
478 strings.NewReader(data["post"].(string)),
479 ).Decode(&post); err != nil {
483 switch model.ChannelType(data["channel_type"].(string)) {
484 case model.ChannelTypeDirect:
485 userId := strings.TrimPrefix(chName, me.Id+"__")
486 userId = strings.TrimSuffix(userId, "__"+me.Id)
487 user := Users[userId]
489 log.Println("unknown user:", post)
492 recipient = path.Join("users", user.Username)
493 case model.ChannelTypeOpen:
495 case model.ChannelTypePrivate:
497 case model.ChannelTypeGroup:
498 recipient = path.Join("chans", chName)
501 recipient, Users, []mmc.Post{{P: &post, E: eventType}},
505 case model.WebsocketEventStatusChange:
506 log.Println("status change:", user.Username, "->", data["status"].(string))
507 if *notifyCmd != "" {
508 exec.Command(*notifyCmd, fmt.Sprintf(
510 user.Username, data["status"].(string),
513 case model.WebsocketEventHello:
514 case model.WebsocketEventChannelViewed:
518 case resp := <-wc.ResponseChannel:
519 if resp == nil || !resp.IsValid() {
523 spew.Fdump(DebugFd, resp)
525 if text, ok := resp.Data["text"].(string); ok && text == "pong" {
526 LastSent = time.Now()
532 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
535 log.Println("finished")