Skip to content

Commit 57cad63

Browse files
Gargronhiyuki2578
authored andcommitted
Add timeline read markers API (mastodon#11762)
Fix mastodon#4093
1 parent 9312ef6 commit 57cad63

12 files changed

Lines changed: 219 additions & 2 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# frozen_string_literal: true
2+
3+
class Api::V1::MarkersController < Api::BaseController
4+
before_action -> { doorkeeper_authorize! :read, :'read:statuses' }, only: [:index]
5+
before_action -> { doorkeeper_authorize! :write, :'write:statuses' }, except: [:index]
6+
7+
before_action :require_user!
8+
9+
def index
10+
@markers = current_user.markers.where(timeline: Array(params[:timeline])).each_with_object({}) { |marker, h| h[marker.timeline] = marker }
11+
render json: serialize_map(@markers)
12+
end
13+
14+
def create
15+
Marker.transaction do
16+
@markers = {}
17+
18+
resource_params.each_pair do |timeline, timeline_params|
19+
@markers[timeline] = current_user.markers.find_or_initialize_by(timeline: timeline)
20+
@markers[timeline].update!(timeline_params)
21+
end
22+
end
23+
24+
render json: serialize_map(@markers)
25+
rescue ActiveRecord::StaleObjectError
26+
render json: { error: 'Conflict during update, please try again' }, status: 409
27+
end
28+
29+
private
30+
31+
def serialize_map(map)
32+
serialized = {}
33+
34+
map.each_pair do |key, value|
35+
serialized[key] = ActiveModelSerializers::SerializableResource.new(value, serializer: REST::MarkerSerializer).as_json
36+
end
37+
38+
Oj.dump(serialized)
39+
end
40+
41+
def resource_params
42+
params.slice(*Marker::TIMELINES).permit(*Marker::TIMELINES.map { |timeline| { timeline.to_sym => [:last_read_id] } })
43+
end
44+
end
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
export const submitMarkers = () => (dispatch, getState) => {
2+
const accessToken = getState().getIn(['meta', 'access_token'], '');
3+
const params = {};
4+
5+
const lastHomeId = getState().getIn(['timelines', 'home', 'items', 0]);
6+
const lastNotificationId = getState().getIn(['notifications', 'items', 0, 'id']);
7+
8+
if (lastHomeId) {
9+
params.home = {
10+
last_read_id: lastHomeId,
11+
};
12+
}
13+
14+
if (lastNotificationId) {
15+
params.notifications = {
16+
last_read_id: lastNotificationId,
17+
};
18+
}
19+
20+
if (Object.keys(params).length === 0) {
21+
return;
22+
}
23+
24+
const client = new XMLHttpRequest();
25+
26+
client.open('POST', '/api/v1/markers', false);
27+
client.setRequestHeader('Content-Type', 'application/json');
28+
client.setRequestHeader('Authorization', `Bearer ${accessToken}`);
29+
client.send(JSON.stringify(params));
30+
};

app/javascript/mastodon/features/ui/index.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { expandNotifications } from '../../actions/notifications';
1616
import { fetchFilters } from '../../actions/filters';
1717
import { clearHeight } from '../../actions/height_cache';
1818
import { focusApp, unfocusApp } from 'mastodon/actions/app';
19+
import { submitMarkers } from 'mastodon/actions/markers';
1920
import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers';
2021
import UploadArea from './components/upload_area';
2122
import ColumnsAreaContainer from './containers/columns_area_container';
@@ -241,7 +242,9 @@ class UI extends React.PureComponent {
241242
};
242243

243244
handleBeforeUnload = e => {
244-
const { intl, isComposing, hasComposingText, hasMediaAttachments } = this.props;
245+
const { intl, dispatch, isComposing, hasComposingText, hasMediaAttachments } = this.props;
246+
247+
dispatch(submitMarkers());
245248

246249
if (isComposing && (hasComposingText || hasMediaAttachments)) {
247250
// Setting returnValue to any string causes confirmation dialog.

app/models/marker.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# frozen_string_literal: true
2+
3+
# == Schema Information
4+
#
5+
# Table name: markers
6+
#
7+
# id :bigint(8) not null, primary key
8+
# user_id :bigint(8)
9+
# timeline :string default(""), not null
10+
# last_read_id :bigint(8) default(0), not null
11+
# lock_version :integer default(0), not null
12+
# created_at :datetime not null
13+
# updated_at :datetime not null
14+
#
15+
16+
class Marker < ApplicationRecord
17+
TIMELINES = %w(home notifications).freeze
18+
19+
belongs_to :user
20+
21+
validates :timeline, :last_read_id, presence: true
22+
validates :timeline, inclusion: { in: TIMELINES }
23+
end

app/models/user.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ class User < ApplicationRecord
7474
has_many :applications, class_name: 'Doorkeeper::Application', as: :owner
7575
has_many :backups, inverse_of: :user
7676
has_many :invites, inverse_of: :user
77+
has_many :markers, inverse_of: :user, dependent: :destroy
7778

7879
has_one :invite_request, class_name: 'UserInviteRequest', inverse_of: :user, dependent: :destroy
7980
accepts_nested_attributes_for :invite_request, reject_if: ->(attributes) { attributes['text'].blank? }
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# frozen_string_literal: true
2+
3+
class REST::MarkerSerializer < ActiveModel::Serializer
4+
attributes :last_read_id, :version, :updated_at
5+
6+
def last_read_id
7+
object.last_read_id.to_s
8+
end
9+
10+
def version
11+
object.lock_version
12+
end
13+
end

config/routes.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,7 @@
314314
resources :trends, only: [:index]
315315
resources :filters, only: [:index, :create, :show, :update, :destroy]
316316
resources :endorsements, only: [:index]
317+
resources :markers, only: [:index, :create]
317318

318319
namespace :apps do
319320
get :verify_credentials, to: 'credentials#show'
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class CreateMarkers < ActiveRecord::Migration[5.2]
2+
def change
3+
create_table :markers do |t|
4+
t.references :user, foreign_key: { on_delete: :cascade, index: false }
5+
t.string :timeline, default: '', null: false
6+
t.bigint :last_read_id, default: 0, null: false
7+
t.integer :lock_version, default: 0, null: false
8+
9+
t.timestamps
10+
end
11+
12+
add_index :markers, [:user_id, :timeline], unique: true
13+
end
14+
end

db/schema.rb

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
#
1111
# It's strongly recommended that you check this file into your version control system.
1212

13-
ActiveRecord::Schema.define(version: 2019_09_01_040524) do
13+
ActiveRecord::Schema.define(version: 2019_09_04_222339) do
1414

1515
# These are extensions that must be enabled in order to support this database
1616
enable_extension "plpgsql"
@@ -367,6 +367,17 @@
367367
t.index ["account_id"], name: "index_lists_on_account_id"
368368
end
369369

370+
create_table "markers", force: :cascade do |t|
371+
t.bigint "user_id"
372+
t.string "timeline", default: "", null: false
373+
t.bigint "last_read_id", default: 0, null: false
374+
t.integer "lock_version", default: 0, null: false
375+
t.datetime "created_at", null: false
376+
t.datetime "updated_at", null: false
377+
t.index ["user_id", "timeline"], name: "index_markers_on_user_id_and_timeline", unique: true
378+
t.index ["user_id"], name: "index_markers_on_user_id"
379+
end
380+
370381
create_table "media_attachments", force: :cascade do |t|
371382
t.bigint "status_id"
372383
t.string "file_file_name"
@@ -792,6 +803,7 @@
792803
add_foreign_key "list_accounts", "follows", on_delete: :cascade
793804
add_foreign_key "list_accounts", "lists", on_delete: :cascade
794805
add_foreign_key "lists", "accounts", on_delete: :cascade
806+
add_foreign_key "markers", "users", on_delete: :cascade
795807
add_foreign_key "media_attachments", "accounts", name: "fk_96dd81e81b", on_delete: :nullify
796808
add_foreign_key "media_attachments", "scheduled_statuses", on_delete: :nullify
797809
add_foreign_key "media_attachments", "statuses", on_delete: :nullify
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
require 'rails_helper'
2+
3+
RSpec.describe Api::V1::MarkersController, type: :controller do
4+
render_views
5+
6+
let!(:user) { Fabricate(:user, account: Fabricate(:account, username: 'alice')) }
7+
let!(:token) { Fabricate(:accessible_access_token, resource_owner_id: user.id, scopes: 'read:statuses write:statuses') }
8+
9+
before { allow(controller).to receive(:doorkeeper_token) { token } }
10+
11+
describe 'GET #index' do
12+
before do
13+
Fabricate(:marker, timeline: 'home', last_read_id: 123, user: user)
14+
Fabricate(:marker, timeline: 'notifications', last_read_id: 456, user: user)
15+
16+
get :index, params: { timeline: %w(home notifications) }
17+
end
18+
19+
it 'returns http success' do
20+
expect(response).to have_http_status(200)
21+
end
22+
23+
it 'returns markers' do
24+
json = body_as_json
25+
26+
expect(json.key?(:home)).to be true
27+
expect(json[:home][:last_read_id]).to eq '123'
28+
expect(json.key?(:notifications)).to be true
29+
expect(json[:notifications][:last_read_id]).to eq '456'
30+
end
31+
end
32+
33+
describe 'POST #create' do
34+
context 'when no marker exists' do
35+
before do
36+
post :create, params: { home: { last_read_id: '69420' } }
37+
end
38+
39+
it 'returns http success' do
40+
expect(response).to have_http_status(200)
41+
end
42+
43+
it 'creates a marker' do
44+
expect(user.markers.first.timeline).to eq 'home'
45+
expect(user.markers.first.last_read_id).to eq 69420
46+
end
47+
end
48+
49+
context 'when a marker exists' do
50+
before do
51+
post :create, params: { home: { last_read_id: '69420' } }
52+
post :create, params: { home: { last_read_id: '70120' } }
53+
end
54+
55+
it 'returns http success' do
56+
expect(response).to have_http_status(200)
57+
end
58+
59+
it 'updates a marker' do
60+
expect(user.markers.first.timeline).to eq 'home'
61+
expect(user.markers.first.last_read_id).to eq 70120
62+
end
63+
end
64+
end
65+
end

0 commit comments

Comments
 (0)