Ghost-Admin/app/models/post.js

200 lines
6.2 KiB
JavaScript
Raw Normal View History

/* eslint-disable camelcase */
2015-02-13 05:22:32 +01:00
import Ember from 'ember';
import computed, {equal, filterBy} from 'ember-computed';
import injectService from 'ember-service/inject';
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import {belongsTo, hasMany} from 'ember-data/relationships';
import ValidationEngine from 'ghost-admin/mixins/validation-engine';
import {BLANK_DOC} from 'ghost-admin/components/ghost-editor'; // a blank mobile doc
// ember-cli-shims doesn't export these so we must get them manually
const {Comparable, compare} = Ember;
function statusCompare(postA, postB) {
let status1 = postA.get('status');
let status2 = postB.get('status');
// if any of those is empty
if (!status1 && !status2) {
return 0;
}
if (!status1 && status2) {
return -1;
}
if (!status2 && status1) {
return 1;
}
// We have to make sure, that scheduled posts will be listed first
// after that, draft and published will be sorted alphabetically and don't need
// any manual comparison.
if (status1 === 'scheduled' && (status2 === 'draft' || status2 === 'published')) {
return -1;
}
if (status2 === 'scheduled' && (status1 === 'draft' || status1 === 'published')) {
return 1;
}
return compare(status1.valueOf(), status2.valueOf());
}
function publishedAtCompare(postA, postB) {
let published1 = postA.get('publishedAtUTC');
let published2 = postB.get('publishedAtUTC');
if (!published1 && !published2) {
return 0;
}
if (!published1 && published2) {
return -1;
}
if (!published2 && published1) {
return 1;
}
return compare(published1.valueOf(), published2.valueOf());
}
export default Model.extend(Comparable, ValidationEngine, {
validationType: 'post',
uuid: attr('string'),
title: attr('string', {defaultValue: ''}),
slug: attr('string'),
markdown: attr('string', {defaultValue: ''}),
mobiledoc: attr('json-string', {defaultValue: BLANK_DOC}),
html: attr('string'),
image: attr('string'),
featured: attr('boolean', {defaultValue: false}),
page: attr('boolean', {defaultValue: false}),
status: attr('string', {defaultValue: 'draft'}),
language: attr('string', {defaultValue: 'en_US'}),
metaTitle: attr('string'),
metaDescription: attr('string'),
author: belongsTo('user', {async: true}),
authorId: attr('string'),
updatedAtUTC: attr('moment-utc'),
updatedBy: attr(),
publishedAtUTC: attr('moment-utc'),
publishedBy: belongsTo('user', {async: true}),
createdAtUTC: attr('moment-utc'),
createdBy: attr(),
tags: hasMany('tag', {
embedded: 'always',
async: false
}),
url: attr('string'),
config: injectService(),
ghostPaths: injectService(),
timeZone: injectService(),
clock: injectService(),
absoluteUrl: computed('url', 'ghostPaths.url', 'config.blogUrl', function () {
let blogUrl = this.get('config.blogUrl');
let postUrl = this.get('url');
return this.get('ghostPaths.url').join(blogUrl, postUrl);
}),
previewUrl: computed('uuid', 'ghostPaths.url', 'config.blogUrl', 'config.routeKeywords.preview', function () {
let blogUrl = this.get('config.blogUrl');
let uuid = this.get('uuid');
let previewKeyword = this.get('config.routeKeywords.preview');
// New posts don't have a preview
if (!uuid) {
return '';
}
return this.get('ghostPaths.url').join(blogUrl, previewKeyword, uuid);
}),
scratch: null,
titleScratch: null,
// Computed post properties
isPublished: equal('status', 'published'),
isDraft: equal('status', 'draft'),
internalTags: filterBy('tags', 'isInternal', true),
Scheduler UI refs TryGhost/Ghost#6413 and TryGhost/Ghost#6870 needs TryGhost/Ghost#6861 - **Post Settings Menu (PSM)**:'Publish Date' input accepts a date from now, min. 2 minutes to allow scheduler processing on the server. Also, there will always be some delay between typing the date and clicking on the 'Schedule Post' button. If the user types a future date for an already published post, the date will be reseted and he sees the message, that the post needs to be unpublished first. Once, the date is accepted, the label will change to 'Scheduled Date'. - adds a CP 'timeScheduled' to post model, which will return `true` if the publish time is currently in the future. - **Changes to the button flow in editor**: - if the the CP `timeScheduled` returns true, a different drop-down-menu will be shown: 'Schedule Post' replaces 'Publish Now' and 'Unschedule' replaces 'Unpublish'. - Covering the _edge cases_, especially when a scheduled post is about to be published, while the user is in the editor. - First, a new CP `scheduleCountdown` will return the remaining time, when the estimated publish time is 15 minutes from now. A notification with this live-ticker is shown next to the save button. Once, we reach a 2 minutes limit, another CP `statusFreeze` will return true and causes the save button to only show `Unschedule` in a red state, until we reach the publish time - Once the publish time is reached, a CP `scheduledWillPublish` causes the buttons and the existing code to pretend we're already dealing with a publish post. At the moment, there's no way to make a background-fetch of the now serverside-scheduled post model from the server, so Ember doesn't know about the changed state at that time. - Changes in the editor, which are done during this 'status freeze'-process will be saved back correctly, once the user hits 'Update Post' after the buttons changed back. A click on 'Unpublish' will change the status back to a draft. - The user will get a regular 'toaster' notification that the post has been published. - adds CP `isScheduled` for scheduled posts - adds CP `offset` to component `gh-posts-list-item` and helper `gh-format-time-scheduled` to show schedule date in content overview. - sets timeout in `gh-spin-button` to 10ms for `Ember.testing` - changes error message in `gh-editor-base-controller` to be in one line, seperated with a `:` TODOs: - [x] new sort order for posts (1. scheduled, 2. draft, 3. published) (refs TryGhost/Ghost#6932) - [ ] Move posts sorting from posts controller to model and refactor to use `Ember.comparable` mixin - [x] Flows for draft -> scheduled -> published like described in TryGhost/Ghost#6870 incl. edge cases and button behaviour - [x] Tests - [x] new PSM behaviour for time/date in future - [x] display publishedAt date with timezone offset on posts overview
2016-02-02 08:04:40 +01:00
isScheduled: equal('status', 'scheduled'),
// TODO: move this into gh-posts-list-item component
// Checks every second, if we reached the scheduled date
timeScheduled: computed('publishedAtUTC', 'clock.second', function () {
let publishedAtUTC = this.get('publishedAtUTC') || moment.utc(new Date());
Scheduler UI refs TryGhost/Ghost#6413 and TryGhost/Ghost#6870 needs TryGhost/Ghost#6861 - **Post Settings Menu (PSM)**:'Publish Date' input accepts a date from now, min. 2 minutes to allow scheduler processing on the server. Also, there will always be some delay between typing the date and clicking on the 'Schedule Post' button. If the user types a future date for an already published post, the date will be reseted and he sees the message, that the post needs to be unpublished first. Once, the date is accepted, the label will change to 'Scheduled Date'. - adds a CP 'timeScheduled' to post model, which will return `true` if the publish time is currently in the future. - **Changes to the button flow in editor**: - if the the CP `timeScheduled` returns true, a different drop-down-menu will be shown: 'Schedule Post' replaces 'Publish Now' and 'Unschedule' replaces 'Unpublish'. - Covering the _edge cases_, especially when a scheduled post is about to be published, while the user is in the editor. - First, a new CP `scheduleCountdown` will return the remaining time, when the estimated publish time is 15 minutes from now. A notification with this live-ticker is shown next to the save button. Once, we reach a 2 minutes limit, another CP `statusFreeze` will return true and causes the save button to only show `Unschedule` in a red state, until we reach the publish time - Once the publish time is reached, a CP `scheduledWillPublish` causes the buttons and the existing code to pretend we're already dealing with a publish post. At the moment, there's no way to make a background-fetch of the now serverside-scheduled post model from the server, so Ember doesn't know about the changed state at that time. - Changes in the editor, which are done during this 'status freeze'-process will be saved back correctly, once the user hits 'Update Post' after the buttons changed back. A click on 'Unpublish' will change the status back to a draft. - The user will get a regular 'toaster' notification that the post has been published. - adds CP `isScheduled` for scheduled posts - adds CP `offset` to component `gh-posts-list-item` and helper `gh-format-time-scheduled` to show schedule date in content overview. - sets timeout in `gh-spin-button` to 10ms for `Ember.testing` - changes error message in `gh-editor-base-controller` to be in one line, seperated with a `:` TODOs: - [x] new sort order for posts (1. scheduled, 2. draft, 3. published) (refs TryGhost/Ghost#6932) - [ ] Move posts sorting from posts controller to model and refactor to use `Ember.comparable` mixin - [x] Flows for draft -> scheduled -> published like described in TryGhost/Ghost#6870 incl. edge cases and button behaviour - [x] Tests - [x] new PSM behaviour for time/date in future - [x] display publishedAt date with timezone offset on posts overview
2016-02-02 08:04:40 +01:00
this.get('clock.second');
return publishedAtUTC.diff(moment.utc(new Date()), 'hours', true) > 0 ? true : false;
Scheduler UI refs TryGhost/Ghost#6413 and TryGhost/Ghost#6870 needs TryGhost/Ghost#6861 - **Post Settings Menu (PSM)**:'Publish Date' input accepts a date from now, min. 2 minutes to allow scheduler processing on the server. Also, there will always be some delay between typing the date and clicking on the 'Schedule Post' button. If the user types a future date for an already published post, the date will be reseted and he sees the message, that the post needs to be unpublished first. Once, the date is accepted, the label will change to 'Scheduled Date'. - adds a CP 'timeScheduled' to post model, which will return `true` if the publish time is currently in the future. - **Changes to the button flow in editor**: - if the the CP `timeScheduled` returns true, a different drop-down-menu will be shown: 'Schedule Post' replaces 'Publish Now' and 'Unschedule' replaces 'Unpublish'. - Covering the _edge cases_, especially when a scheduled post is about to be published, while the user is in the editor. - First, a new CP `scheduleCountdown` will return the remaining time, when the estimated publish time is 15 minutes from now. A notification with this live-ticker is shown next to the save button. Once, we reach a 2 minutes limit, another CP `statusFreeze` will return true and causes the save button to only show `Unschedule` in a red state, until we reach the publish time - Once the publish time is reached, a CP `scheduledWillPublish` causes the buttons and the existing code to pretend we're already dealing with a publish post. At the moment, there's no way to make a background-fetch of the now serverside-scheduled post model from the server, so Ember doesn't know about the changed state at that time. - Changes in the editor, which are done during this 'status freeze'-process will be saved back correctly, once the user hits 'Update Post' after the buttons changed back. A click on 'Unpublish' will change the status back to a draft. - The user will get a regular 'toaster' notification that the post has been published. - adds CP `isScheduled` for scheduled posts - adds CP `offset` to component `gh-posts-list-item` and helper `gh-format-time-scheduled` to show schedule date in content overview. - sets timeout in `gh-spin-button` to 10ms for `Ember.testing` - changes error message in `gh-editor-base-controller` to be in one line, seperated with a `:` TODOs: - [x] new sort order for posts (1. scheduled, 2. draft, 3. published) (refs TryGhost/Ghost#6932) - [ ] Move posts sorting from posts controller to model and refactor to use `Ember.comparable` mixin - [x] Flows for draft -> scheduled -> published like described in TryGhost/Ghost#6870 incl. edge cases and button behaviour - [x] Tests - [x] new PSM behaviour for time/date in future - [x] display publishedAt date with timezone offset on posts overview
2016-02-02 08:04:40 +01:00
}),
// remove client-generated tags, which have `id: null`.
// Ember Data won't recognize/update them automatically
// when returned from the server with ids.
// https://github.com/emberjs/data/issues/1829
updateTags() {
let tags = this.get('tags');
let oldTags = tags.filterBy('id', null);
tags.removeObjects(oldTags);
oldTags.invoke('deleteRecord');
},
isAuthoredByUser(user) {
return user.get('id') === this.get('authorId');
},
// a custom sort function is needed in order to sort the posts list the same way the server would:
// status: scheduled, draft, published
// publishedAt: DESC
// updatedAt: DESC
// id: DESC
compare(postA, postB) {
let updated1 = postA.get('updatedAtUTC');
let updated2 = postB.get('updatedAtUTC');
let idResult,
publishedAtResult,
statusResult,
updatedAtResult;
// when `updatedAt` is undefined, the model is still
// being written to with the results from the server
if (postA.get('isNew') || !updated1) {
return -1;
}
if (postB.get('isNew') || !updated2) {
return 1;
}
// TODO: revisit the ID sorting because we no longer have auto-incrementing IDs
idResult = compare(postA.get('id'), postB.get('id'));
statusResult = statusCompare(postA, postB);
updatedAtResult = compare(updated1.valueOf(), updated2.valueOf());
publishedAtResult = publishedAtCompare(postA, postB);
if (statusResult === 0) {
if (publishedAtResult === 0) {
if (updatedAtResult === 0) {
// This should be DESC
return idResult * -1;
}
// This should be DESC
return updatedAtResult * -1;
}
// This should be DESC
return publishedAtResult * -1;
}
return statusResult;
}
});