~samwhited/blogsync

ref: 79ae993fa7f0ead57d96927e000b80814a78a964 blogsync/preview.go -rw-r--r-- 7.3 KiB
79ae993fSam Whited blogsync: remove duplicate WF runner code 1 year, 10 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// Copyright 2019 The Blog Sync Contributors.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.

package main

import (
	"context"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"strconv"
	"text/template"
	"time"

	"github.com/writeas/go-writeas/v2"
	"mellium.im/blogsync/internal/browser"
	"mellium.im/cli"
)

const (
	dbFileName  = "data.db"
	cfgFileName = "config.ini"
	adminUser   = "root"
	/* #nosec */
	adminPass = "password"
	binName   = "writefreely"
)

type writeFreelyConfig struct {
	Bind            string
	Collection      string
	DBFile          string
	Port            int
	Prefix          string
	Resources       string
	SiteDescription string
	SiteName        string
}

const tmpFileTmpl = `
[server]
hidden_host          =
port                 = {{.Port}}
bind                 = {{.Bind}}
tls_cert_path        =
tls_key_path         =
autocert             = false
templates_parent_dir = {{.Resources}}
static_parent_dir    = {{.Resources}}
pages_parent_dir     = {{.Resources}}
keys_parent_dir      = {{.Prefix}}

[database]
type     = sqlite3
filename = {{.Prefix}}/{{.DBFile}}
username =
password =
database =
host     = localhost
port     = 3306

[app]
site_name          = {{.SiteName}}
site_description   = {{.SiteDescription}}
host               = http://{{.Bind}}:{{.Port}}
theme              = write
editor             =
disable_js         = false
webfonts           = true
landing            = /{{.Collection}}
simple_nav         = false
wf_modesty         = false
chorus             = false
disable_drafts     = false
single_user        = false
open_registration  = false
min_username_len   = 3
max_blogs          = 2
federation         = false
public_stats       = false
private            = false
local_timeline     = false
user_invites       =
default_visibility = public
`

func previewCmd(siteConfig Config, logger, debug *log.Logger) *cli.Command {
	var (
		port    = 8080
		bind    = "127.0.0.1"
		content = "content/"
		res     = "/usr/share/writefreely/"
	)
	flags := flag.NewFlagSet("preview", flag.ContinueOnError)
	flags.IntVar(&port, "port", port, "The port for writefreely to bind to")
	flags.StringVar(&bind, "addr", bind, "The address the server should bind to")
	flags.StringVar(&content, "content", content, "A directory containing pages and posts")
	flags.StringVar(&res, "resources", res, "A directory containing writefreelys templates and static assets")

	return &cli.Command{
		Usage:       "preview [options]",
		Flags:       flags,
		Description: `Launch writefreely and upload current pages.`,
		Run: func(cmd *cli.Command, args ...string) error {
			// Override the default SIGINT handler so that we can cleanup properly on
			// Ctrl+C instead of immediately exiting.
			sigs := make(chan os.Signal, 1)
			signal.Notify(sigs, os.Interrupt)

			_, err := exec.LookPath(binName)
			if err != nil {
				return fmt.Errorf(`
The 'writefreely' command could not be found.
To use the preview feature, please install writefreely:

https://writefreely.org/

(original error: %w)`, err)
			}

			tmpDir, err := mkTmp(writeFreelyConfig{
				Bind:            bind,
				Collection:      siteConfig.Collection,
				DBFile:          dbFileName,
				Port:            port,
				Resources:       res,
				SiteDescription: siteConfig.Description,
				SiteName:        siteConfig.Title,
			}, debug)
			if err != nil {
				return fmt.Errorf("can't create temporary directories: %v", err)
			}
			defer func() {
				err := os.RemoveAll(tmpDir)
				if err != nil {
					debug.Printf("error removing temporary dir %s: %v", tmpDir, err)
				}
			}()

			var cfgFilePath = filepath.Join(tmpDir, cfgFileName)

			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()

			err = tailWriteFreely(ctx, cfgFilePath, debug, "-gen-keys")
			if err != nil {
				return err
			}
			err = tailWriteFreely(ctx, cfgFilePath, debug, "-init-db")
			if err != nil {
				return err
			}
			err = tailWriteFreely(ctx, cfgFilePath, debug, "-create-admin", fmt.Sprintf("%s:%s", adminUser, adminPass))
			if err != nil {
				return err
			}

			go func() {
				err = tailWriteFreely(ctx, cfgFilePath, debug)
				if err != nil {
					debug.Printf("error while executing writefreely: %v", err)
				}
				cancel()
			}()

			addr := net.JoinHostPort(bind, strconv.Itoa(port))

			// Wait until writefreely becomes available.
			var connected bool
			for i := 0; i < 5; i++ {
				const timeout = 1 * time.Second
				logger.Printf("waiting %s for writefreely to accept connections…", timeout)
				conn, err := net.Dial("tcp", addr)
				if err == nil {
					err = conn.Close()
					if err != nil {
						debug.Printf("error closing temporary TCP connection: %v", err)
					}
					logger.Println("connected to writefreely!")
					connected = true
					break
				}
				time.Sleep(timeout)
			}
			if !connected {
				return fmt.Errorf("failed to connect to writefreely, did it start?")
			}

			baseAddr := "http://" + addr
			client := writeas.NewClientWith(writeas.Config{
				URL: baseAddr + "/api",
			})
			authUser, err := client.LogIn(adminUser, adminPass)
			if err != nil {
				return err
			}
			debug.Printf("logged in as: %+v", authUser)

			opts := newPublishOpts(siteConfig)
			opts.createCollections = true

			err = publish(opts, siteConfig, client, logger, debug)
			if err != nil {
				return err
			}

			browser.Open(baseAddr)

			select {
			case <-sigs:
			case <-ctx.Done():
			}
			return nil
		},
	}
}

func tailWriteFreely(ctx context.Context, cfgFile string, debug *log.Logger, args ...string) error {
	args = append([]string{"-c", cfgFile}, args...)
	cmd := exec.CommandContext(ctx, binName, args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Stdin = os.Stdin
	cmd.Dir = filepath.Dir(cfgFile)

	debug.Printf("running %s with %v…\n", cmd.Path, cmd.Args)

	return cmd.Run()
}

func writeConfig(cfgFileName string, cfg writeFreelyConfig, debug *log.Logger) (err error) {
	cfgFile, err := os.Create(cfgFileName)
	if err != nil {
		return err
	}
	defer func() {
		if err != nil {
			err := os.Remove(cfgFile.Name())
			if err != nil {
				debug.Printf("error during early removal of temporary config file %s: %v", cfgFile.Name(), err)
			}
		}
	}()

	t := template.Must(template.New("cfg").Parse(tmpFileTmpl))
	err = t.Execute(cfgFile, cfg)
	if err != nil {
		return fmt.Errorf("error executing template: %w", err)
	}
	err = cfgFile.Close()
	if err != nil {
		return fmt.Errorf("error closing temporary config file %s: %w", cfgFile.Name(), err)
	}

	return nil
}

func mkTmp(cfg writeFreelyConfig, debug *log.Logger) (tmpDir string, e error) {
	const (
		mode = os.ModeDir | 0755
	)

	tmpDir, err := ioutil.TempDir("", "blogsync")
	if err != nil {
		return tmpDir, err
	}
	defer func() {
		if e != nil {
			err := os.RemoveAll(tmpDir)
			if err != nil {
				debug.Printf("error during early removal of temporary dir %s: %v", tmpDir, err)
			}
		}
	}()
	cfg.Prefix = tmpDir

	for _, dir := range []string{"keys", "pages", "static", "templates"} {
		err := os.Mkdir(filepath.Join(tmpDir, dir), mode)
		if err != nil {
			return tmpDir, err
		}
	}

	dbFile, err := os.Create(filepath.Join(tmpDir, cfg.DBFile))
	if err != nil {
		return tmpDir, err
	}
	err = dbFile.Close()
	if err != nil {
		return tmpDir, err
	}

	err = writeConfig(filepath.Join(tmpDir, cfgFileName), cfg, debug)
	if err != nil {
		return tmpDir, err
	}

	return tmpDir, nil
}