A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 

2862 linhas
88 KiB

  1. /*
  2. * Copyright © 2018-2021 Musing Studio LLC.
  3. *
  4. * This file is part of WriteFreely.
  5. *
  6. * WriteFreely is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License, included
  8. * in the LICENSE file in this source code package.
  9. */
  10. package writefreely
  11. import (
  12. "context"
  13. "database/sql"
  14. "fmt"
  15. "github.com/writeas/web-core/silobridge"
  16. wf_db "github.com/writefreely/writefreely/db"
  17. "net/http"
  18. "strings"
  19. "time"
  20. "github.com/guregu/null"
  21. "github.com/guregu/null/zero"
  22. uuid "github.com/nu7hatch/gouuid"
  23. "github.com/writeas/activityserve"
  24. "github.com/writeas/impart"
  25. "github.com/writeas/web-core/activitypub"
  26. "github.com/writeas/web-core/auth"
  27. "github.com/writeas/web-core/data"
  28. "github.com/writeas/web-core/id"
  29. "github.com/writeas/web-core/log"
  30. "github.com/writeas/web-core/query"
  31. "github.com/writefreely/writefreely/author"
  32. "github.com/writefreely/writefreely/config"
  33. "github.com/writefreely/writefreely/key"
  34. )
  35. const (
  36. mySQLErrDuplicateKey = 1062
  37. mySQLErrCollationMix = 1267
  38. mySQLErrTooManyConns = 1040
  39. mySQLErrMaxUserConns = 1203
  40. driverMySQL = "mysql"
  41. driverSQLite = "sqlite3"
  42. )
  43. var (
  44. SQLiteEnabled bool
  45. )
  46. type writestore interface {
  47. CreateUser(*config.Config, *User, string, string) error
  48. UpdateUserEmail(keys *key.Keychain, userID int64, email string) error
  49. UpdateEncryptedUserEmail(int64, []byte) error
  50. GetUserByID(int64) (*User, error)
  51. GetUserForAuth(string) (*User, error)
  52. GetUserForAuthByID(int64) (*User, error)
  53. GetUserNameFromToken(string) (string, error)
  54. GetUserDataFromToken(string) (int64, string, error)
  55. GetAPIUser(header string) (*User, error)
  56. GetUserID(accessToken string) int64
  57. GetUserIDPrivilege(accessToken string) (userID int64, sudo bool)
  58. DeleteToken(accessToken []byte) error
  59. FetchLastAccessToken(userID int64) string
  60. GetAccessToken(userID int64) (string, error)
  61. GetTemporaryAccessToken(userID int64, validSecs int) (string, error)
  62. GetTemporaryOneTimeAccessToken(userID int64, validSecs int, oneTime bool) (string, error)
  63. DeleteAccount(userID int64) error
  64. ChangeSettings(app *App, u *User, s *userSettings) error
  65. ChangePassphrase(userID int64, sudo bool, curPass string, hashedPass []byte) error
  66. GetCollections(u *User, hostName string) (*[]Collection, error)
  67. GetPublishableCollections(u *User, hostName string) (*[]Collection, error)
  68. GetMeStats(u *User) userMeStats
  69. GetTotalCollections() (int64, error)
  70. GetTotalPosts() (int64, error)
  71. GetTopPosts(u *User, alias string, hostName string) (*[]PublicPost, error)
  72. GetAnonymousPosts(u *User, page int) (*[]PublicPost, error)
  73. GetUserPosts(u *User) (*[]PublicPost, error)
  74. CreateOwnedPost(post *SubmittedPost, accessToken, collAlias, hostName string) (*PublicPost, error)
  75. CreatePost(userID, collID int64, post *SubmittedPost) (*Post, error)
  76. UpdateOwnedPost(post *AuthenticatedPost, userID int64) error
  77. GetEditablePost(id, editToken string) (*PublicPost, error)
  78. PostIDExists(id string) bool
  79. GetPost(id string, collectionID int64) (*PublicPost, error)
  80. GetOwnedPost(id string, ownerID int64) (*PublicPost, error)
  81. GetPostProperty(id string, collectionID int64, property string) (interface{}, error)
  82. CreateCollectionFromToken(*config.Config, string, string, string) (*Collection, error)
  83. CreateCollection(*config.Config, string, string, int64) (*Collection, error)
  84. GetCollectionBy(condition string, value interface{}) (*Collection, error)
  85. GetCollection(alias string) (*Collection, error)
  86. GetCollectionForPad(alias string) (*Collection, error)
  87. GetCollectionByID(id int64) (*Collection, error)
  88. UpdateCollection(c *SubmittedCollection, alias string) error
  89. DeleteCollection(alias string, userID int64) error
  90. UpdatePostPinState(pinned bool, postID string, collID, ownerID, pos int64) error
  91. GetLastPinnedPostPos(collID int64) int64
  92. GetPinnedPosts(coll *CollectionObj, includeFuture bool) (*[]PublicPost, error)
  93. RemoveCollectionRedirect(t *sql.Tx, alias string) error
  94. GetCollectionRedirect(alias string) (new string)
  95. IsCollectionAttributeOn(id int64, attr string) bool
  96. CollectionHasAttribute(id int64, attr string) bool
  97. CanCollect(cpr *ClaimPostRequest, userID int64) bool
  98. AttemptClaim(p *ClaimPostRequest, query string, params []interface{}, slugIdx int) (sql.Result, error)
  99. DispersePosts(userID int64, postIDs []string) (*[]ClaimPostResult, error)
  100. ClaimPosts(cfg *config.Config, userID int64, collAlias string, posts *[]ClaimPostRequest) (*[]ClaimPostResult, error)
  101. GetPostsCount(c *CollectionObj, includeFuture bool)
  102. GetPosts(cfg *config.Config, c *Collection, page int, includeFuture, forceRecentFirst, includePinned bool) (*[]PublicPost, error)
  103. GetAllPostsTaggedIDs(c *Collection, tag string, includeFuture bool) ([]string, error)
  104. GetPostsTagged(cfg *config.Config, c *Collection, tag string, page int, includeFuture bool) (*[]PublicPost, error)
  105. GetAPFollowers(c *Collection) (*[]RemoteUser, error)
  106. GetAPActorKeys(collectionID int64) ([]byte, []byte)
  107. CreateUserInvite(id string, userID int64, maxUses int, expires *time.Time) error
  108. GetUserInvites(userID int64) (*[]Invite, error)
  109. GetUserInvite(id string) (*Invite, error)
  110. GetUsersInvitedCount(id string) int64
  111. CreateInvitedUser(inviteID string, userID int64) error
  112. GetDynamicContent(id string) (*instanceContent, error)
  113. UpdateDynamicContent(id, title, content, contentType string) error
  114. GetAllUsers(page uint) (*[]User, error)
  115. GetAllUsersCount() int64
  116. GetUserLastPostTime(id int64) (*time.Time, error)
  117. GetCollectionLastPostTime(id int64) (*time.Time, error)
  118. GetIDForRemoteUser(context.Context, string, string, string) (int64, error)
  119. RecordRemoteUserID(context.Context, int64, string, string, string, string) error
  120. ValidateOAuthState(context.Context, string) (string, string, int64, string, error)
  121. GenerateOAuthState(context.Context, string, string, int64, string) (string, error)
  122. GetOauthAccounts(ctx context.Context, userID int64) ([]oauthAccountInfo, error)
  123. RemoveOauth(ctx context.Context, userID int64, provider string, clientID string, remoteUserID string) error
  124. DatabaseInitialized() bool
  125. }
  126. type datastore struct {
  127. *sql.DB
  128. driverName string
  129. }
  130. var _ writestore = &datastore{}
  131. func (db *datastore) now() string {
  132. if db.driverName == driverSQLite {
  133. return "strftime('%Y-%m-%d %H:%M:%S','now')"
  134. }
  135. return "NOW()"
  136. }
  137. func (db *datastore) clip(field string, l int) string {
  138. if db.driverName == driverSQLite {
  139. return fmt.Sprintf("SUBSTR(%s, 0, %d)", field, l)
  140. }
  141. return fmt.Sprintf("LEFT(%s, %d)", field, l)
  142. }
  143. func (db *datastore) upsert(indexedCols ...string) string {
  144. if db.driverName == driverSQLite {
  145. // NOTE: SQLite UPSERT syntax only works in v3.24.0 (2018-06-04) or later
  146. // Leaving this for whenever we can upgrade and include it in our binary
  147. cc := strings.Join(indexedCols, ", ")
  148. return "ON CONFLICT(" + cc + ") DO UPDATE SET"
  149. }
  150. return "ON DUPLICATE KEY UPDATE"
  151. }
  152. func (db *datastore) dateSub(l int, unit string) string {
  153. if db.driverName == driverSQLite {
  154. return fmt.Sprintf("DATETIME('now', '-%d %s')", l, unit)
  155. }
  156. return fmt.Sprintf("DATE_SUB(NOW(), INTERVAL %d %s)", l, unit)
  157. }
  158. // CreateUser creates a new user in the database from the given User, UPDATING it in the process with the user's ID.
  159. func (db *datastore) CreateUser(cfg *config.Config, u *User, collectionTitle string, collectionDesc string) error {
  160. if db.PostIDExists(u.Username) {
  161. return impart.HTTPError{http.StatusConflict, "Invalid collection name."}
  162. }
  163. // New users get a `users` and `collections` row.
  164. t, err := db.Begin()
  165. if err != nil {
  166. return err
  167. }
  168. // 1. Add to `users` table
  169. // NOTE: Assumes User's Password is already hashed!
  170. res, err := t.Exec("INSERT INTO users (username, password, email) VALUES (?, ?, ?)", u.Username, u.HashedPass, u.Email)
  171. if err != nil {
  172. t.Rollback()
  173. if db.isDuplicateKeyErr(err) {
  174. return impart.HTTPError{http.StatusConflict, "Username is already taken."}
  175. }
  176. log.Error("Rolling back users INSERT: %v\n", err)
  177. return err
  178. }
  179. u.ID, err = res.LastInsertId()
  180. if err != nil {
  181. t.Rollback()
  182. log.Error("Rolling back after LastInsertId: %v\n", err)
  183. return err
  184. }
  185. // 2. Create user's Collection
  186. if collectionTitle == "" {
  187. collectionTitle = u.Username
  188. }
  189. res, err = t.Exec("INSERT INTO collections (alias, title, description, privacy, owner_id, view_count) VALUES (?, ?, ?, ?, ?, ?)", u.Username, collectionTitle, collectionDesc, defaultVisibility(cfg), u.ID, 0)
  190. if err != nil {
  191. t.Rollback()
  192. if db.isDuplicateKeyErr(err) {
  193. return impart.HTTPError{http.StatusConflict, "Username is already taken."}
  194. }
  195. log.Error("Rolling back collections INSERT: %v\n", err)
  196. return err
  197. }
  198. db.RemoveCollectionRedirect(t, u.Username)
  199. err = t.Commit()
  200. if err != nil {
  201. t.Rollback()
  202. log.Error("Rolling back after Commit(): %v\n", err)
  203. return err
  204. }
  205. return nil
  206. }
  207. // FIXME: We're returning errors inconsistently in this file. Do we use Errorf
  208. // for returned value, or impart?
  209. func (db *datastore) UpdateUserEmail(keys *key.Keychain, userID int64, email string) error {
  210. encEmail, err := data.Encrypt(keys.EmailKey, email)
  211. if err != nil {
  212. return fmt.Errorf("Couldn't encrypt email %s: %s\n", email, err)
  213. }
  214. return db.UpdateEncryptedUserEmail(userID, encEmail)
  215. }
  216. func (db *datastore) UpdateEncryptedUserEmail(userID int64, encEmail []byte) error {
  217. _, err := db.Exec("UPDATE users SET email = ? WHERE id = ?", encEmail, userID)
  218. if err != nil {
  219. return fmt.Errorf("Unable to update user email: %s", err)
  220. }
  221. return nil
  222. }
  223. func (db *datastore) CreateCollectionFromToken(cfg *config.Config, alias, title, accessToken string) (*Collection, error) {
  224. userID := db.GetUserID(accessToken)
  225. if userID == -1 {
  226. return nil, ErrBadAccessToken
  227. }
  228. return db.CreateCollection(cfg, alias, title, userID)
  229. }
  230. func (db *datastore) GetUserCollectionCount(userID int64) (uint64, error) {
  231. var collCount uint64
  232. err := db.QueryRow("SELECT COUNT(*) FROM collections WHERE owner_id = ?", userID).Scan(&collCount)
  233. switch {
  234. case err == sql.ErrNoRows:
  235. return 0, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user from database."}
  236. case err != nil:
  237. log.Error("Couldn't get collections count for user %d: %v", userID, err)
  238. return 0, err
  239. }
  240. return collCount, nil
  241. }
  242. func (db *datastore) CreateCollection(cfg *config.Config, alias, title string, userID int64) (*Collection, error) {
  243. if db.PostIDExists(alias) {
  244. return nil, impart.HTTPError{http.StatusConflict, "Invalid collection name."}
  245. }
  246. // All good, so create new collection
  247. res, err := db.Exec("INSERT INTO collections (alias, title, description, privacy, owner_id, view_count) VALUES (?, ?, ?, ?, ?, ?)", alias, title, "", defaultVisibility(cfg), userID, 0)
  248. if err != nil {
  249. if db.isDuplicateKeyErr(err) {
  250. return nil, impart.HTTPError{http.StatusConflict, "Collection already exists."}
  251. }
  252. log.Error("Couldn't add to collections: %v\n", err)
  253. return nil, err
  254. }
  255. c := &Collection{
  256. Alias: alias,
  257. Title: title,
  258. OwnerID: userID,
  259. PublicOwner: false,
  260. Public: defaultVisibility(cfg) == CollPublic,
  261. }
  262. c.ID, err = res.LastInsertId()
  263. if err != nil {
  264. log.Error("Couldn't get collection LastInsertId: %v\n", err)
  265. }
  266. return c, nil
  267. }
  268. func (db *datastore) GetUserByID(id int64) (*User, error) {
  269. u := &User{ID: id}
  270. err := db.QueryRow("SELECT username, password, email, created, status FROM users WHERE id = ?", id).Scan(&u.Username, &u.HashedPass, &u.Email, &u.Created, &u.Status)
  271. switch {
  272. case err == sql.ErrNoRows:
  273. return nil, ErrUserNotFound
  274. case err != nil:
  275. log.Error("Couldn't SELECT user password: %v", err)
  276. return nil, err
  277. }
  278. return u, nil
  279. }
  280. // IsUserSilenced returns true if the user account associated with id is
  281. // currently silenced.
  282. func (db *datastore) IsUserSilenced(id int64) (bool, error) {
  283. u := &User{ID: id}
  284. err := db.QueryRow("SELECT status FROM users WHERE id = ?", id).Scan(&u.Status)
  285. switch {
  286. case err == sql.ErrNoRows:
  287. return false, ErrUserNotFound
  288. case err != nil:
  289. log.Error("Couldn't SELECT user status: %v", err)
  290. return false, fmt.Errorf("is user silenced: %v", err)
  291. }
  292. return u.IsSilenced(), nil
  293. }
  294. // DoesUserNeedAuth returns true if the user hasn't provided any methods for
  295. // authenticating with the account, such a passphrase or email address.
  296. // Any errors are reported to admin and silently quashed, returning false as the
  297. // result.
  298. func (db *datastore) DoesUserNeedAuth(id int64) bool {
  299. var pass, email []byte
  300. // Find out if user has an email set first
  301. err := db.QueryRow("SELECT password, email FROM users WHERE id = ?", id).Scan(&pass, &email)
  302. switch {
  303. case err == sql.ErrNoRows:
  304. // ERROR. Don't give false positives on needing auth methods
  305. return false
  306. case err != nil:
  307. // ERROR. Don't give false positives on needing auth methods
  308. log.Error("Couldn't SELECT user %d from users: %v", id, err)
  309. return false
  310. }
  311. // User doesn't need auth if there's an email
  312. return len(email) == 0 && len(pass) == 0
  313. }
  314. func (db *datastore) IsUserPassSet(id int64) (bool, error) {
  315. var pass []byte
  316. err := db.QueryRow("SELECT password FROM users WHERE id = ?", id).Scan(&pass)
  317. switch {
  318. case err == sql.ErrNoRows:
  319. return false, nil
  320. case err != nil:
  321. log.Error("Couldn't SELECT user %d from users: %v", id, err)
  322. return false, err
  323. }
  324. return len(pass) > 0, nil
  325. }
  326. func (db *datastore) GetUserForAuth(username string) (*User, error) {
  327. u := &User{Username: username}
  328. err := db.QueryRow("SELECT id, password, email, created, status FROM users WHERE username = ?", username).Scan(&u.ID, &u.HashedPass, &u.Email, &u.Created, &u.Status)
  329. switch {
  330. case err == sql.ErrNoRows:
  331. // Check if they've entered the wrong, unnormalized username
  332. username = getSlug(username, "")
  333. if username != u.Username {
  334. err = db.QueryRow("SELECT id FROM users WHERE username = ? LIMIT 1", username).Scan(&u.ID)
  335. if err == nil {
  336. return db.GetUserForAuth(username)
  337. }
  338. }
  339. return nil, ErrUserNotFound
  340. case err != nil:
  341. log.Error("Couldn't SELECT user password: %v", err)
  342. return nil, err
  343. }
  344. return u, nil
  345. }
  346. func (db *datastore) GetUserForAuthByID(userID int64) (*User, error) {
  347. u := &User{ID: userID}
  348. err := db.QueryRow("SELECT id, password, email, created, status FROM users WHERE id = ?", u.ID).Scan(&u.ID, &u.HashedPass, &u.Email, &u.Created, &u.Status)
  349. switch {
  350. case err == sql.ErrNoRows:
  351. return nil, ErrUserNotFound
  352. case err != nil:
  353. log.Error("Couldn't SELECT userForAuthByID: %v", err)
  354. return nil, err
  355. }
  356. return u, nil
  357. }
  358. func (db *datastore) GetUserNameFromToken(accessToken string) (string, error) {
  359. t := auth.GetToken(accessToken)
  360. if len(t) == 0 {
  361. return "", ErrNoAccessToken
  362. }
  363. var oneTime bool
  364. var username string
  365. err := db.QueryRow("SELECT username, one_time FROM accesstokens LEFT JOIN users ON user_id = id WHERE token LIKE ? AND (expires IS NULL OR expires > "+db.now()+")", t).Scan(&username, &oneTime)
  366. switch {
  367. case err == sql.ErrNoRows:
  368. return "", ErrBadAccessToken
  369. case err != nil:
  370. return "", ErrInternalGeneral
  371. }
  372. // Delete token if it was one-time
  373. if oneTime {
  374. db.DeleteToken(t[:])
  375. }
  376. return username, nil
  377. }
  378. func (db *datastore) GetUserDataFromToken(accessToken string) (int64, string, error) {
  379. t := auth.GetToken(accessToken)
  380. if len(t) == 0 {
  381. return 0, "", ErrNoAccessToken
  382. }
  383. var userID int64
  384. var oneTime bool
  385. var username string
  386. err := db.QueryRow("SELECT user_id, username, one_time FROM accesstokens LEFT JOIN users ON user_id = id WHERE token LIKE ? AND (expires IS NULL OR expires > "+db.now()+")", t).Scan(&userID, &username, &oneTime)
  387. switch {
  388. case err == sql.ErrNoRows:
  389. return 0, "", ErrBadAccessToken
  390. case err != nil:
  391. return 0, "", ErrInternalGeneral
  392. }
  393. // Delete token if it was one-time
  394. if oneTime {
  395. db.DeleteToken(t[:])
  396. }
  397. return userID, username, nil
  398. }
  399. func (db *datastore) GetAPIUser(header string) (*User, error) {
  400. uID := db.GetUserID(header)
  401. if uID == -1 {
  402. return nil, fmt.Errorf(ErrUserNotFound.Error())
  403. }
  404. return db.GetUserByID(uID)
  405. }
  406. // GetUserID takes a hexadecimal accessToken, parses it into its binary
  407. // representation, and gets any user ID associated with the token. If no user
  408. // is associated, -1 is returned.
  409. func (db *datastore) GetUserID(accessToken string) int64 {
  410. i, _ := db.GetUserIDPrivilege(accessToken)
  411. return i
  412. }
  413. func (db *datastore) GetUserIDPrivilege(accessToken string) (userID int64, sudo bool) {
  414. t := auth.GetToken(accessToken)
  415. if len(t) == 0 {
  416. return -1, false
  417. }
  418. var oneTime bool
  419. err := db.QueryRow("SELECT user_id, sudo, one_time FROM accesstokens WHERE token LIKE ? AND (expires IS NULL OR expires > "+db.now()+")", t).Scan(&userID, &sudo, &oneTime)
  420. switch {
  421. case err == sql.ErrNoRows:
  422. return -1, false
  423. case err != nil:
  424. return -1, false
  425. }
  426. // Delete token if it was one-time
  427. if oneTime {
  428. db.DeleteToken(t[:])
  429. }
  430. return
  431. }
  432. func (db *datastore) DeleteToken(accessToken []byte) error {
  433. res, err := db.Exec("DELETE FROM accesstokens WHERE token LIKE ?", accessToken)
  434. if err != nil {
  435. return err
  436. }
  437. rowsAffected, _ := res.RowsAffected()
  438. if rowsAffected == 0 {
  439. return impart.HTTPError{http.StatusNotFound, "Token is invalid or doesn't exist"}
  440. }
  441. return nil
  442. }
  443. // FetchLastAccessToken creates a new non-expiring, valid access token for the given
  444. // userID.
  445. func (db *datastore) FetchLastAccessToken(userID int64) string {
  446. var t []byte
  447. err := db.QueryRow("SELECT token FROM accesstokens WHERE user_id = ? AND (expires IS NULL OR expires > "+db.now()+") ORDER BY created DESC LIMIT 1", userID).Scan(&t)
  448. switch {
  449. case err == sql.ErrNoRows:
  450. return ""
  451. case err != nil:
  452. log.Error("Failed selecting from accesstoken: %v", err)
  453. return ""
  454. }
  455. u, err := uuid.Parse(t)
  456. if err != nil {
  457. return ""
  458. }
  459. return u.String()
  460. }
  461. // GetAccessToken creates a new non-expiring, valid access token for the given
  462. // userID.
  463. func (db *datastore) GetAccessToken(userID int64) (string, error) {
  464. return db.GetTemporaryOneTimeAccessToken(userID, 0, false)
  465. }
  466. // GetTemporaryAccessToken creates a new valid access token for the given
  467. // userID that remains valid for the given time in seconds. If validSecs is 0,
  468. // the access token doesn't automatically expire.
  469. func (db *datastore) GetTemporaryAccessToken(userID int64, validSecs int) (string, error) {
  470. return db.GetTemporaryOneTimeAccessToken(userID, validSecs, false)
  471. }
  472. // GetTemporaryOneTimeAccessToken creates a new valid access token for the given
  473. // userID that remains valid for the given time in seconds and can only be used
  474. // once if oneTime is true. If validSecs is 0, the access token doesn't
  475. // automatically expire.
  476. func (db *datastore) GetTemporaryOneTimeAccessToken(userID int64, validSecs int, oneTime bool) (string, error) {
  477. u, err := uuid.NewV4()
  478. if err != nil {
  479. log.Error("Unable to generate token: %v", err)
  480. return "", err
  481. }
  482. // Insert UUID to `accesstokens`
  483. binTok := u[:]
  484. expirationVal := "NULL"
  485. if validSecs > 0 {
  486. expirationVal = fmt.Sprintf("DATE_ADD("+db.now()+", INTERVAL %d SECOND)", validSecs)
  487. }
  488. _, err = db.Exec("INSERT INTO accesstokens (token, user_id, one_time, expires) VALUES (?, ?, ?, "+expirationVal+")", string(binTok), userID, oneTime)
  489. if err != nil {
  490. log.Error("Couldn't INSERT accesstoken: %v", err)
  491. return "", err
  492. }
  493. return u.String(), nil
  494. }
  495. func (db *datastore) CreateOwnedPost(post *SubmittedPost, accessToken, collAlias, hostName string) (*PublicPost, error) {
  496. var userID, collID int64 = -1, -1
  497. var coll *Collection
  498. var err error
  499. if accessToken != "" {
  500. userID = db.GetUserID(accessToken)
  501. if userID == -1 {
  502. return nil, ErrBadAccessToken
  503. }
  504. if collAlias != "" {
  505. coll, err = db.GetCollection(collAlias)
  506. if err != nil {
  507. return nil, err
  508. }
  509. coll.hostName = hostName
  510. if coll.OwnerID != userID {
  511. return nil, ErrForbiddenCollection
  512. }
  513. collID = coll.ID
  514. }
  515. }
  516. rp := &PublicPost{}
  517. rp.Post, err = db.CreatePost(userID, collID, post)
  518. if err != nil {
  519. return rp, err
  520. }
  521. if coll != nil {
  522. coll.ForPublic()
  523. rp.Collection = &CollectionObj{Collection: *coll}
  524. }
  525. return rp, nil
  526. }
  527. func (db *datastore) CreatePost(userID, collID int64, post *SubmittedPost) (*Post, error) {
  528. idLen := postIDLen
  529. friendlyID := id.GenerateFriendlyRandomString(idLen)
  530. // Handle appearance / font face
  531. appearance := post.Font
  532. if !post.isFontValid() {
  533. appearance = "norm"
  534. }
  535. var err error
  536. ownerID := sql.NullInt64{
  537. Valid: false,
  538. }
  539. ownerCollID := sql.NullInt64{
  540. Valid: false,
  541. }
  542. slug := sql.NullString{"", false}
  543. // If an alias was supplied, we'll add this to the collection as well.
  544. if userID > 0 {
  545. ownerID.Int64 = userID
  546. ownerID.Valid = true
  547. if collID > 0 {
  548. ownerCollID.Int64 = collID
  549. ownerCollID.Valid = true
  550. var slugVal string
  551. if post.Slug != nil && *post.Slug != "" {
  552. slugVal = *post.Slug
  553. } else {
  554. if post.Title != nil && *post.Title != "" {
  555. slugVal = getSlug(*post.Title, post.Language.String)
  556. if slugVal == "" {
  557. slugVal = getSlug(*post.Content, post.Language.String)
  558. }
  559. } else {
  560. slugVal = getSlug(*post.Content, post.Language.String)
  561. }
  562. }
  563. if slugVal == "" {
  564. slugVal = friendlyID
  565. }
  566. slug = sql.NullString{slugVal, true}
  567. }
  568. }
  569. created := time.Now()
  570. if db.driverName == driverSQLite {
  571. // SQLite stores datetimes in UTC, so convert time.Now() to it here
  572. created = created.UTC()
  573. }
  574. if post.Created != nil && *post.Created != "" {
  575. created, err = time.Parse("2006-01-02T15:04:05Z", *post.Created)
  576. if err != nil {
  577. log.Error("Unable to parse Created time '%s': %v", *post.Created, err)
  578. created = time.Now()
  579. if db.driverName == driverSQLite {
  580. // SQLite stores datetimes in UTC, so convert time.Now() to it here
  581. created = created.UTC()
  582. }
  583. }
  584. }
  585. stmt, err := db.Prepare("INSERT INTO posts (id, slug, title, content, text_appearance, language, rtl, privacy, owner_id, collection_id, created, updated, view_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + db.now() + ", ?)")
  586. if err != nil {
  587. return nil, err
  588. }
  589. defer stmt.Close()
  590. _, err = stmt.Exec(friendlyID, slug, post.Title, post.Content, appearance, post.Language, post.IsRTL, 0, ownerID, ownerCollID, created, 0)
  591. if err != nil {
  592. if db.isDuplicateKeyErr(err) {
  593. // Duplicate entry error; try a new slug
  594. // TODO: make this a little more robust
  595. slug = sql.NullString{id.GenSafeUniqueSlug(slug.String), true}
  596. _, err = stmt.Exec(friendlyID, slug, post.Title, post.Content, appearance, post.Language, post.IsRTL, 0, ownerID, ownerCollID, created, 0)
  597. if err != nil {
  598. return nil, handleFailedPostInsert(fmt.Errorf("Retried slug generation, still failed: %v", err))
  599. }
  600. } else {
  601. return nil, handleFailedPostInsert(err)
  602. }
  603. }
  604. // TODO: return Created field in proper format
  605. return &Post{
  606. ID: friendlyID,
  607. Slug: null.NewString(slug.String, slug.Valid),
  608. Font: appearance,
  609. Language: zero.NewString(post.Language.String, post.Language.Valid),
  610. RTL: zero.NewBool(post.IsRTL.Bool, post.IsRTL.Valid),
  611. OwnerID: null.NewInt(userID, true),
  612. CollectionID: null.NewInt(userID, true),
  613. Created: created.Truncate(time.Second).UTC(),
  614. Updated: time.Now().Truncate(time.Second).UTC(),
  615. Title: zero.NewString(*(post.Title), true),
  616. Content: *(post.Content),
  617. }, nil
  618. }
  619. // UpdateOwnedPost updates an existing post with only the given fields in the
  620. // supplied AuthenticatedPost.
  621. func (db *datastore) UpdateOwnedPost(post *AuthenticatedPost, userID int64) error {
  622. params := []interface{}{}
  623. var queryUpdates, sep, authCondition string
  624. if post.Slug != nil && *post.Slug != "" {
  625. queryUpdates += sep + "slug = ?"
  626. sep = ", "
  627. params = append(params, getSlug(*post.Slug, ""))
  628. }
  629. if post.Content != nil {
  630. queryUpdates += sep + "content = ?"
  631. sep = ", "
  632. params = append(params, post.Content)
  633. }
  634. if post.Title != nil {
  635. queryUpdates += sep + "title = ?"
  636. sep = ", "
  637. params = append(params, post.Title)
  638. }
  639. if post.Language.Valid {
  640. queryUpdates += sep + "language = ?"
  641. sep = ", "
  642. params = append(params, post.Language.String)
  643. }
  644. if post.IsRTL.Valid {
  645. queryUpdates += sep + "rtl = ?"
  646. sep = ", "
  647. params = append(params, post.IsRTL.Bool)
  648. }
  649. if post.Font != "" {
  650. queryUpdates += sep + "text_appearance = ?"
  651. sep = ", "
  652. params = append(params, post.Font)
  653. }
  654. if post.Created != nil {
  655. createTime, err := time.Parse(postMetaDateFormat, *post.Created)
  656. if err != nil {
  657. log.Error("Unable to parse Created date: %v", err)
  658. return fmt.Errorf("That's the incorrect format for Created date.")
  659. }
  660. queryUpdates += sep + "created = ?"
  661. sep = ", "
  662. params = append(params, createTime)
  663. }
  664. // WHERE parameters...
  665. // id = ?
  666. params = append(params, post.ID)
  667. // AND owner_id = ?
  668. authCondition = "(owner_id = ?)"
  669. params = append(params, userID)
  670. if queryUpdates == "" {
  671. return ErrPostNoUpdatableVals
  672. }
  673. queryUpdates += sep + "updated = " + db.now()
  674. res, err := db.Exec("UPDATE posts SET "+queryUpdates+" WHERE id = ? AND "+authCondition, params...)
  675. if err != nil {
  676. log.Error("Unable to update owned post: %v", err)
  677. return err
  678. }
  679. rowsAffected, _ := res.RowsAffected()
  680. if rowsAffected == 0 {
  681. // Show the correct error message if nothing was updated
  682. var dummy int
  683. err := db.QueryRow("SELECT 1 FROM posts WHERE id = ? AND "+authCondition, post.ID, params[len(params)-1]).Scan(&dummy)
  684. switch {
  685. case err == sql.ErrNoRows:
  686. return ErrUnauthorizedEditPost
  687. case err != nil:
  688. log.Error("Failed selecting from posts: %v", err)
  689. }
  690. return nil
  691. }
  692. return nil
  693. }
  694. func (db *datastore) GetCollectionBy(condition string, value interface{}) (*Collection, error) {
  695. c := &Collection{}
  696. // FIXME: change Collection to reflect database values. Add helper functions to get actual values
  697. var styleSheet, script, signature, format zero.String
  698. row := db.QueryRow("SELECT id, alias, title, description, style_sheet, script, post_signature, format, owner_id, privacy, view_count FROM collections WHERE "+condition, value)
  699. err := row.Scan(&c.ID, &c.Alias, &c.Title, &c.Description, &styleSheet, &script, &signature, &format, &c.OwnerID, &c.Visibility, &c.Views)
  700. switch {
  701. case err == sql.ErrNoRows:
  702. return nil, impart.HTTPError{http.StatusNotFound, "Collection doesn't exist."}
  703. case db.isHighLoadError(err):
  704. return nil, ErrUnavailable
  705. case err != nil:
  706. log.Error("Failed selecting from collections: %v", err)
  707. return nil, err
  708. }
  709. c.StyleSheet = styleSheet.String
  710. c.Script = script.String
  711. c.Signature = signature.String
  712. c.Format = format.String
  713. c.Public = c.IsPublic()
  714. c.Monetization = db.GetCollectionAttribute(c.ID, "monetization_pointer")
  715. c.db = db
  716. return c, nil
  717. }
  718. func (db *datastore) GetCollection(alias string) (*Collection, error) {
  719. return db.GetCollectionBy("alias = ?", alias)
  720. }
  721. func (db *datastore) GetCollectionForPad(alias string) (*Collection, error) {
  722. c := &Collection{Alias: alias}
  723. row := db.QueryRow("SELECT id, alias, title, description, privacy FROM collections WHERE alias = ?", alias)
  724. err := row.Scan(&c.ID, &c.Alias, &c.Title, &c.Description, &c.Visibility)
  725. switch {
  726. case err == sql.ErrNoRows:
  727. return c, impart.HTTPError{http.StatusNotFound, "Collection doesn't exist."}
  728. case err != nil:
  729. log.Error("Failed selecting from collections: %v", err)
  730. return c, ErrInternalGeneral
  731. }
  732. c.Public = c.IsPublic()
  733. return c, nil
  734. }
  735. func (db *datastore) GetCollectionByID(id int64) (*Collection, error) {
  736. return db.GetCollectionBy("id = ?", id)
  737. }
  738. func (db *datastore) GetCollectionFromDomain(host string) (*Collection, error) {
  739. return db.GetCollectionBy("host = ?", host)
  740. }
  741. func (db *datastore) UpdateCollection(c *SubmittedCollection, alias string) error {
  742. q := query.NewUpdate().
  743. SetStringPtr(c.Title, "title").
  744. SetStringPtr(c.Description, "description").
  745. SetNullString(c.StyleSheet, "style_sheet").
  746. SetNullString(c.Script, "script").
  747. SetNullString(c.Signature, "post_signature")
  748. if c.Format != nil {
  749. cf := &CollectionFormat{Format: c.Format.String}
  750. if cf.Valid() {
  751. q.SetNullString(c.Format, "format")
  752. }
  753. }
  754. var updatePass bool
  755. if c.Visibility != nil && (collVisibility(*c.Visibility)&CollProtected == 0 || c.Pass != "") {
  756. q.SetIntPtr(c.Visibility, "privacy")
  757. if c.Pass != "" {
  758. updatePass = true
  759. }
  760. }
  761. // WHERE values
  762. q.Where("alias = ? AND owner_id = ?", alias, c.OwnerID)
  763. if q.Updates == "" && c.Monetization == nil {
  764. return ErrPostNoUpdatableVals
  765. }
  766. // Find any current domain
  767. var collID int64
  768. var rowsAffected int64
  769. var changed bool
  770. var res sql.Result
  771. err := db.QueryRow("SELECT id FROM collections WHERE alias = ?", alias).Scan(&collID)
  772. if err != nil {
  773. log.Error("Failed selecting from collections: %v. Some things won't work.", err)
  774. }
  775. // Update MathJax value
  776. if c.MathJax {
  777. if db.driverName == driverSQLite {
  778. _, err = db.Exec("INSERT OR REPLACE INTO collectionattributes (collection_id, attribute, value) VALUES (?, ?, ?)", collID, "render_mathjax", "1")
  779. } else {
  780. _, err = db.Exec("INSERT INTO collectionattributes (collection_id, attribute, value) VALUES (?, ?, ?) "+db.upsert("collection_id", "attribute")+" value = ?", collID, "render_mathjax", "1", "1")
  781. }
  782. if err != nil {
  783. log.Error("Unable to insert render_mathjax value: %v", err)
  784. return err
  785. }
  786. } else {
  787. _, err = db.Exec("DELETE FROM collectionattributes WHERE collection_id = ? AND attribute = ?", collID, "render_mathjax")
  788. if err != nil {
  789. log.Error("Unable to delete render_mathjax value: %v", err)
  790. return err
  791. }
  792. }
  793. // Update Monetization value
  794. if c.Monetization != nil {
  795. skipUpdate := false
  796. if *c.Monetization != "" {
  797. // Strip away any excess spaces
  798. trimmed := strings.TrimSpace(*c.Monetization)
  799. // Only update value when it starts with "$", per spec: https://paymentpointers.org
  800. if strings.HasPrefix(trimmed, "$") {
  801. c.Monetization = &trimmed
  802. } else {
  803. // Value appears invalid, so don't update
  804. skipUpdate = true
  805. }
  806. }
  807. if !skipUpdate {
  808. _, err = db.Exec("INSERT INTO collectionattributes (collection_id, attribute, value) VALUES (?, ?, ?) "+db.upsert("collection_id", "attribute")+" value = ?", collID, "monetization_pointer", *c.Monetization, *c.Monetization)
  809. if err != nil {
  810. log.Error("Unable to insert monetization_pointer value: %v", err)
  811. return err
  812. }
  813. }
  814. }
  815. // Update rest of the collection data
  816. if q.Updates != "" {
  817. res, err = db.Exec("UPDATE collections SET "+q.Updates+" WHERE "+q.Conditions, q.Params...)
  818. if err != nil {
  819. log.Error("Unable to update collection: %v", err)
  820. return err
  821. }
  822. }
  823. rowsAffected, _ = res.RowsAffected()
  824. if !changed || rowsAffected == 0 {
  825. // Show the correct error message if nothing was updated
  826. var dummy int
  827. err := db.QueryRow("SELECT 1 FROM collections WHERE alias = ? AND owner_id = ?", alias, c.OwnerID).Scan(&dummy)
  828. switch {
  829. case err == sql.ErrNoRows:
  830. return ErrUnauthorizedEditPost
  831. case err != nil:
  832. log.Error("Failed selecting from collections: %v", err)
  833. }
  834. if !updatePass {
  835. return nil
  836. }
  837. }
  838. if updatePass {
  839. hashedPass, err := auth.HashPass([]byte(c.Pass))
  840. if err != nil {
  841. log.Error("Unable to create hash: %s", err)
  842. return impart.HTTPError{http.StatusInternalServerError, "Could not create password hash."}
  843. }
  844. if db.driverName == driverSQLite {
  845. _, err = db.Exec("INSERT OR REPLACE INTO collectionpasswords (collection_id, password) VALUES ((SELECT id FROM collections WHERE alias = ?), ?)", alias, hashedPass)
  846. } else {
  847. _, err = db.Exec("INSERT INTO collectionpasswords (collection_id, password) VALUES ((SELECT id FROM collections WHERE alias = ?), ?) "+db.upsert("collection_id")+" password = ?", alias, hashedPass, hashedPass)
  848. }
  849. if err != nil {
  850. return err
  851. }
  852. }
  853. return nil
  854. }
  855. const postCols = "id, slug, text_appearance, language, rtl, privacy, owner_id, collection_id, pinned_position, created, updated, view_count, title, content"
  856. // getEditablePost returns a PublicPost with the given ID only if the given
  857. // edit token is valid for the post.
  858. func (db *datastore) GetEditablePost(id, editToken string) (*PublicPost, error) {
  859. // FIXME: code duplicated from getPost()
  860. // TODO: add slight logic difference to getPost / one func
  861. var ownerName sql.NullString
  862. p := &Post{}
  863. row := db.QueryRow("SELECT "+postCols+", (SELECT username FROM users WHERE users.id = posts.owner_id) AS username FROM posts WHERE id = ? LIMIT 1", id)
  864. err := row.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content, &ownerName)
  865. switch {
  866. case err == sql.ErrNoRows:
  867. return nil, ErrPostNotFound
  868. case err != nil:
  869. log.Error("Failed selecting from collections: %v", err)
  870. return nil, err
  871. }
  872. if p.Content == "" && p.Title.String == "" {
  873. return nil, ErrPostUnpublished
  874. }
  875. res := p.processPost()
  876. if ownerName.Valid {
  877. res.Owner = &PublicUser{Username: ownerName.String}
  878. }
  879. return &res, nil
  880. }
  881. func (db *datastore) PostIDExists(id string) bool {
  882. var dummy bool
  883. err := db.QueryRow("SELECT 1 FROM posts WHERE id = ?", id).Scan(&dummy)
  884. return err == nil && dummy
  885. }
  886. // GetPost gets a public-facing post object from the database. If collectionID
  887. // is > 0, the post will be retrieved by slug and collection ID, rather than
  888. // post ID.
  889. // TODO: break this into two functions:
  890. // - GetPost(id string)
  891. // - GetCollectionPost(slug string, collectionID int64)
  892. func (db *datastore) GetPost(id string, collectionID int64) (*PublicPost, error) {
  893. var ownerName sql.NullString
  894. p := &Post{}
  895. var row *sql.Row
  896. var where string
  897. params := []interface{}{id}
  898. if collectionID > 0 {
  899. where = "slug = ? AND collection_id = ?"
  900. params = append(params, collectionID)
  901. } else {
  902. where = "id = ?"
  903. }
  904. row = db.QueryRow("SELECT "+postCols+", (SELECT username FROM users WHERE users.id = posts.owner_id) AS username FROM posts WHERE "+where+" LIMIT 1", params...)
  905. err := row.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content, &ownerName)
  906. switch {
  907. case err == sql.ErrNoRows:
  908. if collectionID > 0 {
  909. return nil, ErrCollectionPageNotFound
  910. }
  911. return nil, ErrPostNotFound
  912. case err != nil:
  913. log.Error("Failed selecting from collections: %v", err)
  914. return nil, err
  915. }
  916. if p.Content == "" && p.Title.String == "" {
  917. return nil, ErrPostUnpublished
  918. }
  919. res := p.processPost()
  920. if ownerName.Valid {
  921. res.Owner = &PublicUser{Username: ownerName.String}
  922. }
  923. return &res, nil
  924. }
  925. // TODO: don't duplicate getPost() functionality
  926. func (db *datastore) GetOwnedPost(id string, ownerID int64) (*PublicPost, error) {
  927. p := &Post{}
  928. var row *sql.Row
  929. where := "id = ? AND owner_id = ?"
  930. params := []interface{}{id, ownerID}
  931. row = db.QueryRow("SELECT "+postCols+" FROM posts WHERE "+where+" LIMIT 1", params...)
  932. err := row.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content)
  933. switch {
  934. case err == sql.ErrNoRows:
  935. return nil, ErrPostNotFound
  936. case err != nil:
  937. log.Error("Failed selecting from collections: %v", err)
  938. return nil, err
  939. }
  940. if p.Content == "" && p.Title.String == "" {
  941. return nil, ErrPostUnpublished
  942. }
  943. res := p.processPost()
  944. return &res, nil
  945. }
  946. func (db *datastore) GetPostProperty(id string, collectionID int64, property string) (interface{}, error) {
  947. propSelects := map[string]string{
  948. "views": "view_count AS views",
  949. }
  950. selectQuery, ok := propSelects[property]
  951. if !ok {
  952. return nil, impart.HTTPError{http.StatusBadRequest, fmt.Sprintf("Invalid property: %s.", property)}
  953. }
  954. var res interface{}
  955. var row *sql.Row
  956. if collectionID != 0 {
  957. row = db.QueryRow("SELECT "+selectQuery+" FROM posts WHERE slug = ? AND collection_id = ? LIMIT 1", id, collectionID)
  958. } else {
  959. row = db.QueryRow("SELECT "+selectQuery+" FROM posts WHERE id = ? LIMIT 1", id)
  960. }
  961. err := row.Scan(&res)
  962. switch {
  963. case err == sql.ErrNoRows:
  964. return nil, impart.HTTPError{http.StatusNotFound, "Post not found."}
  965. case err != nil:
  966. log.Error("Failed selecting post: %v", err)
  967. return nil, err
  968. }
  969. return res, nil
  970. }
  971. // GetPostsCount modifies the CollectionObj to include the correct number of
  972. // standard (non-pinned) posts. It will return future posts if `includeFuture`
  973. // is true.
  974. func (db *datastore) GetPostsCount(c *CollectionObj, includeFuture bool) {
  975. var count int64
  976. timeCondition := ""
  977. if !includeFuture {
  978. timeCondition = "AND created <= " + db.now()
  979. }
  980. err := db.QueryRow("SELECT COUNT(*) FROM posts WHERE collection_id = ? AND pinned_position IS NULL "+timeCondition, c.ID).Scan(&count)
  981. switch {
  982. case err == sql.ErrNoRows:
  983. c.TotalPosts = 0
  984. case err != nil:
  985. log.Error("Failed selecting from collections: %v", err)
  986. c.TotalPosts = 0
  987. }
  988. c.TotalPosts = int(count)
  989. }
  990. // GetPosts retrieves all posts for the given Collection.
  991. // It will return future posts if `includeFuture` is true.
  992. // It will include only standard (non-pinned) posts unless `includePinned` is true.
  993. // TODO: change includeFuture to isOwner, since that's how it's used
  994. func (db *datastore) GetPosts(cfg *config.Config, c *Collection, page int, includeFuture, forceRecentFirst, includePinned bool) (*[]PublicPost, error) {
  995. collID := c.ID
  996. cf := c.NewFormat()
  997. order := "DESC"
  998. if cf.Ascending() && !forceRecentFirst {
  999. order = "ASC"
  1000. }
  1001. pagePosts := cf.PostsPerPage()
  1002. start := page*pagePosts - pagePosts
  1003. if page == 0 {
  1004. start = 0
  1005. pagePosts = 1000
  1006. }
  1007. limitStr := ""
  1008. if page > 0 {
  1009. limitStr = fmt.Sprintf(" LIMIT %d, %d", start, pagePosts)
  1010. }
  1011. timeCondition := ""
  1012. if !includeFuture {
  1013. timeCondition = "AND created <= " + db.now()
  1014. }
  1015. pinnedCondition := ""
  1016. if !includePinned {
  1017. pinnedCondition = "AND pinned_position IS NULL"
  1018. }
  1019. rows, err := db.Query("SELECT "+postCols+" FROM posts WHERE collection_id = ? "+pinnedCondition+" "+timeCondition+" ORDER BY created "+order+limitStr, collID)
  1020. if err != nil {
  1021. log.Error("Failed selecting from posts: %v", err)
  1022. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve collection posts."}
  1023. }
  1024. defer rows.Close()
  1025. // TODO: extract this common row scanning logic for queries using `postCols`
  1026. posts := []PublicPost{}
  1027. for rows.Next() {
  1028. p := &Post{}
  1029. err = rows.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content)
  1030. if err != nil {
  1031. log.Error("Failed scanning row: %v", err)
  1032. break
  1033. }
  1034. p.extractData()
  1035. p.augmentContent(c)
  1036. p.formatContent(cfg, c, includeFuture, false)
  1037. posts = append(posts, p.processPost())
  1038. }
  1039. err = rows.Err()
  1040. if err != nil {
  1041. log.Error("Error after Next() on rows: %v", err)
  1042. }
  1043. return &posts, nil
  1044. }
  1045. func (db *datastore) GetAllPostsTaggedIDs(c *Collection, tag string, includeFuture bool) ([]string, error) {
  1046. collID := c.ID
  1047. cf := c.NewFormat()
  1048. order := "DESC"
  1049. if cf.Ascending() {
  1050. order = "ASC"
  1051. }
  1052. timeCondition := ""
  1053. if !includeFuture {
  1054. timeCondition = "AND created <= NOW()"
  1055. }
  1056. var rows *sql.Rows
  1057. var err error
  1058. if db.driverName == driverSQLite {
  1059. rows, err = db.Query("SELECT id FROM posts WHERE collection_id = ? AND LOWER(content) regexp ? "+timeCondition+" ORDER BY created "+order, collID, `.*#`+strings.ToLower(tag)+`\b.*`)
  1060. } else {
  1061. rows, err = db.Query("SELECT id FROM posts WHERE collection_id = ? AND LOWER(content) RLIKE ? "+timeCondition+" ORDER BY created "+order, collID, "#"+strings.ToLower(tag)+"[[:>:]]")
  1062. }
  1063. if err != nil {
  1064. log.Error("Failed selecting tagged posts: %v", err)
  1065. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve tagged collection posts."}
  1066. }
  1067. defer rows.Close()
  1068. ids := []string{}
  1069. for rows.Next() {
  1070. var id string
  1071. err = rows.Scan(&id)
  1072. if err != nil {
  1073. log.Error("Failed scanning row: %v", err)
  1074. break
  1075. }
  1076. ids = append(ids, id)
  1077. }
  1078. err = rows.Err()
  1079. if err != nil {
  1080. log.Error("Error after Next() on rows: %v", err)
  1081. }
  1082. return ids, nil
  1083. }
  1084. // GetPostsTagged retrieves all posts on the given Collection that contain the
  1085. // given tag.
  1086. // It will return future posts if `includeFuture` is true.
  1087. // TODO: change includeFuture to isOwner, since that's how it's used
  1088. func (db *datastore) GetPostsTagged(cfg *config.Config, c *Collection, tag string, page int, includeFuture bool) (*[]PublicPost, error) {
  1089. collID := c.ID
  1090. cf := c.NewFormat()
  1091. order := "DESC"
  1092. if cf.Ascending() {
  1093. order = "ASC"
  1094. }
  1095. pagePosts := cf.PostsPerPage()
  1096. start := page*pagePosts - pagePosts
  1097. if page == 0 {
  1098. start = 0
  1099. pagePosts = 1000
  1100. }
  1101. limitStr := ""
  1102. if page > 0 {
  1103. limitStr = fmt.Sprintf(" LIMIT %d, %d", start, pagePosts)
  1104. }
  1105. timeCondition := ""
  1106. if !includeFuture {
  1107. timeCondition = "AND created <= " + db.now()
  1108. }
  1109. var rows *sql.Rows
  1110. var err error
  1111. if db.driverName == driverSQLite {
  1112. rows, err = db.Query("SELECT "+postCols+" FROM posts WHERE collection_id = ? AND LOWER(content) regexp ? "+timeCondition+" ORDER BY created "+order+limitStr, collID, `.*#`+strings.ToLower(tag)+`\b.*`)
  1113. } else {
  1114. rows, err = db.Query("SELECT "+postCols+" FROM posts WHERE collection_id = ? AND LOWER(content) RLIKE ? "+timeCondition+" ORDER BY created "+order+limitStr, collID, "#"+strings.ToLower(tag)+"[[:>:]]")
  1115. }
  1116. if err != nil {
  1117. log.Error("Failed selecting from posts: %v", err)
  1118. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve collection posts."}
  1119. }
  1120. defer rows.Close()
  1121. // TODO: extract this common row scanning logic for queries using `postCols`
  1122. posts := []PublicPost{}
  1123. for rows.Next() {
  1124. p := &Post{}
  1125. err = rows.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content)
  1126. if err != nil {
  1127. log.Error("Failed scanning row: %v", err)
  1128. break
  1129. }
  1130. p.extractData()
  1131. p.augmentContent(c)
  1132. p.formatContent(cfg, c, includeFuture, false)
  1133. posts = append(posts, p.processPost())
  1134. }
  1135. err = rows.Err()
  1136. if err != nil {
  1137. log.Error("Error after Next() on rows: %v", err)
  1138. }
  1139. return &posts, nil
  1140. }
  1141. func (db *datastore) GetAPFollowers(c *Collection) (*[]RemoteUser, error) {
  1142. rows, err := db.Query("SELECT actor_id, inbox, shared_inbox FROM remotefollows f INNER JOIN remoteusers u ON f.remote_user_id = u.id WHERE collection_id = ?", c.ID)
  1143. if err != nil {
  1144. log.Error("Failed selecting from followers: %v", err)
  1145. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve followers."}
  1146. }
  1147. defer rows.Close()
  1148. followers := []RemoteUser{}
  1149. for rows.Next() {
  1150. f := RemoteUser{}
  1151. err = rows.Scan(&f.ActorID, &f.Inbox, &f.SharedInbox)
  1152. followers = append(followers, f)
  1153. }
  1154. return &followers, nil
  1155. }
  1156. // CanCollect returns whether or not the given user can add the given post to a
  1157. // collection. This is true when a post is already owned by the user.
  1158. // NOTE: this is currently only used to potentially add owned posts to a
  1159. // collection. This has the SIDE EFFECT of also generating a slug for the post.
  1160. // FIXME: make this side effect more explicit (or extract it)
  1161. func (db *datastore) CanCollect(cpr *ClaimPostRequest, userID int64) bool {
  1162. var title, content string
  1163. var lang sql.NullString
  1164. err := db.QueryRow("SELECT title, content, language FROM posts WHERE id = ? AND owner_id = ?", cpr.ID, userID).Scan(&title, &content, &lang)
  1165. switch {
  1166. case err == sql.ErrNoRows:
  1167. return false
  1168. case err != nil:
  1169. log.Error("Failed on post CanCollect(%s, %d): %v", cpr.ID, userID, err)
  1170. return false
  1171. }
  1172. // Since we have the post content and the post is collectable, generate the
  1173. // post's slug now.
  1174. cpr.Slug = getSlugFromPost(title, content, lang.String)
  1175. return true
  1176. }
  1177. func (db *datastore) AttemptClaim(p *ClaimPostRequest, query string, params []interface{}, slugIdx int) (sql.Result, error) {
  1178. qRes, err := db.Exec(query, params...)
  1179. if err != nil {
  1180. if db.isDuplicateKeyErr(err) && slugIdx > -1 {
  1181. s := id.GenSafeUniqueSlug(p.Slug)
  1182. if s == p.Slug {
  1183. // Sanity check to prevent infinite recursion
  1184. return qRes, fmt.Errorf("GenSafeUniqueSlug generated nothing unique: %s", s)
  1185. }
  1186. p.Slug = s
  1187. params[slugIdx] = p.Slug
  1188. return db.AttemptClaim(p, query, params, slugIdx)
  1189. }
  1190. return qRes, fmt.Errorf("attemptClaim: %s", err)
  1191. }
  1192. return qRes, nil
  1193. }
  1194. func (db *datastore) DispersePosts(userID int64, postIDs []string) (*[]ClaimPostResult, error) {
  1195. postClaimReqs := map[string]bool{}
  1196. res := []ClaimPostResult{}
  1197. for i := range postIDs {
  1198. postID := postIDs[i]
  1199. r := ClaimPostResult{Code: 0, ErrorMessage: ""}
  1200. // Perform post validation
  1201. if postID == "" {
  1202. r.ErrorMessage = "Missing post ID. "
  1203. }
  1204. if _, ok := postClaimReqs[postID]; ok {
  1205. r.Code = 429
  1206. r.ErrorMessage = "You've already tried anonymizing this post."
  1207. r.ID = postID
  1208. res = append(res, r)
  1209. continue
  1210. }
  1211. postClaimReqs[postID] = true
  1212. var err error
  1213. // Get full post information to return
  1214. var fullPost *PublicPost
  1215. fullPost, err = db.GetPost(postID, 0)
  1216. if err != nil {
  1217. if err, ok := err.(impart.HTTPError); ok {
  1218. r.Code = err.Status
  1219. r.ErrorMessage = err.Message
  1220. r.ID = postID
  1221. res = append(res, r)
  1222. continue
  1223. } else {
  1224. log.Error("Error getting post in dispersePosts: %v", err)
  1225. }
  1226. }
  1227. if fullPost.OwnerID.Int64 != userID {
  1228. r.Code = http.StatusConflict
  1229. r.ErrorMessage = "Post is already owned by someone else."
  1230. r.ID = postID
  1231. res = append(res, r)
  1232. continue
  1233. }
  1234. var qRes sql.Result
  1235. var query string
  1236. var params []interface{}
  1237. // Do AND owner_id = ? for sanity.
  1238. // This should've been caught and returned with a good error message
  1239. // just above.
  1240. query = "UPDATE posts SET collection_id = NULL WHERE id = ? AND owner_id = ?"
  1241. params = []interface{}{postID, userID}
  1242. qRes, err = db.Exec(query, params...)
  1243. if err != nil {
  1244. r.Code = http.StatusInternalServerError
  1245. r.ErrorMessage = "A glitch happened on our end."
  1246. r.ID = postID
  1247. res = append(res, r)
  1248. log.Error("dispersePosts (post %s): %v", postID, err)
  1249. continue
  1250. }
  1251. // Post was successfully dispersed
  1252. r.Code = http.StatusOK
  1253. r.Post = fullPost
  1254. rowsAffected, _ := qRes.RowsAffected()
  1255. if rowsAffected == 0 {
  1256. // This was already claimed, but return 200
  1257. r.Code = http.StatusOK
  1258. }
  1259. res = append(res, r)
  1260. }
  1261. return &res, nil
  1262. }
  1263. func (db *datastore) ClaimPosts(cfg *config.Config, userID int64, collAlias string, posts *[]ClaimPostRequest) (*[]ClaimPostResult, error) {
  1264. postClaimReqs := map[string]bool{}
  1265. res := []ClaimPostResult{}
  1266. postCollAlias := collAlias
  1267. for i := range *posts {
  1268. p := (*posts)[i]
  1269. if &p == nil {
  1270. continue
  1271. }
  1272. r := ClaimPostResult{Code: 0, ErrorMessage: ""}
  1273. // Perform post validation
  1274. if p.ID == "" {
  1275. r.ErrorMessage = "Missing post ID `id`. "
  1276. }
  1277. if _, ok := postClaimReqs[p.ID]; ok {
  1278. r.Code = 429
  1279. r.ErrorMessage = "You've already tried claiming this post."
  1280. r.ID = p.ID
  1281. res = append(res, r)
  1282. continue
  1283. }
  1284. postClaimReqs[p.ID] = true
  1285. canCollect := db.CanCollect(&p, userID)
  1286. if !canCollect && p.Token == "" {
  1287. // TODO: ensure post isn't owned by anyone else when a valid modify
  1288. // token is given.
  1289. r.ErrorMessage += "Missing post Edit Token `token`."
  1290. }
  1291. if r.ErrorMessage != "" {
  1292. // Post validate failed
  1293. r.Code = http.StatusBadRequest
  1294. r.ID = p.ID
  1295. res = append(res, r)
  1296. continue
  1297. }
  1298. var err error
  1299. var qRes sql.Result
  1300. var query string
  1301. var params []interface{}
  1302. var slugIdx int = -1
  1303. var coll *Collection
  1304. if collAlias == "" {
  1305. // Posts are being claimed at /posts/claim, not
  1306. // /collections/{alias}/collect, so use given individual collection
  1307. // to associate post with.
  1308. postCollAlias = p.CollectionAlias
  1309. }
  1310. if postCollAlias != "" {
  1311. // Associate this post with a collection
  1312. if p.CreateCollection {
  1313. // This is a new collection
  1314. // TODO: consider removing this. This seriously complicates this
  1315. // method and adds another (unnecessary?) logic path.
  1316. coll, err = db.CreateCollection(cfg, postCollAlias, "", userID)
  1317. if err != nil {
  1318. if err, ok := err.(impart.HTTPError); ok {
  1319. r.Code = err.Status
  1320. r.ErrorMessage = err.Message
  1321. } else {
  1322. r.Code = http.StatusInternalServerError
  1323. r.ErrorMessage = "Unknown error occurred creating collection"
  1324. }
  1325. r.ID = p.ID
  1326. res = append(res, r)
  1327. continue
  1328. }
  1329. } else {
  1330. // Attempt to add to existing collection
  1331. coll, err = db.GetCollection(postCollAlias)
  1332. if err != nil {
  1333. if err, ok := err.(impart.HTTPError); ok {
  1334. if err.Status == http.StatusNotFound {
  1335. // Show obfuscated "forbidden" response, as if attempting to add to an
  1336. // unowned blog.
  1337. r.Code = ErrForbiddenCollection.Status
  1338. r.ErrorMessage = ErrForbiddenCollection.Message
  1339. } else {
  1340. r.Code = err.Status
  1341. r.ErrorMessage = err.Message
  1342. }
  1343. } else {
  1344. r.Code = http.StatusInternalServerError
  1345. r.ErrorMessage = "Unknown error occurred claiming post with collection"
  1346. }
  1347. r.ID = p.ID
  1348. res = append(res, r)
  1349. continue
  1350. }
  1351. if coll.OwnerID != userID {
  1352. r.Code = ErrForbiddenCollection.Status
  1353. r.ErrorMessage = ErrForbiddenCollection.Message
  1354. r.ID = p.ID
  1355. res = append(res, r)
  1356. continue
  1357. }
  1358. }
  1359. if p.Slug == "" {
  1360. p.Slug = p.ID
  1361. }
  1362. if canCollect {
  1363. // User already owns this post, so just add it to the given
  1364. // collection.
  1365. query = "UPDATE posts SET collection_id = ?, slug = ? WHERE id = ? AND owner_id = ?"
  1366. params = []interface{}{coll.ID, p.Slug, p.ID, userID}
  1367. slugIdx = 1
  1368. } else {
  1369. query = "UPDATE posts SET owner_id = ?, collection_id = ?, slug = ? WHERE id = ? AND modify_token = ? AND owner_id IS NULL"
  1370. params = []interface{}{userID, coll.ID, p.Slug, p.ID, p.Token}
  1371. slugIdx = 2
  1372. }
  1373. } else {
  1374. query = "UPDATE posts SET owner_id = ? WHERE id = ? AND modify_token = ? AND owner_id IS NULL"
  1375. params = []interface{}{userID, p.ID, p.Token}
  1376. }
  1377. qRes, err = db.AttemptClaim(&p, query, params, slugIdx)
  1378. if err != nil {
  1379. r.Code = http.StatusInternalServerError
  1380. r.ErrorMessage = "An unknown error occurred."
  1381. r.ID = p.ID
  1382. res = append(res, r)
  1383. log.Error("claimPosts (post %s): %v", p.ID, err)
  1384. continue
  1385. }
  1386. // Get full post information to return
  1387. var fullPost *PublicPost
  1388. if p.Token != "" {
  1389. fullPost, err = db.GetEditablePost(p.ID, p.Token)
  1390. } else {
  1391. fullPost, err = db.GetPost(p.ID, 0)
  1392. }
  1393. if err != nil {
  1394. if err, ok := err.(impart.HTTPError); ok {
  1395. r.Code = err.Status
  1396. r.ErrorMessage = err.Message
  1397. r.ID = p.ID
  1398. res = append(res, r)
  1399. continue
  1400. }
  1401. }
  1402. if fullPost.OwnerID.Int64 != userID {
  1403. r.Code = http.StatusConflict
  1404. r.ErrorMessage = "Post is already owned by someone else."
  1405. r.ID = p.ID
  1406. res = append(res, r)
  1407. continue
  1408. }
  1409. // Post was successfully claimed
  1410. r.Code = http.StatusOK
  1411. r.Post = fullPost
  1412. if coll != nil {
  1413. r.Post.Collection = &CollectionObj{Collection: *coll}
  1414. }
  1415. rowsAffected, _ := qRes.RowsAffected()
  1416. if rowsAffected == 0 {
  1417. // This was already claimed, but return 200
  1418. r.Code = http.StatusOK
  1419. }
  1420. res = append(res, r)
  1421. }
  1422. return &res, nil
  1423. }
  1424. func (db *datastore) UpdatePostPinState(pinned bool, postID string, collID, ownerID, pos int64) error {
  1425. if pos <= 0 || pos > 20 {
  1426. pos = db.GetLastPinnedPostPos(collID) + 1
  1427. if pos == -1 {
  1428. pos = 1
  1429. }
  1430. }
  1431. var err error
  1432. if pinned {
  1433. _, err = db.Exec("UPDATE posts SET pinned_position = ? WHERE id = ?", pos, postID)
  1434. } else {
  1435. _, err = db.Exec("UPDATE posts SET pinned_position = NULL WHERE id = ?", postID)
  1436. }
  1437. if err != nil {
  1438. log.Error("Unable to update pinned post: %v", err)
  1439. return err
  1440. }
  1441. return nil
  1442. }
  1443. func (db *datastore) GetLastPinnedPostPos(collID int64) int64 {
  1444. var lastPos sql.NullInt64
  1445. err := db.QueryRow("SELECT MAX(pinned_position) FROM posts WHERE collection_id = ? AND pinned_position IS NOT NULL", collID).Scan(&lastPos)
  1446. switch {
  1447. case err == sql.ErrNoRows:
  1448. return -1
  1449. case err != nil:
  1450. log.Error("Failed selecting from posts: %v", err)
  1451. return -1
  1452. }
  1453. if !lastPos.Valid {
  1454. return -1
  1455. }
  1456. return lastPos.Int64
  1457. }
  1458. func (db *datastore) GetPinnedPosts(coll *CollectionObj, includeFuture bool) (*[]PublicPost, error) {
  1459. // FIXME: sqlite-backed instances don't include ellipsis on truncated titles
  1460. timeCondition := ""
  1461. if !includeFuture {
  1462. timeCondition = "AND created <= " + db.now()
  1463. }
  1464. rows, err := db.Query("SELECT id, slug, title, "+db.clip("content", 80)+", pinned_position FROM posts WHERE collection_id = ? AND pinned_position IS NOT NULL "+timeCondition+" ORDER BY pinned_position ASC", coll.ID)
  1465. if err != nil {
  1466. log.Error("Failed selecting pinned posts: %v", err)
  1467. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve pinned posts."}
  1468. }
  1469. defer rows.Close()
  1470. posts := []PublicPost{}
  1471. for rows.Next() {
  1472. p := &Post{}
  1473. err = rows.Scan(&p.ID, &p.Slug, &p.Title, &p.Content, &p.PinnedPosition)
  1474. if err != nil {
  1475. log.Error("Failed scanning row: %v", err)
  1476. break
  1477. }
  1478. p.extractData()
  1479. p.augmentContent(&coll.Collection)
  1480. pp := p.processPost()
  1481. pp.Collection = coll
  1482. posts = append(posts, pp)
  1483. }
  1484. return &posts, nil
  1485. }
  1486. func (db *datastore) GetCollections(u *User, hostName string) (*[]Collection, error) {
  1487. rows, err := db.Query("SELECT id, alias, title, description, privacy, view_count FROM collections WHERE owner_id = ? ORDER BY id ASC", u.ID)
  1488. if err != nil {
  1489. log.Error("Failed selecting from collections: %v", err)
  1490. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user collections."}
  1491. }
  1492. defer rows.Close()
  1493. colls := []Collection{}
  1494. for rows.Next() {
  1495. c := Collection{}
  1496. err = rows.Scan(&c.ID, &c.Alias, &c.Title, &c.Description, &c.Visibility, &c.Views)
  1497. if err != nil {
  1498. log.Error("Failed scanning row: %v", err)
  1499. break
  1500. }
  1501. c.hostName = hostName
  1502. c.URL = c.CanonicalURL()
  1503. c.Public = c.IsPublic()
  1504. /*
  1505. // NOTE: future functionality
  1506. if visibility != nil { // TODO: && visibility == CollPublic {
  1507. // Add Monetization info when retrieving all public collections
  1508. c.Monetization = db.GetCollectionAttribute(c.ID, "monetization_pointer")
  1509. }
  1510. */
  1511. colls = append(colls, c)
  1512. }
  1513. err = rows.Err()
  1514. if err != nil {
  1515. log.Error("Error after Next() on rows: %v", err)
  1516. }
  1517. return &colls, nil
  1518. }
  1519. func (db *datastore) GetPublishableCollections(u *User, hostName string) (*[]Collection, error) {
  1520. c, err := db.GetCollections(u, hostName)
  1521. if err != nil {
  1522. return nil, err
  1523. }
  1524. if len(*c) == 0 {
  1525. return nil, impart.HTTPError{http.StatusInternalServerError, "You don't seem to have any blogs; they might've moved to another account. Try logging out and logging into your other account."}
  1526. }
  1527. return c, nil
  1528. }
  1529. func (db *datastore) GetPublicCollections(hostName string) (*[]Collection, error) {
  1530. rows, err := db.Query(`SELECT c.id, alias, title, description, privacy, view_count
  1531. FROM collections c
  1532. LEFT JOIN users u ON u.id = c.owner_id
  1533. WHERE c.privacy = 1 AND u.status = 0
  1534. ORDER BY title ASC`)
  1535. if err != nil {
  1536. log.Error("Failed selecting public collections: %v", err)
  1537. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve public collections."}
  1538. }
  1539. defer rows.Close()
  1540. colls := []Collection{}
  1541. for rows.Next() {
  1542. c := Collection{}
  1543. err = rows.Scan(&c.ID, &c.Alias, &c.Title, &c.Description, &c.Visibility, &c.Views)
  1544. if err != nil {
  1545. log.Error("Failed scanning row: %v", err)
  1546. break
  1547. }
  1548. c.hostName = hostName
  1549. c.URL = c.CanonicalURL()
  1550. c.Public = c.IsPublic()
  1551. // Add Monetization information
  1552. c.Monetization = db.GetCollectionAttribute(c.ID, "monetization_pointer")
  1553. colls = append(colls, c)
  1554. }
  1555. err = rows.Err()
  1556. if err != nil {
  1557. log.Error("Error after Next() on rows: %v", err)
  1558. }
  1559. return &colls, nil
  1560. }
  1561. func (db *datastore) GetMeStats(u *User) userMeStats {
  1562. s := userMeStats{}
  1563. // User counts
  1564. colls, _ := db.GetUserCollectionCount(u.ID)
  1565. s.TotalCollections = colls
  1566. var articles, collPosts uint64
  1567. err := db.QueryRow("SELECT COUNT(*) FROM posts WHERE owner_id = ? AND collection_id IS NULL", u.ID).Scan(&articles)
  1568. if err != nil && err != sql.ErrNoRows {
  1569. log.Error("Couldn't get articles count for user %d: %v", u.ID, err)
  1570. }
  1571. s.TotalArticles = articles
  1572. err = db.QueryRow("SELECT COUNT(*) FROM posts WHERE owner_id = ? AND collection_id IS NOT NULL", u.ID).Scan(&collPosts)
  1573. if err != nil && err != sql.ErrNoRows {
  1574. log.Error("Couldn't get coll posts count for user %d: %v", u.ID, err)
  1575. }
  1576. s.CollectionPosts = collPosts
  1577. return s
  1578. }
  1579. func (db *datastore) GetTotalCollections() (collCount int64, err error) {
  1580. err = db.QueryRow(`
  1581. SELECT COUNT(*)
  1582. FROM collections c
  1583. LEFT JOIN users u ON u.id = c.owner_id
  1584. WHERE u.status = 0`).Scan(&collCount)
  1585. if err != nil {
  1586. log.Error("Unable to fetch collections count: %v", err)
  1587. }
  1588. return
  1589. }
  1590. func (db *datastore) GetTotalPosts() (postCount int64, err error) {
  1591. err = db.QueryRow(`
  1592. SELECT COUNT(*)
  1593. FROM posts p
  1594. LEFT JOIN users u ON u.id = p.owner_id
  1595. WHERE u.status = 0`).Scan(&postCount)
  1596. if err != nil {
  1597. log.Error("Unable to fetch posts count: %v", err)
  1598. }
  1599. return
  1600. }
  1601. func (db *datastore) GetTopPosts(u *User, alias string, hostName string) (*[]PublicPost, error) {
  1602. params := []interface{}{u.ID}
  1603. where := ""
  1604. if alias != "" {
  1605. where = " AND alias = ?"
  1606. params = append(params, alias)
  1607. }
  1608. rows, err := db.Query("SELECT p.id, p.slug, p.view_count, p.title, p.content, c.alias, c.title, c.description, c.view_count FROM posts p LEFT JOIN collections c ON p.collection_id = c.id WHERE p.owner_id = ?"+where+" ORDER BY p.view_count DESC, created DESC LIMIT 25", params...)
  1609. if err != nil {
  1610. log.Error("Failed selecting from posts: %v", err)
  1611. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user top posts."}
  1612. }
  1613. defer rows.Close()
  1614. posts := []PublicPost{}
  1615. var gotErr bool
  1616. for rows.Next() {
  1617. p := Post{}
  1618. c := Collection{}
  1619. var alias, title, description sql.NullString
  1620. var views sql.NullInt64
  1621. err = rows.Scan(&p.ID, &p.Slug, &p.ViewCount, &p.Title, &p.Content, &alias, &title, &description, &views)
  1622. if err != nil {
  1623. log.Error("Failed scanning User.getPosts() row: %v", err)
  1624. gotErr = true
  1625. break
  1626. }
  1627. p.extractData()
  1628. pubPost := p.processPost()
  1629. if alias.Valid && alias.String != "" {
  1630. c.Alias = alias.String
  1631. c.Title = title.String
  1632. c.Description = description.String
  1633. c.Views = views.Int64
  1634. c.hostName = hostName
  1635. pubPost.Collection = &CollectionObj{Collection: c}
  1636. }
  1637. posts = append(posts, pubPost)
  1638. }
  1639. err = rows.Err()
  1640. if err != nil {
  1641. log.Error("Error after Next() on rows: %v", err)
  1642. }
  1643. if gotErr && len(posts) == 0 {
  1644. // There were a lot of errors
  1645. return nil, impart.HTTPError{http.StatusInternalServerError, "Unable to get data."}
  1646. }
  1647. return &posts, nil
  1648. }
  1649. func (db *datastore) GetAnonymousPosts(u *User, page int) (*[]PublicPost, error) {
  1650. pagePosts := 10
  1651. start := page*pagePosts - pagePosts
  1652. if page == 0 {
  1653. start = 0
  1654. pagePosts = 1000
  1655. }
  1656. limitStr := ""
  1657. if page > 0 {
  1658. limitStr = fmt.Sprintf(" LIMIT %d, %d", start, pagePosts)
  1659. }
  1660. rows, err := db.Query("SELECT id, view_count, title, language, created, updated, content FROM posts WHERE owner_id = ? AND collection_id IS NULL ORDER BY created DESC"+limitStr, u.ID)
  1661. if err != nil {
  1662. log.Error("Failed selecting from posts: %v", err)
  1663. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user anonymous posts."}
  1664. }
  1665. defer rows.Close()
  1666. posts := []PublicPost{}
  1667. for rows.Next() {
  1668. p := Post{}
  1669. err = rows.Scan(&p.ID, &p.ViewCount, &p.Title, &p.Language, &p.Created, &p.Updated, &p.Content)
  1670. if err != nil {
  1671. log.Error("Failed scanning row: %v", err)
  1672. break
  1673. }
  1674. p.extractData()
  1675. posts = append(posts, p.processPost())
  1676. }
  1677. err = rows.Err()
  1678. if err != nil {
  1679. log.Error("Error after Next() on rows: %v", err)
  1680. }
  1681. return &posts, nil
  1682. }
  1683. func (db *datastore) GetUserPosts(u *User) (*[]PublicPost, error) {
  1684. rows, err := db.Query("SELECT p.id, p.slug, p.view_count, p.title, p.created, p.updated, p.content, p.text_appearance, p.language, p.rtl, c.alias, c.title, c.description, c.view_count FROM posts p LEFT JOIN collections c ON collection_id = c.id WHERE p.owner_id = ? ORDER BY created ASC", u.ID)
  1685. if err != nil {
  1686. log.Error("Failed selecting from posts: %v", err)
  1687. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user posts."}
  1688. }
  1689. defer rows.Close()
  1690. posts := []PublicPost{}
  1691. var gotErr bool
  1692. for rows.Next() {
  1693. p := Post{}
  1694. c := Collection{}
  1695. var alias, title, description sql.NullString
  1696. var views sql.NullInt64
  1697. err = rows.Scan(&p.ID, &p.Slug, &p.ViewCount, &p.Title, &p.Created, &p.Updated, &p.Content, &p.Font, &p.Language, &p.RTL, &alias, &title, &description, &views)
  1698. if err != nil {
  1699. log.Error("Failed scanning User.getPosts() row: %v", err)
  1700. gotErr = true
  1701. break
  1702. }
  1703. p.extractData()
  1704. pubPost := p.processPost()
  1705. if alias.Valid && alias.String != "" {
  1706. c.Alias = alias.String
  1707. c.Title = title.String
  1708. c.Description = description.String
  1709. c.Views = views.Int64
  1710. pubPost.Collection = &CollectionObj{Collection: c}
  1711. }
  1712. posts = append(posts, pubPost)
  1713. }
  1714. err = rows.Err()
  1715. if err != nil {
  1716. log.Error("Error after Next() on rows: %v", err)
  1717. }
  1718. if gotErr && len(posts) == 0 {
  1719. // There were a lot of errors
  1720. return nil, impart.HTTPError{http.StatusInternalServerError, "Unable to get data."}
  1721. }
  1722. return &posts, nil
  1723. }
  1724. func (db *datastore) GetUserPostsCount(userID int64) int64 {
  1725. var count int64
  1726. err := db.QueryRow("SELECT COUNT(*) FROM posts WHERE owner_id = ?", userID).Scan(&count)
  1727. switch {
  1728. case err == sql.ErrNoRows:
  1729. return 0
  1730. case err != nil:
  1731. log.Error("Failed selecting posts count for user %d: %v", userID, err)
  1732. return 0
  1733. }
  1734. return count
  1735. }
  1736. // ChangeSettings takes a User and applies the changes in the given
  1737. // userSettings, MODIFYING THE USER with successful changes.
  1738. func (db *datastore) ChangeSettings(app *App, u *User, s *userSettings) error {
  1739. var errPass error
  1740. q := query.NewUpdate()
  1741. // Update email if given
  1742. if s.Email != "" {
  1743. encEmail, err := data.Encrypt(app.keys.EmailKey, s.Email)
  1744. if err != nil {
  1745. log.Error("Couldn't encrypt email %s: %s\n", s.Email, err)
  1746. return impart.HTTPError{http.StatusInternalServerError, "Unable to encrypt email address."}
  1747. }
  1748. q.SetBytes(encEmail, "email")
  1749. // Update the email if something goes awry updating the password
  1750. defer func() {
  1751. if errPass != nil {
  1752. db.UpdateEncryptedUserEmail(u.ID, encEmail)
  1753. }
  1754. }()
  1755. u.Email = zero.StringFrom(s.Email)
  1756. }
  1757. // Update username if given
  1758. var newUsername string
  1759. if s.Username != "" {
  1760. var ie *impart.HTTPError
  1761. newUsername, ie = getValidUsername(app, s.Username, u.Username)
  1762. if ie != nil {
  1763. // Username is invalid
  1764. return *ie
  1765. }
  1766. if !author.IsValidUsername(app.cfg, newUsername) {
  1767. // Ensure the username is syntactically correct.
  1768. return impart.HTTPError{http.StatusPreconditionFailed, "Username isn't valid."}
  1769. }
  1770. t, err := db.Begin()
  1771. if err != nil {
  1772. log.Error("Couldn't start username change transaction: %v", err)
  1773. return err
  1774. }
  1775. _, err = t.Exec("UPDATE users SET username = ? WHERE id = ?", newUsername, u.ID)
  1776. if err != nil {
  1777. t.Rollback()
  1778. if db.isDuplicateKeyErr(err) {
  1779. return impart.HTTPError{http.StatusConflict, "Username is already taken."}
  1780. }
  1781. log.Error("Unable to update users table: %v", err)
  1782. return ErrInternalGeneral
  1783. }
  1784. _, err = t.Exec("UPDATE collections SET alias = ? WHERE alias = ? AND owner_id = ?", newUsername, u.Username, u.ID)
  1785. if err != nil {
  1786. t.Rollback()
  1787. if db.isDuplicateKeyErr(err) {
  1788. return impart.HTTPError{http.StatusConflict, "Username is already taken."}
  1789. }
  1790. log.Error("Unable to update collection: %v", err)
  1791. return ErrInternalGeneral
  1792. }
  1793. // Keep track of name changes for redirection
  1794. db.RemoveCollectionRedirect(t, newUsername)
  1795. _, err = t.Exec("UPDATE collectionredirects SET new_alias = ? WHERE new_alias = ?", newUsername, u.Username)
  1796. if err != nil {
  1797. log.Error("Unable to update collectionredirects: %v", err)
  1798. }
  1799. _, err = t.Exec("INSERT INTO collectionredirects (prev_alias, new_alias) VALUES (?, ?)", u.Username, newUsername)
  1800. if err != nil {
  1801. log.Error("Unable to add new collectionredirect: %v", err)
  1802. }
  1803. err = t.Commit()
  1804. if err != nil {
  1805. t.Rollback()
  1806. log.Error("Rolling back after Commit(): %v\n", err)
  1807. return err
  1808. }
  1809. u.Username = newUsername
  1810. }
  1811. // Update passphrase if given
  1812. if s.NewPass != "" {
  1813. // Check if user has already set a password
  1814. var err error
  1815. u.HasPass, err = db.IsUserPassSet(u.ID)
  1816. if err != nil {
  1817. errPass = impart.HTTPError{http.StatusInternalServerError, "Unable to retrieve user data."}
  1818. return errPass
  1819. }
  1820. if u.HasPass {
  1821. // Check if currently-set password is correct
  1822. hashedPass := u.HashedPass
  1823. if len(hashedPass) == 0 {
  1824. authUser, err := db.GetUserForAuthByID(u.ID)
  1825. if err != nil {
  1826. errPass = err
  1827. return errPass
  1828. }
  1829. hashedPass = authUser.HashedPass
  1830. }
  1831. if !auth.Authenticated(hashedPass, []byte(s.OldPass)) {
  1832. errPass = impart.HTTPError{http.StatusUnauthorized, "Incorrect password."}
  1833. return errPass
  1834. }
  1835. }
  1836. hashedPass, err := auth.HashPass([]byte(s.NewPass))
  1837. if err != nil {
  1838. errPass = impart.HTTPError{http.StatusInternalServerError, "Could not create password hash."}
  1839. return errPass
  1840. }
  1841. q.SetBytes(hashedPass, "password")
  1842. }
  1843. // WHERE values
  1844. q.Append(u.ID)
  1845. if q.Updates == "" {
  1846. if s.Username == "" {
  1847. return ErrPostNoUpdatableVals
  1848. }
  1849. // Nothing to update except username. That was successful, so return now.
  1850. return nil
  1851. }
  1852. res, err := db.Exec("UPDATE users SET "+q.Updates+" WHERE id = ?", q.Params...)
  1853. if err != nil {
  1854. log.Error("Unable to update collection: %v", err)
  1855. return err
  1856. }
  1857. rowsAffected, _ := res.RowsAffected()
  1858. if rowsAffected == 0 {
  1859. // Show the correct error message if nothing was updated
  1860. var dummy int
  1861. err := db.QueryRow("SELECT 1 FROM users WHERE id = ?", u.ID).Scan(&dummy)
  1862. switch {
  1863. case err == sql.ErrNoRows:
  1864. return ErrUnauthorizedGeneral
  1865. case err != nil:
  1866. log.Error("Failed selecting from users: %v", err)
  1867. }
  1868. return nil
  1869. }
  1870. if s.NewPass != "" && !u.HasPass {
  1871. u.HasPass = true
  1872. }
  1873. return nil
  1874. }
  1875. func (db *datastore) ChangePassphrase(userID int64, sudo bool, curPass string, hashedPass []byte) error {
  1876. var dbPass []byte
  1877. err := db.QueryRow("SELECT password FROM users WHERE id = ?", userID).Scan(&dbPass)
  1878. switch {
  1879. case err == sql.ErrNoRows:
  1880. return ErrUserNotFound
  1881. case err != nil:
  1882. log.Error("Couldn't SELECT user password for change: %v", err)
  1883. return err
  1884. }
  1885. if !sudo && !auth.Authenticated(dbPass, []byte(curPass)) {
  1886. return impart.HTTPError{http.StatusUnauthorized, "Incorrect password."}
  1887. }
  1888. _, err = db.Exec("UPDATE users SET password = ? WHERE id = ?", hashedPass, userID)
  1889. if err != nil {
  1890. log.Error("Could not update passphrase: %v", err)
  1891. return err
  1892. }
  1893. return nil
  1894. }
  1895. func (db *datastore) RemoveCollectionRedirect(t *sql.Tx, alias string) error {
  1896. _, err := t.Exec("DELETE FROM collectionredirects WHERE prev_alias = ?", alias)
  1897. if err != nil {
  1898. log.Error("Unable to delete from collectionredirects: %v", err)
  1899. return err
  1900. }
  1901. return nil
  1902. }
  1903. func (db *datastore) GetCollectionRedirect(alias string) (new string) {
  1904. row := db.QueryRow("SELECT new_alias FROM collectionredirects WHERE prev_alias = ?", alias)
  1905. err := row.Scan(&new)
  1906. if err != nil && err != sql.ErrNoRows && !db.isIgnorableError(err) {
  1907. log.Error("Failed selecting from collectionredirects: %v", err)
  1908. }
  1909. return
  1910. }
  1911. func (db *datastore) DeleteCollection(alias string, userID int64) error {
  1912. c := &Collection{Alias: alias}
  1913. var username string
  1914. row := db.QueryRow("SELECT username FROM users WHERE id = ?", userID)
  1915. err := row.Scan(&username)
  1916. if err != nil {
  1917. return err
  1918. }
  1919. // Ensure user isn't deleting their main blog
  1920. if alias == username {
  1921. return impart.HTTPError{http.StatusForbidden, "You cannot currently delete your primary blog."}
  1922. }
  1923. row = db.QueryRow("SELECT id FROM collections WHERE alias = ? AND owner_id = ?", alias, userID)
  1924. err = row.Scan(&c.ID)
  1925. switch {
  1926. case err == sql.ErrNoRows:
  1927. return impart.HTTPError{http.StatusNotFound, "Collection doesn't exist or you're not allowed to delete it."}
  1928. case err != nil:
  1929. log.Error("Failed selecting from collections: %v", err)
  1930. return ErrInternalGeneral
  1931. }
  1932. t, err := db.Begin()
  1933. if err != nil {
  1934. return err
  1935. }
  1936. // Float all collection's posts
  1937. _, err = t.Exec("UPDATE posts SET collection_id = NULL WHERE collection_id = ? AND owner_id = ?", c.ID, userID)
  1938. if err != nil {
  1939. t.Rollback()
  1940. return err
  1941. }
  1942. // Remove redirects to or from this collection
  1943. _, err = t.Exec("DELETE FROM collectionredirects WHERE prev_alias = ? OR new_alias = ?", alias, alias)
  1944. if err != nil {
  1945. t.Rollback()
  1946. return err
  1947. }
  1948. // Remove any optional collection password
  1949. _, err = t.Exec("DELETE FROM collectionpasswords WHERE collection_id = ?", c.ID)
  1950. if err != nil {
  1951. t.Rollback()
  1952. return err
  1953. }
  1954. // Finally, delete collection itself
  1955. _, err = t.Exec("DELETE FROM collections WHERE id = ?", c.ID)
  1956. if err != nil {
  1957. t.Rollback()
  1958. return err
  1959. }
  1960. err = t.Commit()
  1961. if err != nil {
  1962. t.Rollback()
  1963. return err
  1964. }
  1965. return nil
  1966. }
  1967. func (db *datastore) IsCollectionAttributeOn(id int64, attr string) bool {
  1968. var v string
  1969. err := db.QueryRow("SELECT value FROM collectionattributes WHERE collection_id = ? AND attribute = ?", id, attr).Scan(&v)
  1970. switch {
  1971. case err == sql.ErrNoRows:
  1972. return false
  1973. case err != nil:
  1974. log.Error("Couldn't SELECT value in isCollectionAttributeOn for attribute '%s': %v", attr, err)
  1975. return false
  1976. }
  1977. return v == "1"
  1978. }
  1979. func (db *datastore) CollectionHasAttribute(id int64, attr string) bool {
  1980. var dummy string
  1981. err := db.QueryRow("SELECT value FROM collectionattributes WHERE collection_id = ? AND attribute = ?", id, attr).Scan(&dummy)
  1982. switch {
  1983. case err == sql.ErrNoRows:
  1984. return false
  1985. case err != nil:
  1986. log.Error("Couldn't SELECT value in collectionHasAttribute for attribute '%s': %v", attr, err)
  1987. return false
  1988. }
  1989. return true
  1990. }
  1991. func (db *datastore) GetCollectionAttribute(id int64, attr string) string {
  1992. var v string
  1993. err := db.QueryRow("SELECT value FROM collectionattributes WHERE collection_id = ? AND attribute = ?", id, attr).Scan(&v)
  1994. switch {
  1995. case err == sql.ErrNoRows:
  1996. return ""
  1997. case err != nil:
  1998. log.Error("Couldn't SELECT value in getCollectionAttribute for attribute '%s': %v", attr, err)
  1999. return ""
  2000. }
  2001. return v
  2002. }
  2003. func (db *datastore) SetCollectionAttribute(id int64, attr, v string) error {
  2004. _, err := db.Exec("INSERT INTO collectionattributes (collection_id, attribute, value) VALUES (?, ?, ?)", id, attr, v)
  2005. if err != nil {
  2006. log.Error("Unable to INSERT into collectionattributes: %v", err)
  2007. return err
  2008. }
  2009. return nil
  2010. }
  2011. // DeleteAccount will delete the entire account for userID
  2012. func (db *datastore) DeleteAccount(userID int64) error {
  2013. // Get all collections
  2014. rows, err := db.Query("SELECT id, alias FROM collections WHERE owner_id = ?", userID)
  2015. if err != nil {
  2016. log.Error("Unable to get collections: %v", err)
  2017. return err
  2018. }
  2019. defer rows.Close()
  2020. colls := []Collection{}
  2021. var c Collection
  2022. for rows.Next() {
  2023. err = rows.Scan(&c.ID, &c.Alias)
  2024. if err != nil {
  2025. log.Error("Unable to scan collection cols: %v", err)
  2026. return err
  2027. }
  2028. colls = append(colls, c)
  2029. }
  2030. // Start transaction
  2031. t, err := db.Begin()
  2032. if err != nil {
  2033. log.Error("Unable to begin: %v", err)
  2034. return err
  2035. }
  2036. // Clean up all collection related information
  2037. var res sql.Result
  2038. for _, c := range colls {
  2039. // Delete tokens
  2040. res, err = t.Exec("DELETE FROM collectionattributes WHERE collection_id = ?", c.ID)
  2041. if err != nil {
  2042. t.Rollback()
  2043. log.Error("Unable to delete attributes on %s: %v", c.Alias, err)
  2044. return err
  2045. }
  2046. rs, _ := res.RowsAffected()
  2047. log.Info("Deleted %d for %s from collectionattributes", rs, c.Alias)
  2048. // Remove any optional collection password
  2049. res, err = t.Exec("DELETE FROM collectionpasswords WHERE collection_id = ?", c.ID)
  2050. if err != nil {
  2051. t.Rollback()
  2052. log.Error("Unable to delete passwords on %s: %v", c.Alias, err)
  2053. return err
  2054. }
  2055. rs, _ = res.RowsAffected()
  2056. log.Info("Deleted %d for %s from collectionpasswords", rs, c.Alias)
  2057. // Remove redirects to this collection
  2058. res, err = t.Exec("DELETE FROM collectionredirects WHERE new_alias = ?", c.Alias)
  2059. if err != nil {
  2060. t.Rollback()
  2061. log.Error("Unable to delete redirects on %s: %v", c.Alias, err)
  2062. return err
  2063. }
  2064. rs, _ = res.RowsAffected()
  2065. log.Info("Deleted %d for %s from collectionredirects", rs, c.Alias)
  2066. // Remove any collection keys
  2067. res, err = t.Exec("DELETE FROM collectionkeys WHERE collection_id = ?", c.ID)
  2068. if err != nil {
  2069. t.Rollback()
  2070. log.Error("Unable to delete keys on %s: %v", c.Alias, err)
  2071. return err
  2072. }
  2073. rs, _ = res.RowsAffected()
  2074. log.Info("Deleted %d for %s from collectionkeys", rs, c.Alias)
  2075. // TODO: federate delete collection
  2076. // Remove remote follows
  2077. res, err = t.Exec("DELETE FROM remotefollows WHERE collection_id = ?", c.ID)
  2078. if err != nil {
  2079. t.Rollback()
  2080. log.Error("Unable to delete remote follows on %s: %v", c.Alias, err)
  2081. return err
  2082. }
  2083. rs, _ = res.RowsAffected()
  2084. log.Info("Deleted %d for %s from remotefollows", rs, c.Alias)
  2085. }
  2086. // Delete collections
  2087. res, err = t.Exec("DELETE FROM collections WHERE owner_id = ?", userID)
  2088. if err != nil {
  2089. t.Rollback()
  2090. log.Error("Unable to delete collections: %v", err)
  2091. return err
  2092. }
  2093. rs, _ := res.RowsAffected()
  2094. log.Info("Deleted %d from collections", rs)
  2095. // Delete tokens
  2096. res, err = t.Exec("DELETE FROM accesstokens WHERE user_id = ?", userID)
  2097. if err != nil {
  2098. t.Rollback()
  2099. log.Error("Unable to delete access tokens: %v", err)
  2100. return err
  2101. }
  2102. rs, _ = res.RowsAffected()
  2103. log.Info("Deleted %d from accesstokens", rs)
  2104. // Delete user attributes
  2105. res, err = t.Exec("DELETE FROM oauth_users WHERE user_id = ?", userID)
  2106. if err != nil {
  2107. t.Rollback()
  2108. log.Error("Unable to delete oauth_users: %v", err)
  2109. return err
  2110. }
  2111. rs, _ = res.RowsAffected()
  2112. log.Info("Deleted %d from oauth_users", rs)
  2113. // Delete posts
  2114. // TODO: should maybe get each row so we can federate a delete
  2115. // if so needs to be outside of transaction like collections
  2116. res, err = t.Exec("DELETE FROM posts WHERE owner_id = ?", userID)
  2117. if err != nil {
  2118. t.Rollback()
  2119. log.Error("Unable to delete posts: %v", err)
  2120. return err
  2121. }
  2122. rs, _ = res.RowsAffected()
  2123. log.Info("Deleted %d from posts", rs)
  2124. // Delete user attributes
  2125. res, err = t.Exec("DELETE FROM userattributes WHERE user_id = ?", userID)
  2126. if err != nil {
  2127. t.Rollback()
  2128. log.Error("Unable to delete attributes: %v", err)
  2129. return err
  2130. }
  2131. rs, _ = res.RowsAffected()
  2132. log.Info("Deleted %d from userattributes", rs)
  2133. // Delete user invites
  2134. res, err = t.Exec("DELETE FROM userinvites WHERE owner_id = ?", userID)
  2135. if err != nil {
  2136. t.Rollback()
  2137. log.Error("Unable to delete invites: %v", err)
  2138. return err
  2139. }
  2140. rs, _ = res.RowsAffected()
  2141. log.Info("Deleted %d from userinvites", rs)
  2142. // Delete the user
  2143. res, err = t.Exec("DELETE FROM users WHERE id = ?", userID)
  2144. if err != nil {
  2145. t.Rollback()
  2146. log.Error("Unable to delete user: %v", err)
  2147. return err
  2148. }
  2149. rs, _ = res.RowsAffected()
  2150. log.Info("Deleted %d from users", rs)
  2151. // Commit all changes to the database
  2152. err = t.Commit()
  2153. if err != nil {
  2154. t.Rollback()
  2155. log.Error("Unable to commit: %v", err)
  2156. return err
  2157. }
  2158. // TODO: federate delete actor
  2159. return nil
  2160. }
  2161. func (db *datastore) GetAPActorKeys(collectionID int64) ([]byte, []byte) {
  2162. var pub, priv []byte
  2163. err := db.QueryRow("SELECT public_key, private_key FROM collectionkeys WHERE collection_id = ?", collectionID).Scan(&pub, &priv)
  2164. switch {
  2165. case err == sql.ErrNoRows:
  2166. // Generate keys
  2167. pub, priv = activitypub.GenerateKeys()
  2168. _, err = db.Exec("INSERT INTO collectionkeys (collection_id, public_key, private_key) VALUES (?, ?, ?)", collectionID, pub, priv)
  2169. if err != nil {
  2170. log.Error("Unable to INSERT new activitypub keypair: %v", err)
  2171. return nil, nil
  2172. }
  2173. case err != nil:
  2174. log.Error("Couldn't SELECT collectionkeys: %v", err)
  2175. return nil, nil
  2176. }
  2177. return pub, priv
  2178. }
  2179. func (db *datastore) CreateUserInvite(id string, userID int64, maxUses int, expires *time.Time) error {
  2180. _, err := db.Exec("INSERT INTO userinvites (id, owner_id, max_uses, created, expires, inactive) VALUES (?, ?, ?, "+db.now()+", ?, 0)", id, userID, maxUses, expires)
  2181. return err
  2182. }
  2183. func (db *datastore) GetUserInvites(userID int64) (*[]Invite, error) {
  2184. rows, err := db.Query("SELECT id, max_uses, created, expires, inactive FROM userinvites WHERE owner_id = ? ORDER BY created DESC", userID)
  2185. if err != nil {
  2186. log.Error("Failed selecting from userinvites: %v", err)
  2187. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user invites."}
  2188. }
  2189. defer rows.Close()
  2190. is := []Invite{}
  2191. for rows.Next() {
  2192. i := Invite{}
  2193. err = rows.Scan(&i.ID, &i.MaxUses, &i.Created, &i.Expires, &i.Inactive)
  2194. is = append(is, i)
  2195. }
  2196. return &is, nil
  2197. }
  2198. func (db *datastore) GetUserInvite(id string) (*Invite, error) {
  2199. var i Invite
  2200. err := db.QueryRow("SELECT id, max_uses, created, expires, inactive FROM userinvites WHERE id = ?", id).Scan(&i.ID, &i.MaxUses, &i.Created, &i.Expires, &i.Inactive)
  2201. switch {
  2202. case err == sql.ErrNoRows, db.isIgnorableError(err):
  2203. return nil, impart.HTTPError{http.StatusNotFound, "Invite doesn't exist."}
  2204. case err != nil:
  2205. log.Error("Failed selecting invite: %v", err)
  2206. return nil, err
  2207. }
  2208. return &i, nil
  2209. }
  2210. // IsUsersInvite returns true if the user with ID created the invite with code
  2211. // and an error other than sql no rows, if any. Will return false in the event
  2212. // of an error.
  2213. func (db *datastore) IsUsersInvite(code string, userID int64) (bool, error) {
  2214. var id string
  2215. err := db.QueryRow("SELECT id FROM userinvites WHERE id = ? AND owner_id = ?", code, userID).Scan(&id)
  2216. if err != nil && err != sql.ErrNoRows {
  2217. log.Error("Failed selecting invite: %v", err)
  2218. return false, err
  2219. }
  2220. return id != "", nil
  2221. }
  2222. func (db *datastore) GetUsersInvitedCount(id string) int64 {
  2223. var count int64
  2224. err := db.QueryRow("SELECT COUNT(*) FROM usersinvited WHERE invite_id = ?", id).Scan(&count)
  2225. switch {
  2226. case err == sql.ErrNoRows:
  2227. return 0
  2228. case err != nil:
  2229. log.Error("Failed selecting users invited count: %v", err)
  2230. return 0
  2231. }
  2232. return count
  2233. }
  2234. func (db *datastore) CreateInvitedUser(inviteID string, userID int64) error {
  2235. _, err := db.Exec("INSERT INTO usersinvited (invite_id, user_id) VALUES (?, ?)", inviteID, userID)
  2236. return err
  2237. }
  2238. func (db *datastore) GetInstancePages() ([]*instanceContent, error) {
  2239. return db.GetAllDynamicContent("page")
  2240. }
  2241. func (db *datastore) GetAllDynamicContent(t string) ([]*instanceContent, error) {
  2242. where := ""
  2243. params := []interface{}{}
  2244. if t != "" {
  2245. where = " WHERE content_type = ?"
  2246. params = append(params, t)
  2247. }
  2248. rows, err := db.Query("SELECT id, title, content, updated, content_type FROM appcontent"+where, params...)
  2249. if err != nil {
  2250. log.Error("Failed selecting from appcontent: %v", err)
  2251. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve instance pages."}
  2252. }
  2253. defer rows.Close()
  2254. pages := []*instanceContent{}
  2255. for rows.Next() {
  2256. c := &instanceContent{}
  2257. err = rows.Scan(&c.ID, &c.Title, &c.Content, &c.Updated, &c.Type)
  2258. if err != nil {
  2259. log.Error("Failed scanning row: %v", err)
  2260. break
  2261. }
  2262. pages = append(pages, c)
  2263. }
  2264. err = rows.Err()
  2265. if err != nil {
  2266. log.Error("Error after Next() on rows: %v", err)
  2267. }
  2268. return pages, nil
  2269. }
  2270. func (db *datastore) GetDynamicContent(id string) (*instanceContent, error) {
  2271. c := &instanceContent{
  2272. ID: id,
  2273. }
  2274. err := db.QueryRow("SELECT title, content, updated, content_type FROM appcontent WHERE id = ?", id).Scan(&c.Title, &c.Content, &c.Updated, &c.Type)
  2275. switch {
  2276. case err == sql.ErrNoRows:
  2277. return nil, nil
  2278. case err != nil:
  2279. log.Error("Couldn't SELECT FROM appcontent for id '%s': %v", id, err)
  2280. return nil, err
  2281. }
  2282. return c, nil
  2283. }
  2284. func (db *datastore) UpdateDynamicContent(id, title, content, contentType string) error {
  2285. var err error
  2286. if db.driverName == driverSQLite {
  2287. _, err = db.Exec("INSERT OR REPLACE INTO appcontent (id, title, content, updated, content_type) VALUES (?, ?, ?, "+db.now()+", ?)", id, title, content, contentType)
  2288. } else {
  2289. _, err = db.Exec("INSERT INTO appcontent (id, title, content, updated, content_type) VALUES (?, ?, ?, "+db.now()+", ?) "+db.upsert("id")+" title = ?, content = ?, updated = "+db.now(), id, title, content, contentType, title, content)
  2290. }
  2291. if err != nil {
  2292. log.Error("Unable to INSERT appcontent for '%s': %v", id, err)
  2293. }
  2294. return err
  2295. }
  2296. func (db *datastore) GetAllUsers(page uint) (*[]User, error) {
  2297. limitStr := fmt.Sprintf("0, %d", adminUsersPerPage)
  2298. if page > 1 {
  2299. limitStr = fmt.Sprintf("%d, %d", (page-1)*adminUsersPerPage, adminUsersPerPage)
  2300. }
  2301. rows, err := db.Query("SELECT id, username, created, status FROM users ORDER BY created DESC LIMIT " + limitStr)
  2302. if err != nil {
  2303. log.Error("Failed selecting from users: %v", err)
  2304. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve all users."}
  2305. }
  2306. defer rows.Close()
  2307. users := []User{}
  2308. for rows.Next() {
  2309. u := User{}
  2310. err = rows.Scan(&u.ID, &u.Username, &u.Created, &u.Status)
  2311. if err != nil {
  2312. log.Error("Failed scanning GetAllUsers() row: %v", err)
  2313. break
  2314. }
  2315. users = append(users, u)
  2316. }
  2317. return &users, nil
  2318. }
  2319. func (db *datastore) GetAllUsersCount() int64 {
  2320. var count int64
  2321. err := db.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
  2322. switch {
  2323. case err == sql.ErrNoRows:
  2324. return 0
  2325. case err != nil:
  2326. log.Error("Failed selecting all users count: %v", err)
  2327. return 0
  2328. }
  2329. return count
  2330. }
  2331. func (db *datastore) GetUserLastPostTime(id int64) (*time.Time, error) {
  2332. var t time.Time
  2333. err := db.QueryRow("SELECT created FROM posts WHERE owner_id = ? ORDER BY created DESC LIMIT 1", id).Scan(&t)
  2334. switch {
  2335. case err == sql.ErrNoRows:
  2336. return nil, nil
  2337. case err != nil:
  2338. log.Error("Failed selecting last post time from posts: %v", err)
  2339. return nil, err
  2340. }
  2341. return &t, nil
  2342. }
  2343. // SetUserStatus changes a user's status in the database. see Users.UserStatus
  2344. func (db *datastore) SetUserStatus(id int64, status UserStatus) error {
  2345. _, err := db.Exec("UPDATE users SET status = ? WHERE id = ?", status, id)
  2346. if err != nil {
  2347. return fmt.Errorf("failed to update user status: %v", err)
  2348. }
  2349. return nil
  2350. }
  2351. func (db *datastore) GetCollectionLastPostTime(id int64) (*time.Time, error) {
  2352. var t time.Time
  2353. err := db.QueryRow("SELECT created FROM posts WHERE collection_id = ? ORDER BY created DESC LIMIT 1", id).Scan(&t)
  2354. switch {
  2355. case err == sql.ErrNoRows:
  2356. return nil, nil
  2357. case err != nil:
  2358. log.Error("Failed selecting last post time from posts: %v", err)
  2359. return nil, err
  2360. }
  2361. return &t, nil
  2362. }
  2363. func (db *datastore) GenerateOAuthState(ctx context.Context, provider string, clientID string, attachUser int64, inviteCode string) (string, error) {
  2364. state := id.Generate62RandomString(24)
  2365. attachUserVal := sql.NullInt64{Valid: attachUser > 0, Int64: attachUser}
  2366. inviteCodeVal := sql.NullString{Valid: inviteCode != "", String: inviteCode}
  2367. _, err := db.ExecContext(ctx, "INSERT INTO oauth_client_states (state, provider, client_id, used, created_at, attach_user_id, invite_code) VALUES (?, ?, ?, FALSE, "+db.now()+", ?, ?)", state, provider, clientID, attachUserVal, inviteCodeVal)
  2368. if err != nil {
  2369. return "", fmt.Errorf("unable to record oauth client state: %w", err)
  2370. }
  2371. return state, nil
  2372. }
  2373. func (db *datastore) ValidateOAuthState(ctx context.Context, state string) (string, string, int64, string, error) {
  2374. var provider string
  2375. var clientID string
  2376. var attachUserID sql.NullInt64
  2377. var inviteCode sql.NullString
  2378. err := wf_db.RunTransactionWithOptions(ctx, db.DB, &sql.TxOptions{}, func(ctx context.Context, tx *sql.Tx) error {
  2379. err := tx.
  2380. QueryRowContext(ctx, "SELECT provider, client_id, attach_user_id, invite_code FROM oauth_client_states WHERE state = ? AND used = FALSE", state).
  2381. Scan(&provider, &clientID, &attachUserID, &inviteCode)
  2382. if err != nil {
  2383. return err
  2384. }
  2385. res, err := tx.ExecContext(ctx, "UPDATE oauth_client_states SET used = TRUE WHERE state = ?", state)
  2386. if err != nil {
  2387. return err
  2388. }
  2389. rowsAffected, err := res.RowsAffected()
  2390. if err != nil {
  2391. return err
  2392. }
  2393. if rowsAffected != 1 {
  2394. return fmt.Errorf("state not found")
  2395. }
  2396. return nil
  2397. })
  2398. if err != nil {
  2399. return "", "", 0, "", nil
  2400. }
  2401. return provider, clientID, attachUserID.Int64, inviteCode.String, nil
  2402. }
  2403. func (db *datastore) RecordRemoteUserID(ctx context.Context, localUserID int64, remoteUserID, provider, clientID, accessToken string) error {
  2404. var err error
  2405. if db.driverName == driverSQLite {
  2406. _, err = db.ExecContext(ctx, "INSERT OR REPLACE INTO oauth_users (user_id, remote_user_id, provider, client_id, access_token) VALUES (?, ?, ?, ?, ?)", localUserID, remoteUserID, provider, clientID, accessToken)
  2407. } else {
  2408. _, err = db.ExecContext(ctx, "INSERT INTO oauth_users (user_id, remote_user_id, provider, client_id, access_token) VALUES (?, ?, ?, ?, ?) "+db.upsert("user")+" access_token = ?", localUserID, remoteUserID, provider, clientID, accessToken, accessToken)
  2409. }
  2410. if err != nil {
  2411. log.Error("Unable to INSERT oauth_users for '%d': %v", localUserID, err)
  2412. }
  2413. return err
  2414. }
  2415. // GetIDForRemoteUser returns a user ID associated with a remote user ID.
  2416. func (db *datastore) GetIDForRemoteUser(ctx context.Context, remoteUserID, provider, clientID string) (int64, error) {
  2417. var userID int64 = -1
  2418. err := db.
  2419. QueryRowContext(ctx, "SELECT user_id FROM oauth_users WHERE remote_user_id = ? AND provider = ? AND client_id = ?", remoteUserID, provider, clientID).
  2420. Scan(&userID)
  2421. // Not finding a record is OK.
  2422. if err != nil && err != sql.ErrNoRows {
  2423. return -1, err
  2424. }
  2425. return userID, nil
  2426. }
  2427. type oauthAccountInfo struct {
  2428. Provider string
  2429. ClientID string
  2430. RemoteUserID string
  2431. DisplayName string
  2432. AllowDisconnect bool
  2433. }
  2434. func (db *datastore) GetOauthAccounts(ctx context.Context, userID int64) ([]oauthAccountInfo, error) {
  2435. rows, err := db.QueryContext(ctx, "SELECT provider, client_id, remote_user_id FROM oauth_users WHERE user_id = ? ", userID)
  2436. if err != nil {
  2437. log.Error("Failed selecting from oauth_users: %v", err)
  2438. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user oauth accounts."}
  2439. }
  2440. defer rows.Close()
  2441. var records []oauthAccountInfo
  2442. for rows.Next() {
  2443. info := oauthAccountInfo{}
  2444. err = rows.Scan(&info.Provider, &info.ClientID, &info.RemoteUserID)
  2445. if err != nil {
  2446. log.Error("Failed scanning GetAllUsers() row: %v", err)
  2447. break
  2448. }
  2449. records = append(records, info)
  2450. }
  2451. return records, nil
  2452. }
  2453. // DatabaseInitialized returns whether or not the current datastore has been
  2454. // initialized with the correct schema.
  2455. // Currently, it checks to see if the `users` table exists.
  2456. func (db *datastore) DatabaseInitialized() bool {
  2457. var dummy string
  2458. var err error
  2459. if db.driverName == driverSQLite {
  2460. err = db.QueryRow("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'users'").Scan(&dummy)
  2461. } else {
  2462. err = db.QueryRow("SHOW TABLES LIKE 'users'").Scan(&dummy)
  2463. }
  2464. switch {
  2465. case err == sql.ErrNoRows:
  2466. return false
  2467. case err != nil:
  2468. log.Error("Couldn't SHOW TABLES: %v", err)
  2469. return false
  2470. }
  2471. return true
  2472. }
  2473. func (db *datastore) RemoveOauth(ctx context.Context, userID int64, provider string, clientID string, remoteUserID string) error {
  2474. _, err := db.ExecContext(ctx, `DELETE FROM oauth_users WHERE user_id = ? AND provider = ? AND client_id = ? AND remote_user_id = ?`, userID, provider, clientID, remoteUserID)
  2475. return err
  2476. }
  2477. func stringLogln(log *string, s string, v ...interface{}) {
  2478. *log += fmt.Sprintf(s+"\n", v...)
  2479. }
  2480. func handleFailedPostInsert(err error) error {
  2481. log.Error("Couldn't insert into posts: %v", err)
  2482. return err
  2483. }
  2484. func (db *datastore) GetProfilePageFromHandle(app *App, handle string) (string, error) {
  2485. handle = strings.TrimLeft(handle, "@")
  2486. actorIRI := ""
  2487. parts := strings.Split(handle, "@")
  2488. if len(parts) != 2 {
  2489. return "", fmt.Errorf("invalid handle format")
  2490. }
  2491. domain := parts[1]
  2492. // Check non-AP instances
  2493. if siloProfileURL := silobridge.Profile(parts[0], domain); siloProfileURL != "" {
  2494. return siloProfileURL, nil
  2495. }
  2496. remoteUser, err := getRemoteUserFromHandle(app, handle)
  2497. if err != nil {
  2498. // can't find using handle in the table but the table may already have this user without
  2499. // handle from a previous version
  2500. // TODO: Make this determination. We should know whether a user exists without a handle, or doesn't exist at all
  2501. actorIRI = RemoteLookup(handle)
  2502. _, errRemoteUser := getRemoteUser(app, actorIRI)
  2503. // if it exists then we need to update the handle
  2504. if errRemoteUser == nil {
  2505. _, err := app.db.Exec("UPDATE remoteusers SET handle = ? WHERE actor_id = ?", handle, actorIRI)
  2506. if err != nil {
  2507. log.Error("Couldn't update handle '%s' for user %s", handle, actorIRI)
  2508. }
  2509. } else {
  2510. // this probably means we don't have the user in the table so let's try to insert it
  2511. // here we need to ask the server for the inboxes
  2512. remoteActor, err := activityserve.NewRemoteActor(actorIRI)
  2513. if err != nil {
  2514. log.Error("Couldn't fetch remote actor: %v", err)
  2515. }
  2516. if debugging {
  2517. log.Info("%s %s %s %s", actorIRI, remoteActor.GetInbox(), remoteActor.GetSharedInbox(), handle)
  2518. }
  2519. _, err = app.db.Exec("INSERT INTO remoteusers (actor_id, inbox, shared_inbox, handle) VALUES(?, ?, ?, ?)", actorIRI, remoteActor.GetInbox(), remoteActor.GetSharedInbox(), handle)
  2520. if err != nil {
  2521. log.Error("Couldn't insert remote user: %v", err)
  2522. return "", err
  2523. }
  2524. }
  2525. } else {
  2526. actorIRI = remoteUser.ActorID
  2527. }
  2528. return actorIRI, nil
  2529. }