summaryrefslogtreecommitdiff
path: root/internal/web/profile.go
blob: e8483921d90d22a2c5f3a3c307adfc04147e9cdc (plain)
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package web

import (
	"context"
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
	apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util"
	"github.com/superseriousbusiness/gotosocial/internal/gtserror"
	"github.com/superseriousbusiness/gotosocial/internal/log"
)

type profile struct {
	instance       *apimodel.InstanceV1
	account        *apimodel.WebAccount
	rssFeed        string
	robotsMeta     string
	pinnedStatuses []*apimodel.WebStatus
	statusResp     *apimodel.PageableResponse
	paging         bool
}

// prepareProfile does content type checks, fetches the
// targeted account from the db, and converts it to its
// web representation, along with other data needed to
// render the web view of the account.
func (m *Module) prepareProfile(c *gin.Context) *profile {
	ctx := c.Request.Context()

	// We'll need the instance later, and we can also use it
	// before then to make it easier to return a web error.
	instance, errWithCode := m.processor.InstanceGetV1(ctx)
	if errWithCode != nil {
		apiutil.WebErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
		return nil
	}

	// Return instance we already got from the db,
	// don't try to fetch it again when erroring.
	instanceGet := func(ctx context.Context) (*apimodel.InstanceV1, gtserror.WithCode) {
		return instance, nil
	}

	// Parse + normalize account username from the URL.
	requestedUsername, errWithCode := apiutil.ParseUsername(c.Param(apiutil.UsernameKey))
	if errWithCode != nil {
		apiutil.WebErrorHandler(c, errWithCode, instanceGet)
		return nil
	}
	requestedUsername = strings.ToLower(requestedUsername)

	// Check what type of content is being requested.
	// If we're getting an AP request on this endpoint
	// we should render the AP representation instead.
	contentType, err := apiutil.NegotiateAccept(c, apiutil.HTMLOrActivityPubHeaders...)
	if err != nil {
		apiutil.WebErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), instanceGet)
		return nil
	}

	if contentType == string(apiutil.AppActivityJSON) ||
		contentType == string(apiutil.AppActivityLDJSON) {
		// AP account representation has
		// been requested, return that.
		m.returnAPAccount(c, requestedUsername, contentType)
		return nil
	}

	// text/html has been requested.
	//
	// Proceed with getting the web
	// representation of the account.
	account, errWithCode := m.processor.Account().GetWeb(ctx, requestedUsername)
	if errWithCode != nil {
		apiutil.WebErrorHandler(c, errWithCode, instanceGet)
		return nil
	}

	// If target account is suspended,
	// this page should not be visible.
	//
	// TODO: change this to 410?
	if account.Suspended {
		err := fmt.Errorf("target account %s is suspended", requestedUsername)
		apiutil.WebErrorHandler(c, gtserror.NewErrorNotFound(err), instanceGet)
		return nil
	}

	// Only generate RSS link if
	// account has RSS enabled.
	var rssFeed string
	if account.EnableRSS {
		rssFeed = "/@" + account.Username + "/feed.rss"
	}

	// Only allow search robots
	// if account is discoverable.
	var robotsMeta string
	if account.Discoverable {
		robotsMeta = apiutil.RobotsDirectivesAllowSome
	}

	// Check if paging.
	maxStatusID := apiutil.ParseMaxID(c.Query(apiutil.MaxIDKey), "")
	paging := maxStatusID != ""

	// If not paging, load pinned statuses.
	var (
		mediaOnly      = account.WebLayout == "gallery"
		pinnedStatuses []*apimodel.WebStatus
	)
	if !paging {
		var errWithCode gtserror.WithCode
		pinnedStatuses, errWithCode = m.processor.Account().WebStatusesGetPinned(
			ctx,
			account.ID,
			mediaOnly,
		)
		if errWithCode != nil {
			apiutil.WebErrorHandler(c, errWithCode, instanceGet)
			return nil
		}
	}

	// Limit varies depending on whether this is a gallery view or not.
	// If gallery view, we want a nice full screen of media, else we
	// don't want to overwhelm the viewer with a shitload of posts.
	var limit int
	if account.WebLayout == "gallery" {
		limit = 40
	} else {
		limit = 20
	}

	// Get statuses from maxStatusID onwards (or from top if empty string).
	statusResp, errWithCode := m.processor.Account().WebStatusesGet(
		ctx,
		account.ID,
		mediaOnly,
		limit,
		maxStatusID,
	)
	if errWithCode != nil {
		apiutil.WebErrorHandler(c, errWithCode, instanceGet)
		return nil
	}

	return &profile{
		instance:       instance,
		account:        account,
		rssFeed:        rssFeed,
		robotsMeta:     robotsMeta,
		pinnedStatuses: pinnedStatuses,
		statusResp:     statusResp,
		paging:         paging,
	}
}

// profileGETHandler selects the appropriate rendering
// mode for the target account profile, and serves that.
func (m *Module) profileGETHandler(c *gin.Context) {
	p := m.prepareProfile(c)
	if p == nil {
		// Something went wrong,
		// error already written.
		return
	}

	// Choose desired web renderer for this acct.
	switch wrm := p.account.WebLayout; wrm {

	// El classico.
	case "", "microblog":
		m.profileMicroblog(c, p)

	// 'gram style media gallery.
	case "gallery":
		m.profileGallery(c, p)

	default:
		log.Panicf(
			c.Request.Context(),
			"unknown webrenderingmode %s", wrm,
		)
	}
}

// profileMicroblog serves the profile
// in classic GtS "microblog" view.
func (m *Module) profileMicroblog(c *gin.Context, p *profile) {
	// Prepare stylesheets for profile.
	stylesheets := make([]string, 0, 7)

	// Basic profile stylesheets.
	stylesheets = append(
		stylesheets,
		[]string{
			cssFA,
			cssStatus,
			cssThread,
			cssProfile,
		}...,
	)

	// User-selected theme if set.
	if theme := p.account.Theme; theme != "" {
		stylesheets = append(
			stylesheets,
			themesPathPrefix+"/"+theme,
		)
	}

	// Custom CSS for this user last in cascade.
	stylesheets = append(
		stylesheets,
		"/@"+p.account.Username+"/custom.css",
	)

	page := apiutil.WebPage{
		Template:    "profile.tmpl",
		Instance:    p.instance,
		OGMeta:      apiutil.OGBase(p.instance).WithAccount(p.account),
		Stylesheets: stylesheets,
		Javascript: []apiutil.JavascriptEntry{
			{
				Src:   jsFrontend,
				Async: true,
				Defer: true,
			},
			{
				Bottom: true,
				Src:    jsBlurhash,
			},
		},
		Extra: map[string]any{
			"account":          p.account,
			"rssFeed":          p.rssFeed,
			"robotsMeta":       p.robotsMeta,
			"statuses":         p.statusResp.Items,
			"statuses_next":    p.statusResp.NextLink,
			"pinned_statuses":  p.pinnedStatuses,
			"show_back_to_top": p.paging,
		},
	}

	apiutil.TemplateWebPage(c, page)
}

// profileMicroblog serves the profile
// in media-only 'gram-style gallery view.
func (m *Module) profileGallery(c *gin.Context, p *profile) {
	// Get just attachments from pinned,
	// making a rough guess for slice size.
	pinnedGalleryItems := make([]*apimodel.WebAttachment, 0, len(p.pinnedStatuses)*4)
	for _, status := range p.pinnedStatuses {
		pinnedGalleryItems = append(pinnedGalleryItems, status.MediaAttachments...)
	}

	// Get just attachments from statuses,
	// making a rough guess for slice size.
	galleryItems := make([]*apimodel.WebAttachment, 0, len(p.statusResp.Items)*4)
	for _, statusI := range p.statusResp.Items {
		status := statusI.(*apimodel.WebStatus)
		galleryItems = append(galleryItems, status.MediaAttachments...)
	}

	// Prepare stylesheets for profile.
	stylesheets := make([]string, 0, 4)

	// Profile gallery stylesheets.
	stylesheets = append(
		stylesheets,
		[]string{
			cssFA,
			cssProfileGallery,
		}...)

	// User-selected theme if set.
	if theme := p.account.Theme; theme != "" {
		stylesheets = append(
			stylesheets,
			themesPathPrefix+"/"+theme,
		)
	}

	// Custom CSS for this
	// user last in cascade.
	stylesheets = append(
		stylesheets,
		"/@"+p.account.Username+"/custom.css",
	)

	page := apiutil.WebPage{
		Template:    "profile-gallery.tmpl",
		Instance:    p.instance,
		OGMeta:      apiutil.OGBase(p.instance).WithAccount(p.account),
		Stylesheets: stylesheets,
		Javascript: []apiutil.JavascriptEntry{
			{
				Src:   jsFrontend,
				Async: true,
				Defer: true,
			},
			{
				Bottom: true,
				Src:    jsBlurhash,
			},
		},
		Extra: map[string]any{
			"account":            p.account,
			"rssFeed":            p.rssFeed,
			"robotsMeta":         p.robotsMeta,
			"pinnedGalleryItems": pinnedGalleryItems,
			"galleryItems":       galleryItems,
			"statuses":           p.statusResp.Items,
			"statuses_next":      p.statusResp.NextLink,
			"pinned_statuses":    p.pinnedStatuses,
			"show_back_to_top":   p.paging,
		},
	}

	apiutil.TemplateWebPage(c, page)
}

// returnAPAccount returns an ActivityPub representation of
// target account. It will do http signature authentication.
func (m *Module) returnAPAccount(
	c *gin.Context,
	targetUsername string,
	contentType string,
) {
	user, errWithCode := m.processor.Fedi().UserGet(c.Request.Context(), targetUsername, c.Request.URL)
	if errWithCode != nil {
		apiutil.WebErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
		return
	}

	apiutil.JSONType(c, http.StatusOK, contentType, user)
}