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"
42 const CmdFile = "/FILE "
45 Newwin = flag.String("newwin", "cmd/newwin", "Path to newwin command")
46 DebugFifo = flag.String("debug", "debug", "Path to debug FIFO to be created")
51 func rewriteIfChanged(fn string, data string) {
52 if their, err := os.ReadFile(fn); err != nil ||
53 bytes.Compare([]byte(data), their) != 0 {
54 if err = os.WriteFile(fn, []byte(data), 0o666); err != nil {
61 entrypoint := flag.String("entrypoint", "mm.rnd.stcnet.ru", "Entrypoint")
62 notifyCmd := flag.String("notify", "cmd/notify", "Path to notification handler")
63 heartbeatCh := flag.String("heartbeat-ch", "town-square", "Channel for heartbeating")
65 log.SetFlags(log.Lshortfile)
66 log.SetOutput(os.Stdout)
67 UmaskCur = syscall.Umask(0)
68 syscall.Umask(UmaskCur)
72 DebugFd, err = os.OpenFile(
73 *DebugFifo, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
81 login, password := mmc.FindInNetrc(*entrypoint)
82 if login == "" || password == "" {
83 log.Fatalln("no credentials found for:", *entrypoint)
85 c := model.NewAPIv4Client("https://" + *entrypoint)
86 c.Login(login, password)
87 me, resp, err := c.GetMe("")
90 spew.Fdump(DebugFd, resp)
95 spew.Fdump(DebugFd, me)
97 log.Println("logged in")
99 time.Sleep(mmc.SleepTime)
100 teams, resp, err := c.GetTeamsForUser(me.Id, "")
103 spew.Fdump(DebugFd, resp)
108 spew.Fdump(DebugFd, teams)
112 var updateQueue []string
113 LastSent := time.Now()
115 Users, err := mmc.GetUsers(c, DebugFd)
119 for _, u := range Users {
120 pth := path.Join("users", strings.ReplaceAll(u.Username, ".", "_"))
121 os.MkdirAll(pth, 0777)
123 path.Join(pth, "name"),
124 fmt.Sprintf("%s %s\n", u.FirstName, u.LastName),
126 rewriteIfChanged(path.Join(pth, "email"), u.Email+"\n")
127 rewriteIfChanged(path.Join(pth, "id"), u.Id+"\n")
128 if _, err := os.Stat(path.Join(pth, mmc.OutRec)); err != nil &&
129 errors.Is(err, fs.ErrNotExist) {
130 if _, err = os.OpenFile(
131 path.Join(pth, mmc.OutRec), os.O_WRONLY|os.O_CREATE, 0o666,
136 updateQueue = append(updateQueue,
137 pth, u.Id+"__"+me.Id,
138 pth, me.Id+"__"+u.Id,
141 statusPth := path.Join(pth, "status")
143 if err := syscall.Mkfifo(statusPth, 0666); err != nil {
146 go func(u *model.User) {
148 time.Sleep(mmc.SleepTime)
149 fd, err := os.OpenFile(
150 statusPth, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
153 log.Println("OpenFile:", statusPth, err)
156 status, resp, err := c.GetUserStatus(u.Id, "")
159 spew.Fdump(DebugFd, resp)
161 log.Println("GetUserStatus:", err)
166 spew.Fdump(DebugFd, status)
168 fmt.Fprintf(fd, "%s\n", status.Status)
173 pth = path.Join(pth, "in")
175 if err := syscall.Mkfifo(pth, 0666); err != nil {
178 go func(u *model.User) {
179 var dc *model.Channel
181 fd, err := os.OpenFile(pth, os.O_RDONLY, os.FileMode(0666))
185 data, err := io.ReadAll(fd)
191 dc, resp, err = c.CreateDirectChannel(me.Id, u.Id)
194 spew.Fdump(DebugFd, resp)
196 log.Println("CreateDirectChannel:", err)
200 spew.Fdump(DebugFd, dc)
203 if _, err = makePost(c, dc.Id, string(data)); err != nil {
204 log.Println("makePost:", err)
206 LastSent = time.Now()
211 Chans := make(map[string]*model.Channel)
212 time.Sleep(mmc.SleepTime)
213 page, resp, err := c.GetChannelsForTeamForUser(Team.Id, me.Id, false, "")
216 spew.Fdump(DebugFd, resp)
221 spew.Fdump(DebugFd, page)
223 for _, ch := range page {
228 pth := path.Join("chans", strings.ReplaceAll(ch.Name, ".", "_"))
229 updateQueue = append(updateQueue, pth, ch.Id)
230 os.MkdirAll(pth, 0777)
231 rewriteIfChanged(path.Join(pth, "id"), ch.Id+"\n")
232 rewriteIfChanged(path.Join(pth, "info"), fmt.Sprintf(
238 if _, err := os.Stat(path.Join(pth, mmc.OutRec)); err != nil &&
239 errors.Is(err, fs.ErrNotExist) {
240 if _, err = os.OpenFile(
241 path.Join(pth, mmc.OutRec), os.O_WRONLY|os.O_CREATE, 0o666,
247 usersPth := path.Join(pth, "users")
249 if err := syscall.Mkfifo(usersPth, 0666); err != nil {
252 go func(ch *model.Channel) {
254 time.Sleep(mmc.SleepTime)
255 fd, err := os.OpenFile(
256 usersPth, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
259 log.Println("OpenFile:", usersPth, err)
263 users, resp, err := c.GetUsersInChannel(ch.Id, n, mmc.PerPage, "")
266 spew.Fdump(DebugFd, resp)
268 log.Println("GetUsersInChannel:", err)
273 spew.Fdump(DebugFd, users)
275 for _, u := range users {
276 fmt.Fprintf(fd, "%s\n", u.Username)
278 if len(users) < mmc.PerPage {
286 pth = path.Join(pth, "in")
288 if err := syscall.Mkfifo(pth, 0666); err != nil {
291 go func(ch *model.Channel) {
293 fd, err := os.OpenFile(pth, os.O_RDONLY, os.FileMode(0666))
297 data, err := io.ReadAll(fd)
302 if _, err = makePost(c, ch.Id, string(data)); err != nil {
303 log.Println("makePost:", err)
305 LastSent = time.Now()
311 log.Println("syncing", len(Chans)+len(Users), "rooms")
312 for len(updateQueue) > 0 {
313 err := updatePosts(c, Users, updateQueue[0], updateQueue[1])
315 log.Println("updatePosts:", err)
317 updateQueue = updateQueue[2:]
319 log.Println("sync done")
323 os.MkdirAll("file", 0777)
324 pthGet := path.Join("file", "get")
326 if err := syscall.Mkfifo(pthGet, 0666); err != nil {
329 pthOut := path.Join("file", "out")
331 if err := syscall.Mkfifo(pthOut, 0666); err != nil {
335 time.Sleep(mmc.SleepTime)
336 fd, err := os.OpenFile(pthGet, os.O_RDONLY, os.FileMode(0666))
340 data, err := io.ReadAll(fd)
345 fileId := strings.TrimRight(string(data), " \n")
346 if len(fileId) == 0 {
349 fi, resp, err := c.GetFileInfo(fileId)
351 spew.Fdump(DebugFd, fi, resp)
361 data, resp, err = c.GetFile(fileId)
364 spew.Fdump(DebugFd, resp)
369 fd, err = os.OpenFile(
370 pthOut, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
376 w := tar.NewWriter(fd)
377 if err = w.WriteHeader(&tar.Header{
378 Format: tar.FormatPAX,
379 Typeflag: tar.TypeReg,
381 Size: int64(len(data)),
383 ModTime: time.Unix(fi.CreateAt/1000, 0),
384 PAXRecords: map[string]string{
386 "MM.MIMEType": fi.MimeType,
393 if _, err = io.Copy(w, bytes.NewReader(data)); err != nil {
406 needsShutdown := make(chan os.Signal)
407 wc, err := model.NewWebSocketClient4("wss://"+*entrypoint, c.AuthToken)
413 t := time.NewTicker(time.Minute)
417 if time.Now().Before(LastSent.Add(time.Minute)) {
420 wc.SendMessage("ping", nil)
421 if *heartbeatCh != "" {
422 if _, _, err = c.ViewChannel(
424 &model.ChannelView{ChannelId: Chans[*heartbeatCh].Id},
426 log.Println("ChannelView:", err)
429 case <-wc.PingTimeoutChannel:
430 log.Println("PING timeout")
431 needsShutdown <- syscall.SIGTERM
432 case e := <-wc.EventChannel:
433 if e == nil || !e.IsValid() {
438 spew.Fdump(DebugFd, e.EventType(), data)
441 if userId, ok := data["user_id"]; ok && userId.(string) != "" {
442 user = Users[userId.(string)]
444 log.Println("unknown user for event:", e)
448 switch eventType := e.EventType(); eventType {
449 case model.WebsocketEventTyping:
450 if *notifyCmd != "" {
451 exec.Command(*notifyCmd, "typing: "+user.Username).Run()
453 case model.WebsocketEventPostEdited,
454 model.WebsocketEventPostDeleted,
455 model.WebsocketEventPosted:
456 chName := data["channel_name"].(string)
458 if err = json.NewDecoder(
459 strings.NewReader(data["post"].(string)),
460 ).Decode(&post); err != nil {
464 switch model.ChannelType(data["channel_type"].(string)) {
465 case model.ChannelTypeDirect:
466 userId := strings.TrimPrefix(chName, me.Id+"__")
467 userId = strings.TrimSuffix(userId, "__"+me.Id)
468 user := Users[userId]
470 log.Println("unknown user:", post)
473 recipient = path.Join("users", user.Username)
474 case model.ChannelTypeOpen:
476 case model.ChannelTypePrivate:
478 case model.ChannelTypeGroup:
479 recipient = path.Join("chans", chName)
482 recipient, Users, []mmc.Post{{P: &post, E: eventType}},
486 case model.WebsocketEventStatusChange:
487 log.Println("status change:", user.Username, "->", data["status"].(string))
488 if *notifyCmd != "" {
489 exec.Command(*notifyCmd, fmt.Sprintf(
491 user.Username, data["status"].(string),
494 case model.WebsocketEventHello:
495 case model.WebsocketEventChannelViewed:
499 case resp := <-wc.ResponseChannel:
500 if resp == nil || !resp.IsValid() {
504 spew.Fdump(DebugFd, resp)
506 if text, ok := resp.Data["text"].(string); ok && text == "pong" {
507 LastSent = time.Now()
513 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
516 log.Println("finished")