A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

2728 lines
83 KiB

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