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/>.
38 "github.com/davecgh/go-spew/spew"
39 "github.com/mattermost/mattermost-server/v6/model"
40 "go.stargrave.org/mmc"
43 const CmdFile = "/FILE "
46 Newwin = flag.String("newwin", "cmd/newwin", "Path to newwin command")
47 DebugFifo = flag.String("debug", "", "Path to debug FIFO to be created")
52 func rewriteIfChanged(fn string, data string) {
53 if their, err := os.ReadFile(fn); err != nil ||
54 bytes.Compare([]byte(data), their) != 0 {
55 if err = os.WriteFile(fn, []byte(data), 0o666); err != nil {
62 entrypoint := flag.String("entrypoint", mmc.GetEntrypoint(), "Entrypoint")
63 notifyCmd := flag.String("notify", "cmd/notify", "Path to notification handler")
64 heartbeatCh := flag.String("heartbeat-ch", "town-square", "Channel for heartbeating")
65 userStatusFifo := flag.String("user-status", "", "Path to FIFO for user statuses")
67 log.SetFlags(log.Lshortfile)
68 log.SetOutput(os.Stdout)
69 UmaskCur = syscall.Umask(0)
70 syscall.Umask(UmaskCur)
74 DebugFd, err = os.OpenFile(
75 *DebugFifo, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
83 login, password := mmc.FindInNetrc(*entrypoint)
84 if login == "" || password == "" {
85 log.Fatalln("no credentials found for:", *entrypoint)
87 c := model.NewAPIv4Client("https://" + *entrypoint)
88 c.Login(login, password)
89 me, resp, err := c.GetMe("")
92 spew.Fdump(DebugFd, resp)
97 spew.Fdump(DebugFd, me)
99 log.Println("logged in")
101 time.Sleep(mmc.SleepTime)
102 teams, resp, err := c.GetTeamsForUser(me.Id, "")
105 spew.Fdump(DebugFd, resp)
110 spew.Fdump(DebugFd, teams)
114 var updateQueue []string
115 LastSent := time.Now()
117 Users, err := mmc.GetUsers(c, DebugFd)
122 UsersDC := make(map[string]*model.Channel, len(Users))
123 userIds := make([]string, 0, len(Users))
124 for _, u := range Users {
125 userIds = append(userIds, u.Id)
126 pth := path.Join("users", strings.ReplaceAll(u.Username, ".", "_"))
127 os.MkdirAll(pth, 0777)
129 path.Join(pth, "name"),
130 fmt.Sprintf("%s %s\n", u.FirstName, u.LastName),
132 rewriteIfChanged(path.Join(pth, "email"), u.Email+"\n")
133 rewriteIfChanged(path.Join(pth, "id"), u.Id+"\n")
134 if _, err := os.Stat(path.Join(pth, mmc.OutRec)); err != nil &&
135 errors.Is(err, fs.ErrNotExist) {
136 if _, err = os.OpenFile(
137 path.Join(pth, mmc.OutRec), os.O_WRONLY|os.O_CREATE, 0o666,
143 if fi, err := os.Stat(path.Join(pth, mmc.OutRec)); err == nil && fi.Size() > 0 {
144 time.Sleep(mmc.SleepTime)
145 dc, resp, err := c.CreateDirectChannel(me.Id, u.Id)
148 spew.Fdump(DebugFd, resp)
150 log.Println("CreateDirectChannel:", err)
154 spew.Fdump(DebugFd, dc)
157 updateQueue = append(updateQueue, pth, dc.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)
211 dc, resp, err = c.CreateDirectChannel(me.Id, u.Id)
214 spew.Fdump(DebugFd, resp)
216 log.Println("CreateDirectChannel:", err)
221 spew.Fdump(DebugFd, dc)
224 if _, err = makePost(c, dc.Id, string(data)); err != nil {
225 log.Println("makePost:", err)
227 LastSent = time.Now()
232 UserStatus := make(map[string]string)
233 updateUserStatus := func() {
234 statuses, resp, err := c.GetUsersStatusesByIds(userIds)
237 spew.Fdump(DebugFd, resp)
242 spew.Fdump(DebugFd, teams)
244 for _, s := range statuses {
245 UserStatus[Users[s.UserId].Username] = s.Status
248 if *userStatusFifo != "" {
252 time.Sleep(mmc.SleepTime)
253 fd, err := os.OpenFile(
254 *userStatusFifo, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
257 log.Println("OpenFile:", *userStatusFifo, err)
260 statuses := make(map[string][]string)
261 for name, status := range UserStatus {
262 statuses[status] = append(statuses[status], name)
264 for status := range statuses {
265 if status == "offline" {
268 sort.Strings(statuses[status])
269 fmt.Fprintln(fd, status+":", strings.Join(statuses[status], " "))
276 Chans := make(map[string]*model.Channel)
277 time.Sleep(mmc.SleepTime)
278 page, resp, err := c.GetChannelsForTeamForUser(Team.Id, me.Id, false, "")
281 spew.Fdump(DebugFd, resp)
286 spew.Fdump(DebugFd, page)
288 for _, ch := range page {
293 pth := path.Join("chans", strings.ReplaceAll(ch.Name, ".", "_"))
294 updateQueue = append(updateQueue, pth, ch.Id)
295 os.MkdirAll(pth, 0777)
296 rewriteIfChanged(path.Join(pth, "id"), ch.Id+"\n")
297 rewriteIfChanged(path.Join(pth, "info"), fmt.Sprintf(
303 if _, err := os.Stat(path.Join(pth, mmc.OutRec)); err != nil &&
304 errors.Is(err, fs.ErrNotExist) {
305 if _, err = os.OpenFile(
306 path.Join(pth, mmc.OutRec), os.O_WRONLY|os.O_CREATE, 0o666,
312 usersPth := path.Join(pth, "users")
314 if err := syscall.Mkfifo(usersPth, 0666); err != nil {
317 go func(ch *model.Channel) {
319 time.Sleep(mmc.SleepTime)
320 fd, err := os.OpenFile(
321 usersPth, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
324 log.Println("OpenFile:", usersPth, err)
328 users, resp, err := c.GetUsersInChannel(ch.Id, n, mmc.PerPage, "")
331 spew.Fdump(DebugFd, resp)
333 log.Println("GetUsersInChannel:", err)
338 spew.Fdump(DebugFd, users)
340 for _, u := range users {
341 fmt.Fprintf(fd, "%s\n", u.Username)
343 if len(users) < mmc.PerPage {
351 pth = path.Join(pth, "in")
353 if err := syscall.Mkfifo(pth, 0666); err != nil {
356 go func(ch *model.Channel) {
358 fd, err := os.OpenFile(pth, os.O_RDONLY, os.FileMode(0666))
362 data, err := io.ReadAll(fd)
367 if _, err = makePost(c, ch.Id, string(data)); err != nil {
368 log.Println("makePost:", err)
370 LastSent = time.Now()
375 log.Println("syncing", len(updateQueue)/2, "rooms")
376 for len(updateQueue) > 0 {
377 err := updatePosts(c, Users, updateQueue[0], updateQueue[1])
379 log.Println("updatePosts:", err)
381 updateQueue = updateQueue[2:]
383 log.Println("sync done")
384 if *notifyCmd != "" {
385 exec.Command(*notifyCmd, "sync done").Run()
389 os.MkdirAll("file", 0777)
390 pthGet := path.Join("file", "get")
392 if err := syscall.Mkfifo(pthGet, 0666); err != nil {
395 pthOut := path.Join("file", "out")
397 if err := syscall.Mkfifo(pthOut, 0666); err != nil {
401 time.Sleep(mmc.SleepTime)
402 fd, err := os.OpenFile(pthGet, os.O_RDONLY, os.FileMode(0666))
406 data, err := io.ReadAll(fd)
411 fileId := strings.TrimRight(string(data), " \n")
412 if len(fileId) == 0 {
415 fi, resp, err := c.GetFileInfo(fileId)
417 spew.Fdump(DebugFd, fi, resp)
427 data, resp, err = c.GetFile(fileId)
430 spew.Fdump(DebugFd, resp)
435 fd, err = os.OpenFile(
436 pthOut, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
442 w := tar.NewWriter(fd)
443 if err = w.WriteHeader(&tar.Header{
444 Format: tar.FormatPAX,
445 Typeflag: tar.TypeReg,
447 Size: int64(len(data)),
449 ModTime: time.Unix(fi.CreateAt/1000, 0),
450 PAXRecords: map[string]string{
452 "MM.MIMEType": fi.MimeType,
459 if _, err = io.Copy(w, bytes.NewReader(data)); err != nil {
472 needsShutdown := make(chan os.Signal)
473 wc, err := model.NewWebSocketClient4("wss://"+*entrypoint, c.AuthToken)
479 t := time.NewTicker(time.Minute)
484 if time.Now().Before(LastSent.Add(time.Minute)) {
487 wc.SendMessage("ping", nil)
488 if *heartbeatCh != "" {
489 if _, _, err = c.ViewChannel(
491 &model.ChannelView{ChannelId: Chans[*heartbeatCh].Id},
493 log.Println("ChannelView:", err)
496 case <-wc.PingTimeoutChannel:
497 log.Println("PING timeout")
498 needsShutdown <- syscall.SIGTERM
499 case e := <-wc.EventChannel:
500 if e == nil || !e.IsValid() {
504 spew.Fdump(DebugFd, e)
508 if userId, ok := data["user_id"]; ok && userId.(string) != "" {
509 user = Users[userId.(string)]
511 log.Println("unknown user for event:", e)
515 switch eventType := e.EventType(); eventType {
516 case model.WebsocketEventTyping:
517 if *notifyCmd != "" {
518 exec.Command(*notifyCmd, "typing: "+user.Username).Run()
520 case model.WebsocketEventPostEdited,
521 model.WebsocketEventPostDeleted,
522 model.WebsocketEventPosted:
523 chName, ok := data["channel_name"].(string)
528 if err = json.NewDecoder(
529 strings.NewReader(data["post"].(string)),
530 ).Decode(&post); err != nil {
534 switch model.ChannelType(data["channel_type"].(string)) {
535 case model.ChannelTypeDirect:
536 userId := strings.TrimPrefix(chName, me.Id+"__")
537 userId = strings.TrimSuffix(userId, "__"+me.Id)
538 user := Users[userId]
540 log.Println("unknown user:", post)
543 recipient = path.Join("users", user.Username)
544 case model.ChannelTypeOpen:
546 case model.ChannelTypePrivate:
548 case model.ChannelTypeGroup:
549 recipient = path.Join("chans", chName)
552 recipient, Users, []mmc.Post{{P: &post, E: eventType}},
556 case model.WebsocketEventStatusChange:
557 status := data["status"].(string)
558 UserStatus[user.Username] = status
559 if *notifyCmd != "" {
560 exec.Command(*notifyCmd, fmt.Sprintf(
561 "status: %s -> %s", user.Username, status,
564 case model.WebsocketEventHello:
565 case model.WebsocketEventChannelViewed:
569 case resp := <-wc.ResponseChannel:
570 if resp == nil || !resp.IsValid() {
574 spew.Fdump(DebugFd, resp)
576 if text, ok := resp.Data["text"].(string); ok && text == "pong" {
577 LastSent = time.Now()
583 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
586 log.Println("finished")