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.
 
 
 
 
 

3266 regels
100 KiB

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