]> Sergey Matveev's repositories - mmc.git/blob - cmd/mmc/main.go
tar's mtime
[mmc.git] / cmd / mmc / main.go
1 // mmc -- Mattermost client
2 // Copyright (C) 2023 Sergey Matveev <stargrave@stargrave.org>
3 //
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
7 // License.
8 //
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.
13 //
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/>.
16
17 package main
18
19 import (
20         "archive/tar"
21         "bytes"
22         "encoding/json"
23         "errors"
24         "flag"
25         "fmt"
26         "io"
27         "io/fs"
28         "log"
29         "os"
30         "os/exec"
31         "os/signal"
32         "path"
33         "strings"
34         "syscall"
35         "time"
36
37         "github.com/davecgh/go-spew/spew"
38         "github.com/mattermost/mattermost-server/v6/model"
39         "go.stargrave.org/mmc"
40 )
41
42 const (
43         PerPage = 100
44         CmdFile = "/FILE "
45 )
46
47 var (
48         Newwin    = flag.String("newwin", "cmd/newwin", "Path to newwin command")
49         DebugFifo = flag.String("debug", "debug", "Path to debug FIFO to be created")
50         DebugFd   *os.File
51         UmaskCur  int
52 )
53
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 {
58                         log.Fatalln(err)
59                 }
60         }
61 }
62
63 func main() {
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")
67         flag.Parse()
68         log.SetFlags(log.Lshortfile)
69         log.SetOutput(os.Stdout)
70         UmaskCur = syscall.Umask(0)
71         syscall.Umask(UmaskCur)
72
73         var err error
74         if *DebugFifo != "" {
75                 DebugFd, err = os.OpenFile(
76                         *DebugFifo, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
77                 )
78                 if err != nil {
79                         log.Fatalln(err)
80                 }
81                 defer DebugFd.Close()
82         }
83
84         login, password := mmc.FindInNetrc(*entrypoint)
85         if login == "" || password == "" {
86                 log.Fatalln("no credentials found for:", *entrypoint)
87         }
88         c := model.NewAPIv4Client("https://" + *entrypoint)
89         c.Login(login, password)
90         me, resp, err := c.GetMe("")
91         if err != nil {
92                 if DebugFd != nil {
93                         spew.Fdump(DebugFd, resp)
94                 }
95                 log.Fatalln(err)
96         }
97         if DebugFd != nil {
98                 spew.Fdump(DebugFd, me)
99         }
100         log.Println("logged in")
101
102         time.Sleep(mmc.SleepTime)
103         teams, resp, err := c.GetTeamsForUser(me.Id, "")
104         if err != nil {
105                 if DebugFd != nil {
106                         spew.Fdump(DebugFd, resp)
107                 }
108                 log.Fatalln(err)
109         }
110         if DebugFd != nil {
111                 spew.Fdump(DebugFd, teams)
112         }
113         Team := teams[0]
114
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, "")
119                 if err != nil {
120                         if DebugFd != nil {
121                                 spew.Fdump(DebugFd, resp)
122                         }
123                         log.Fatalln(err)
124                 }
125                 if DebugFd != nil {
126                         spew.Fdump(DebugFd, page)
127                 }
128                 for _, u := range page {
129                         Users[u.Id] = u
130                 }
131                 if len(page) < PerPage {
132                         break
133                 }
134         }
135
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)
141                 rewriteIfChanged(
142                         path.Join(pth, "name"),
143                         fmt.Sprintf("%s %s\n", u.FirstName, u.LastName),
144                 )
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,
151                         ); err != nil {
152                                 log.Fatalln(err)
153                         }
154                 }
155                 updateQueue = append(updateQueue,
156                         pth, u.Id+"__"+me.Id,
157                         pth, me.Id+"__"+u.Id,
158                 )
159
160                 statusPth := path.Join(pth, "status")
161                 os.Remove(statusPth)
162                 if err := syscall.Mkfifo(statusPth, 0666); err != nil {
163                         log.Fatalln(err)
164                 }
165                 go func(u *model.User) {
166                         for {
167                                 time.Sleep(mmc.SleepTime)
168                                 fd, err := os.OpenFile(
169                                         statusPth, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
170                                 )
171                                 if err != nil {
172                                         log.Println("OpenFile:", statusPth, err)
173                                         continue
174                                 }
175                                 status, resp, err := c.GetUserStatus(u.Id, "")
176                                 if err != nil {
177                                         if DebugFd != nil {
178                                                 spew.Fdump(DebugFd, resp)
179                                         }
180                                         log.Println("GetUserStatus:", err)
181                                         fd.Close()
182                                         continue
183                                 }
184                                 if DebugFd != nil {
185                                         spew.Fdump(DebugFd, status)
186                                 }
187                                 fmt.Fprintf(fd, "%s\n", status.Status)
188                                 fd.Close()
189                         }
190                 }(u)
191
192                 pth = path.Join(pth, "in")
193                 os.Remove(pth)
194                 if err := syscall.Mkfifo(pth, 0666); err != nil {
195                         log.Fatalln(err)
196                 }
197                 go func(u *model.User) {
198                         var dc *model.Channel
199                         for {
200                                 fd, err := os.OpenFile(pth, os.O_RDONLY, os.FileMode(0666))
201                                 if err != nil {
202                                         continue
203                                 }
204                                 data, err := io.ReadAll(fd)
205                                 fd.Close()
206                                 if err != nil {
207                                         continue
208                                 }
209                                 if dc == nil {
210                                         dc, resp, err = c.CreateDirectChannel(me.Id, u.Id)
211                                         if err != nil {
212                                                 if DebugFd != nil {
213                                                         spew.Fdump(DebugFd, resp)
214                                                 }
215                                                 log.Println("CreateDirectChannel:", err)
216                                                 continue
217                                         }
218                                         if DebugFd != nil {
219                                                 spew.Fdump(DebugFd, dc)
220                                         }
221                                 }
222                                 if _, err = makePost(c, dc.Id, string(data)); err != nil {
223                                         log.Println("makePost:", err)
224                                 }
225                                 LastSent = time.Now()
226                         }
227                 }(u)
228         }
229
230         Chans := make(map[string]*model.Channel)
231         time.Sleep(mmc.SleepTime)
232         page, resp, err := c.GetChannelsForTeamForUser(Team.Id, me.Id, false, "")
233         if err != nil {
234                 if DebugFd != nil {
235                         spew.Fdump(DebugFd, resp)
236                 }
237                 log.Fatalln(err)
238         }
239         if DebugFd != nil {
240                 spew.Fdump(DebugFd, page)
241         }
242         for _, ch := range page {
243                 if ch.Type == "D" {
244                         continue
245                 }
246                 Chans[ch.Name] = ch
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(
252                         "%s\n%s\n%s\n",
253                         ch.DisplayName,
254                         ch.Header,
255                         ch.Purpose,
256                 ))
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,
261                         ); err != nil {
262                                 log.Fatalln(err)
263                         }
264                 }
265
266                 usersPth := path.Join(pth, "users")
267                 os.Remove(usersPth)
268                 if err := syscall.Mkfifo(usersPth, 0666); err != nil {
269                         log.Fatalln(err)
270                 }
271                 go func(ch *model.Channel) {
272                         for {
273                                 time.Sleep(mmc.SleepTime)
274                                 fd, err := os.OpenFile(
275                                         usersPth, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
276                                 )
277                                 if err != nil {
278                                         log.Println("OpenFile:", usersPth, err)
279                                         continue
280                                 }
281                                 for pageNum := 0; ; pageNum++ {
282                                         users, resp, err := c.GetUsersInChannel(ch.Id, pageNum, PerPage, "")
283                                         if err != nil {
284                                                 if DebugFd != nil {
285                                                         spew.Fdump(DebugFd, resp)
286                                                 }
287                                                 log.Println("GetUsersInChannel:", err)
288                                                 fd.Close()
289                                                 continue
290                                         }
291                                         if DebugFd != nil {
292                                                 spew.Fdump(DebugFd, users)
293                                         }
294                                         for _, u := range users {
295                                                 fmt.Fprintf(fd, "%s\n", u.Username)
296                                         }
297                                         if len(users) < PerPage {
298                                                 break
299                                         }
300                                 }
301                                 fd.Close()
302                         }
303                 }(ch)
304
305                 pth = path.Join(pth, "in")
306                 os.Remove(pth)
307                 if err := syscall.Mkfifo(pth, 0666); err != nil {
308                         log.Fatalln(err)
309                 }
310                 go func(ch *model.Channel) {
311                         for {
312                                 fd, err := os.OpenFile(pth, os.O_RDONLY, os.FileMode(0666))
313                                 if err != nil {
314                                         continue
315                                 }
316                                 data, err := io.ReadAll(fd)
317                                 fd.Close()
318                                 if err != nil {
319                                         continue
320                                 }
321                                 if _, err = makePost(c, ch.Id, string(data)); err != nil {
322                                         log.Println("makePost:", err)
323                                 }
324                                 LastSent = time.Now()
325                         }
326                 }(ch)
327         }
328
329         go func() {
330                 log.Println("syncing", len(Chans)+len(Users), "rooms")
331                 for len(updateQueue) > 0 {
332                         err := updatePosts(c, Users, updateQueue[0], updateQueue[1])
333                         if err != nil {
334                                 log.Println("updatePosts:", err)
335                         }
336                         updateQueue = updateQueue[2:]
337                 }
338                 log.Println("sync done")
339         }()
340
341         go func() {
342                 os.MkdirAll("file", 0777)
343                 pthGet := path.Join("file", "get")
344                 os.Remove(pthGet)
345                 if err := syscall.Mkfifo(pthGet, 0666); err != nil {
346                         log.Fatalln(err)
347                 }
348                 pthOut := path.Join("file", "out")
349                 os.Remove(pthOut)
350                 if err := syscall.Mkfifo(pthOut, 0666); err != nil {
351                         log.Fatalln(err)
352                 }
353                 for {
354                         time.Sleep(mmc.SleepTime)
355                         fd, err := os.OpenFile(pthGet, os.O_RDONLY, os.FileMode(0666))
356                         if err != nil {
357                                 continue
358                         }
359                         data, err := io.ReadAll(fd)
360                         fd.Close()
361                         if err != nil {
362                                 continue
363                         }
364                         fileId := strings.TrimRight(string(data), " \n")
365                         if len(fileId) == 0 {
366                                 continue
367                         }
368                         fi, resp, err := c.GetFileInfo(fileId)
369                         if DebugFd != nil {
370                                 spew.Fdump(DebugFd, fi, resp)
371                         }
372                         if err != nil {
373                                 log.Println(err)
374                                 continue
375                         }
376                         if fi == nil {
377                                 fmt.Println(resp)
378                                 continue
379                         }
380                         data, resp, err = c.GetFile(fileId)
381                         if err != nil {
382                                 if DebugFd != nil {
383                                         spew.Fdump(DebugFd, resp)
384                                 }
385                                 log.Println(err)
386                                 continue
387                         }
388                         fd, err = os.OpenFile(
389                                 pthOut, os.O_WRONLY|os.O_APPEND, os.FileMode(0666),
390                         )
391                         if err != nil {
392                                 log.Println(err)
393                                 continue
394                         }
395                         w := tar.NewWriter(fd)
396                         if err = w.WriteHeader(&tar.Header{
397                                 Format:   tar.FormatPAX,
398                                 Typeflag: tar.TypeReg,
399                                 Name:     fi.Name,
400                                 Size:     int64(len(data)),
401                                 Mode:     0o666,
402                                 ModTime:  time.Unix(fi.CreateAt/1000, 0),
403                                 PAXRecords: map[string]string{
404                                         "MM.FileId":   fi.Id,
405                                         "MM.MIMEType": fi.MimeType,
406                                 },
407                         }); err != nil {
408                                 log.Println(err)
409                                 fd.Close()
410                                 continue
411                         }
412                         if _, err = io.Copy(w, bytes.NewReader(data)); err != nil {
413                                 log.Println(err)
414                                 fd.Close()
415                                 continue
416                         }
417                         err = w.Close()
418                         fd.Close()
419                         if err != nil {
420                                 log.Println(err)
421                         }
422                 }
423         }()
424
425         needsShutdown := make(chan os.Signal)
426         wc, err := model.NewWebSocketClient4("wss://"+*entrypoint, c.AuthToken)
427         if err != nil {
428                 log.Fatalln(err)
429         }
430         go func() {
431                 wc.Listen()
432                 t := time.NewTicker(time.Minute)
433                 for {
434                         select {
435                         case <-t.C:
436                                 if time.Now().Before(LastSent.Add(time.Minute)) {
437                                         continue
438                                 }
439                                 wc.SendMessage("ping", nil)
440                                 if *heartbeatCh != "" {
441                                         if _, _, err = c.ViewChannel(
442                                                 me.Id,
443                                                 &model.ChannelView{ChannelId: Chans[*heartbeatCh].Id},
444                                         ); err != nil {
445                                                 log.Println("ChannelView:", err)
446                                         }
447                                 }
448                         case <-wc.PingTimeoutChannel:
449                                 log.Println("PING timeout")
450                                 needsShutdown <- syscall.SIGTERM
451                         case e := <-wc.EventChannel:
452                                 if e == nil || !e.IsValid() {
453                                         continue
454                                 }
455                                 data := e.GetData()
456                                 if DebugFd != nil {
457                                         spew.Fdump(DebugFd, e.EventType(), data)
458                                 }
459                                 var user *model.User
460                                 if userId, ok := data["user_id"]; ok && userId.(string) != "" {
461                                         user = Users[userId.(string)]
462                                         if user == nil {
463                                                 log.Println("unknown user for event:", e)
464                                                 continue
465                                         }
466                                 }
467                                 switch eventType := e.EventType(); eventType {
468                                 case model.WebsocketEventTyping:
469                                         if *notifyCmd != "" {
470                                                 exec.Command(*notifyCmd, "typing: "+user.Username).Run()
471                                         }
472                                 case model.WebsocketEventPostEdited,
473                                         model.WebsocketEventPostDeleted,
474                                         model.WebsocketEventPosted:
475                                         chName := data["channel_name"].(string)
476                                         var post model.Post
477                                         if err = json.NewDecoder(
478                                                 strings.NewReader(data["post"].(string)),
479                                         ).Decode(&post); err != nil {
480                                                 log.Fatalln(err)
481                                         }
482                                         var recipient string
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]
488                                                 if user == nil {
489                                                         log.Println("unknown user:", post)
490                                                         continue
491                                                 }
492                                                 recipient = path.Join("users", user.Username)
493                                         case model.ChannelTypeOpen:
494                                                 fallthrough
495                                         case model.ChannelTypePrivate:
496                                                 fallthrough
497                                         case model.ChannelTypeGroup:
498                                                 recipient = path.Join("chans", chName)
499                                         }
500                                         if err = writePosts(
501                                                 recipient, Users, []mmc.Post{{P: &post, E: eventType}},
502                                         ); err != nil {
503                                                 log.Fatalln(err)
504                                         }
505                                 case model.WebsocketEventStatusChange:
506                                         log.Println("status change:", user.Username, "->", data["status"].(string))
507                                         if *notifyCmd != "" {
508                                                 exec.Command(*notifyCmd, fmt.Sprintf(
509                                                         "status: %s -> %s",
510                                                         user.Username, data["status"].(string),
511                                                 )).Run()
512                                         }
513                                 case model.WebsocketEventHello:
514                                 case model.WebsocketEventChannelViewed:
515                                 default:
516                                         log.Println(e)
517                                 }
518                         case resp := <-wc.ResponseChannel:
519                                 if resp == nil || !resp.IsValid() {
520                                         continue
521                                 }
522                                 if DebugFd != nil {
523                                         spew.Fdump(DebugFd, resp)
524                                 }
525                                 if text, ok := resp.Data["text"].(string); ok && text == "pong" {
526                                         LastSent = time.Now()
527                                 }
528                         }
529                 }
530         }()
531
532         signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
533         <-needsShutdown
534         c.Logout()
535         log.Println("finished")
536 }