REFACTOR: Remove Discourse.Ajax

This commit is contained in:
Robin Ward 2016-06-30 13:55:44 -04:00
parent 56f07529bb
commit b8125b3512
111 changed files with 567 additions and 549 deletions

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
export default Ember.Component.extend({ export default Ember.Component.extend({
classNames: ["ip-lookup"], classNames: ["ip-lookup"],
@ -23,7 +24,7 @@ export default Ember.Component.extend({
this.set("show", true); this.set("show", true);
if (!this.get("location")) { if (!this.get("location")) {
Discourse.ajax("/admin/users/ip-info", { ajax("/admin/users/ip-info", {
data: { ip: this.get("ip") } data: { ip: this.get("ip") }
}).then(function (location) { }).then(function (location) {
self.set("location", Em.Object.create(location)); self.set("location", Em.Object.create(location));
@ -39,7 +40,7 @@ export default Ember.Component.extend({
"order": "trust_level DESC" "order": "trust_level DESC"
}; };
Discourse.ajax("/admin/users/total-others-with-same-ip", { data }).then(function (result) { ajax("/admin/users/total-others-with-same-ip", { data }).then(function (result) {
self.set("totalOthersWithSameIP", result.total); self.set("totalOthersWithSameIP", result.total);
}); });
@ -67,7 +68,7 @@ export default Ember.Component.extend({
totalOthersWithSameIP: null totalOthersWithSameIP: null
}); });
Discourse.ajax("/admin/users/delete-others-with-same-ip.json", { ajax("/admin/users/delete-others-with-same-ip.json", {
type: "DELETE", type: "DELETE",
data: { data: {
"ip": self.get("ip"), "ip": self.get("ip"),

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
export default Ember.ArrayController.extend({ export default Ember.ArrayController.extend({
needs: ["adminBackups"], needs: ["adminBackups"],
status: Ember.computed.alias("controllers.adminBackups"), status: Ember.computed.alias("controllers.adminBackups"),
@ -39,7 +40,7 @@ export default Ember.ArrayController.extend({
_toggleReadOnlyMode(enable) { _toggleReadOnlyMode(enable) {
var site = this.site; var site = this.site;
Discourse.ajax("/admin/backups/readonly", { ajax("/admin/backups/readonly", {
type: "PUT", type: "PUT",
data: { enable: enable } data: { enable: enable }
}).then(function() { }).then(function() {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
export default Ember.Controller.extend({ export default Ember.Controller.extend({
/** /**
@ -29,7 +30,7 @@ export default Ember.Controller.extend({
}); });
var self = this; var self = this;
Discourse.ajax("/admin/email/test", { ajax("/admin/email/test", {
type: 'POST', type: 'POST',
data: { email_address: this.get('testEmailAddress') } data: { email_address: this.get('testEmailAddress') }
}).then(function () { }).then(function () {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
export default Ember.ArrayController.extend({ export default Ember.ArrayController.extend({
sortProperties: ["name"], sortProperties: ["name"],
@ -15,7 +16,7 @@ export default Ember.ArrayController.extend({
I18n.t("yes_value"), I18n.t("yes_value"),
function(destroy) { function(destroy) {
if (destroy) { if (destroy) {
return Discourse.ajax("/admin/customize/emojis/" + emoji.get("name"), { type: "DELETE" }).then(function() { return ajax("/admin/customize/emojis/" + emoji.get("name"), { type: "DELETE" }).then(function() {
self.removeObject(emoji); self.removeObject(emoji);
}); });
} }

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import computed from 'ember-addons/ember-computed-decorators'; import computed from 'ember-addons/ember-computed-decorators';
import { popupAjaxError } from 'discourse/lib/ajax-error'; import { popupAjaxError } from 'discourse/lib/ajax-error';
@ -20,7 +21,7 @@ export default Ember.Controller.extend({
.reject(x => x.length === 0); .reject(x => x.length === 0);
this.set('saving', true); this.set('saving', true);
Discourse.ajax('/admin/groups/bulk', { ajax('/admin/groups/bulk', {
data: { users, group_id: this.get('groupId') }, data: { users, group_id: this.get('groupId') },
method: 'PUT' method: 'PUT'
}).then(() => { }).then(() => {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
export default Ember.ArrayController.extend({ export default Ember.ArrayController.extend({
sortProperties: ['name'], sortProperties: ['name'],
refreshingAutoGroups: false, refreshingAutoGroups: false,
@ -9,7 +10,7 @@ export default Ember.ArrayController.extend({
refreshAutoGroups: function(){ refreshAutoGroups: function(){
var self = this; var self = this;
this.set('refreshingAutoGroups', true); this.set('refreshingAutoGroups', true);
Discourse.ajax('/admin/groups/refresh_automatic_groups', {type: 'POST'}).then(function() { ajax('/admin/groups/refresh_automatic_groups', {type: 'POST'}).then(function() {
self.transitionToRoute("adminGroupsType", "automatic").then(function() { self.transitionToRoute("adminGroupsType", "automatic").then(function() {
self.set('refreshingAutoGroups', false); self.set('refreshingAutoGroups', false);
}); });

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import CanCheckEmails from 'discourse/mixins/can-check-emails'; import CanCheckEmails from 'discourse/mixins/can-check-emails';
import { propertyNotEqual, setting } from 'discourse/lib/computed'; import { propertyNotEqual, setting } from 'discourse/lib/computed';
@ -38,7 +39,7 @@ export default Ember.Controller.extend(CanCheckEmails, {
saveTitle() { saveTitle() {
const self = this; const self = this;
return Discourse.ajax("/users/" + this.get('model.username').toLowerCase(), { return ajax("/users/" + this.get('model.username').toLowerCase(), {
data: {title: this.get('userTitleValue')}, data: {title: this.get('userTitleValue')},
type: 'PUT' type: 'PUT'
}).catch(function(e) { }).catch(function(e) {
@ -68,7 +69,7 @@ export default Ember.Controller.extend(CanCheckEmails, {
savePrimaryGroup() { savePrimaryGroup() {
const self = this; const self = this;
return Discourse.ajax("/admin/users/" + this.get('model.id') + "/primary_group", { return ajax("/admin/users/" + this.get('model.id') + "/primary_group", {
type: 'PUT', type: 'PUT',
data: {primary_group_id: this.get('model.primary_group_id')} data: {primary_group_id: this.get('model.primary_group_id')}
}).then(function () { }).then(function () {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
export default Ember.Controller.extend({ export default Ember.Controller.extend({
needs: ['modal'], needs: ['modal'],
@ -57,7 +58,7 @@ export default Ember.Controller.extend({
const groupIds = items.map(function(i){return i.get("id") || -1;}); const groupIds = items.map(function(i){return i.get("id") || -1;});
const names = items.map(function(i){return i.get("name");}); const names = items.map(function(i){return i.get("name");});
Discourse.ajax('/admin/badges/badge_groupings',{ ajax('/admin/badges/badge_groupings',{
data: {ids: groupIds, names: names}, data: {ids: groupIds, names: names},
method: 'POST' method: 'POST'
}).then(function(data){ }).then(function(data){

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
const AdminDashboard = Discourse.Model.extend({}); const AdminDashboard = Discourse.Model.extend({});
@ -11,7 +12,7 @@ AdminDashboard.reopenClass({
@return {jqXHR} a jQuery Promise object @return {jqXHR} a jQuery Promise object
**/ **/
find: function() { find: function() {
return Discourse.ajax("/admin/dashboard.json").then(function(json) { return ajax("/admin/dashboard.json").then(function(json) {
var model = AdminDashboard.create(json); var model = AdminDashboard.create(json);
model.set('loaded', true); model.set('loaded', true);
return model; return model;
@ -26,7 +27,7 @@ AdminDashboard.reopenClass({
@return {jqXHR} a jQuery Promise object @return {jqXHR} a jQuery Promise object
**/ **/
fetchProblems: function() { fetchProblems: function() {
return Discourse.ajax("/admin/dashboard/problems.json", { return ajax("/admin/dashboard/problems.json", {
type: 'GET', type: 'GET',
dataType: 'json' dataType: 'json'
}).then(function(json) { }).then(function(json) {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import computed from 'ember-addons/ember-computed-decorators'; import computed from 'ember-addons/ember-computed-decorators';
import { propertyNotEqual } from 'discourse/lib/computed'; import { propertyNotEqual } from 'discourse/lib/computed';
import { popupAjaxError } from 'discourse/lib/ajax-error'; import { popupAjaxError } from 'discourse/lib/ajax-error';
@ -40,7 +41,7 @@ const AdminUser = Discourse.User.extend({
canResetBounceScore: Ember.computed.gt("bounce_score", 0), canResetBounceScore: Ember.computed.gt("bounce_score", 0),
resetBounceScore() { resetBounceScore() {
return Discourse.ajax(`/admin/users/${this.get("id")}/reset_bounce_score`, { return ajax(`/admin/users/${this.get("id")}/reset_bounce_score`, {
type: 'POST' type: 'POST'
}).then(() => this.setProperties({ }).then(() => this.setProperties({
"bounce_score": 0, "bounce_score": 0,
@ -50,7 +51,7 @@ const AdminUser = Discourse.User.extend({
generateApiKey() { generateApiKey() {
const self = this; const self = this;
return Discourse.ajax("/admin/users/" + this.get('id') + "/generate_api_key", { return ajax("/admin/users/" + this.get('id') + "/generate_api_key", {
type: 'POST' type: 'POST'
}).then(function (result) { }).then(function (result) {
const apiKey = ApiKey.create(result.api_key); const apiKey = ApiKey.create(result.api_key);
@ -60,20 +61,20 @@ const AdminUser = Discourse.User.extend({
}, },
groupAdded(added) { groupAdded(added) {
return Discourse.ajax("/admin/users/" + this.get('id') + "/groups", { return ajax("/admin/users/" + this.get('id') + "/groups", {
type: 'POST', type: 'POST',
data: { group_id: added.id } data: { group_id: added.id }
}).then(() => this.get('groups').pushObject(added)); }).then(() => this.get('groups').pushObject(added));
}, },
groupRemoved(groupId) { groupRemoved(groupId) {
return Discourse.ajax("/admin/users/" + this.get('id') + "/groups/" + groupId, { return ajax("/admin/users/" + this.get('id') + "/groups/" + groupId, {
type: 'DELETE' type: 'DELETE'
}).then(() => this.set('groups.[]', this.get('groups').rejectBy("id", groupId))); }).then(() => this.set('groups.[]', this.get('groups').rejectBy("id", groupId)));
}, },
revokeApiKey() { revokeApiKey() {
return Discourse.ajax("/admin/users/" + this.get('id') + "/revoke_api_key", { return ajax("/admin/users/" + this.get('id') + "/revoke_api_key", {
type: 'DELETE' type: 'DELETE'
}).then(() => this.set('api_key', null)); }).then(() => this.set('api_key', null));
}, },
@ -104,7 +105,7 @@ const AdminUser = Discourse.User.extend({
"label": '<i class="fa fa-exclamation-triangle"></i> ' + I18n.t("admin.user.delete_all_posts"), "label": '<i class="fa fa-exclamation-triangle"></i> ' + I18n.t("admin.user.delete_all_posts"),
"class": "btn btn-danger", "class": "btn btn-danger",
"callback": function() { "callback": function() {
Discourse.ajax("/admin/users/" + user.get('id') + "/delete_all_posts", { ajax("/admin/users/" + user.get('id') + "/delete_all_posts", {
type: 'PUT' type: 'PUT'
}).then(() => user.set('post_count', 0)); }).then(() => user.set('post_count', 0));
} }
@ -114,7 +115,7 @@ const AdminUser = Discourse.User.extend({
revokeAdmin() { revokeAdmin() {
const self = this; const self = this;
return Discourse.ajax("/admin/users/" + this.get('id') + "/revoke_admin", { return ajax("/admin/users/" + this.get('id') + "/revoke_admin", {
type: 'PUT' type: 'PUT'
}).then(function() { }).then(function() {
self.setProperties({ self.setProperties({
@ -127,7 +128,7 @@ const AdminUser = Discourse.User.extend({
grantAdmin() { grantAdmin() {
const self = this; const self = this;
return Discourse.ajax("/admin/users/" + this.get('id') + "/grant_admin", { return ajax("/admin/users/" + this.get('id') + "/grant_admin", {
type: 'PUT' type: 'PUT'
}).then(function() { }).then(function() {
self.setProperties({ self.setProperties({
@ -140,7 +141,7 @@ const AdminUser = Discourse.User.extend({
revokeModeration() { revokeModeration() {
const self = this; const self = this;
return Discourse.ajax("/admin/users/" + this.get('id') + "/revoke_moderation", { return ajax("/admin/users/" + this.get('id') + "/revoke_moderation", {
type: 'PUT' type: 'PUT'
}).then(function() { }).then(function() {
self.setProperties({ self.setProperties({
@ -153,7 +154,7 @@ const AdminUser = Discourse.User.extend({
grantModeration() { grantModeration() {
const self = this; const self = this;
return Discourse.ajax("/admin/users/" + this.get('id') + "/grant_moderation", { return ajax("/admin/users/" + this.get('id') + "/grant_moderation", {
type: 'PUT' type: 'PUT'
}).then(function() { }).then(function() {
self.setProperties({ self.setProperties({
@ -165,14 +166,14 @@ const AdminUser = Discourse.User.extend({
}, },
refreshBrowsers() { refreshBrowsers() {
return Discourse.ajax("/admin/users/" + this.get('id') + "/refresh_browsers", { return ajax("/admin/users/" + this.get('id') + "/refresh_browsers", {
type: 'POST' type: 'POST'
}).finally(() => bootbox.alert(I18n.t("admin.user.refresh_browsers_message"))); }).finally(() => bootbox.alert(I18n.t("admin.user.refresh_browsers_message")));
}, },
approve() { approve() {
const self = this; const self = this;
return Discourse.ajax("/admin/users/" + this.get('id') + "/approve", { return ajax("/admin/users/" + this.get('id') + "/approve", {
type: 'PUT' type: 'PUT'
}).then(function() { }).then(function() {
self.setProperties({ self.setProperties({
@ -190,7 +191,7 @@ const AdminUser = Discourse.User.extend({
dirty: propertyNotEqual('originalTrustLevel', 'trustLevel.id'), dirty: propertyNotEqual('originalTrustLevel', 'trustLevel.id'),
saveTrustLevel() { saveTrustLevel() {
return Discourse.ajax("/admin/users/" + this.id + "/trust_level", { return ajax("/admin/users/" + this.id + "/trust_level", {
type: 'PUT', type: 'PUT',
data: { level: this.get('trustLevel.id') } data: { level: this.get('trustLevel.id') }
}).then(function() { }).then(function() {
@ -210,7 +211,7 @@ const AdminUser = Discourse.User.extend({
}, },
lockTrustLevel(locked) { lockTrustLevel(locked) {
return Discourse.ajax("/admin/users/" + this.id + "/trust_level_lock", { return ajax("/admin/users/" + this.id + "/trust_level_lock", {
type: 'PUT', type: 'PUT',
data: { locked: !!locked } data: { locked: !!locked }
}).then(function() { }).then(function() {
@ -239,14 +240,14 @@ const AdminUser = Discourse.User.extend({
}.property('suspended_till', 'suspended_at'), }.property('suspended_till', 'suspended_at'),
suspend(duration, reason) { suspend(duration, reason) {
return Discourse.ajax("/admin/users/" + this.id + "/suspend", { return ajax("/admin/users/" + this.id + "/suspend", {
type: 'PUT', type: 'PUT',
data: { duration: duration, reason: reason } data: { duration: duration, reason: reason }
}); });
}, },
unsuspend() { unsuspend() {
return Discourse.ajax("/admin/users/" + this.id + "/unsuspend", { return ajax("/admin/users/" + this.id + "/unsuspend", {
type: 'PUT' type: 'PUT'
}).then(function() { }).then(function() {
window.location.reload(); window.location.reload();
@ -257,7 +258,7 @@ const AdminUser = Discourse.User.extend({
}, },
log_out() { log_out() {
return Discourse.ajax("/admin/users/" + this.id + "/log_out", { return ajax("/admin/users/" + this.id + "/log_out", {
type: 'POST', type: 'POST',
data: { username_or_email: this.get('username') } data: { username_or_email: this.get('username') }
}).then(function() { }).then(function() {
@ -266,7 +267,7 @@ const AdminUser = Discourse.User.extend({
}, },
impersonate() { impersonate() {
return Discourse.ajax("/admin/impersonate", { return ajax("/admin/impersonate", {
type: 'POST', type: 'POST',
data: { username_or_email: this.get('username') } data: { username_or_email: this.get('username') }
}).then(function() { }).then(function() {
@ -281,7 +282,7 @@ const AdminUser = Discourse.User.extend({
}, },
activate() { activate() {
return Discourse.ajax('/admin/users/' + this.id + '/activate', { return ajax('/admin/users/' + this.id + '/activate', {
type: 'PUT' type: 'PUT'
}).then(function() { }).then(function() {
window.location.reload(); window.location.reload();
@ -292,7 +293,7 @@ const AdminUser = Discourse.User.extend({
}, },
deactivate() { deactivate() {
return Discourse.ajax('/admin/users/' + this.id + '/deactivate', { return ajax('/admin/users/' + this.id + '/deactivate', {
type: 'PUT' type: 'PUT'
}).then(function() { }).then(function() {
window.location.reload(); window.location.reload();
@ -304,7 +305,7 @@ const AdminUser = Discourse.User.extend({
unblock() { unblock() {
this.set('blockingUser', true); this.set('blockingUser', true);
return Discourse.ajax('/admin/users/' + this.id + '/unblock', { return ajax('/admin/users/' + this.id + '/unblock', {
type: 'PUT' type: 'PUT'
}).then(function() { }).then(function() {
window.location.reload(); window.location.reload();
@ -320,7 +321,7 @@ const AdminUser = Discourse.User.extend({
const performBlock = function() { const performBlock = function() {
user.set('blockingUser', true); user.set('blockingUser', true);
return Discourse.ajax('/admin/users/' + user.id + '/block', { return ajax('/admin/users/' + user.id + '/block', {
type: 'PUT' type: 'PUT'
}).then(function() { }).then(function() {
window.location.reload(); window.location.reload();
@ -345,7 +346,7 @@ const AdminUser = Discourse.User.extend({
}, },
sendActivationEmail() { sendActivationEmail() {
return Discourse.ajax('/users/action/send_activation_email', { return ajax('/users/action/send_activation_email', {
type: 'POST', type: 'POST',
data: { username: this.get('username') } data: { username: this.get('username') }
}).then(function() { }).then(function() {
@ -360,7 +361,7 @@ const AdminUser = Discourse.User.extend({
message = I18n.t("admin.user.anonymize_confirm"); message = I18n.t("admin.user.anonymize_confirm");
const performAnonymize = function() { const performAnonymize = function() {
return Discourse.ajax("/admin/users/" + user.get('id') + '/anonymize.json', { return ajax("/admin/users/" + user.get('id') + '/anonymize.json', {
type: 'PUT' type: 'PUT'
}).then(function(data) { }).then(function(data) {
if (data.success) { if (data.success) {
@ -422,7 +423,7 @@ const AdminUser = Discourse.User.extend({
if (opts && opts.deletePosts) { if (opts && opts.deletePosts) {
formData["delete_posts"] = true; formData["delete_posts"] = true;
} }
return Discourse.ajax("/admin/users/" + user.get('id') + '.json', { return ajax("/admin/users/" + user.get('id') + '.json', {
type: 'DELETE', type: 'DELETE',
data: formData data: formData
}).then(function(data) { }).then(function(data) {
@ -481,7 +482,7 @@ const AdminUser = Discourse.User.extend({
"label": '<i class="fa fa-exclamation-triangle"></i> ' + I18n.t("flagging.yes_delete_spammer"), "label": '<i class="fa fa-exclamation-triangle"></i> ' + I18n.t("flagging.yes_delete_spammer"),
"class": "btn btn-danger", "class": "btn btn-danger",
"callback": function() { "callback": function() {
return Discourse.ajax("/admin/users/" + user.get('id') + '.json', { return ajax("/admin/users/" + user.get('id') + '.json', {
type: 'DELETE', type: 'DELETE',
data: { data: {
delete_posts: true, delete_posts: true,
@ -549,7 +550,7 @@ AdminUser.reopenClass({
}); });
}); });
return Discourse.ajax("/admin/users/approve-bulk", { return ajax("/admin/users/approve-bulk", {
type: 'PUT', type: 'PUT',
data: { users: users.map((u) => u.id) } data: { users: users.map((u) => u.id) }
}).finally(() => bootbox.alert(I18n.t("admin.user.approve_bulk_success"))); }).finally(() => bootbox.alert(I18n.t("admin.user.approve_bulk_success")));
@ -561,7 +562,7 @@ AdminUser.reopenClass({
user.set('selected', false); user.set('selected', false);
}); });
return Discourse.ajax("/admin/users/reject-bulk", { return ajax("/admin/users/reject-bulk", {
type: 'DELETE', type: 'DELETE',
data: { data: {
users: users.map((u) => u.id), users: users.map((u) => u.id),
@ -571,14 +572,14 @@ AdminUser.reopenClass({
}, },
find(user_id) { find(user_id) {
return Discourse.ajax("/admin/users/" + user_id + ".json").then(result => { return ajax("/admin/users/" + user_id + ".json").then(result => {
result.loadedDetails = true; result.loadedDetails = true;
return AdminUser.create(result); return AdminUser.create(result);
}); });
}, },
findAll(query, filter) { findAll(query, filter) {
return Discourse.ajax("/admin/users/list/" + query + ".json", { return ajax("/admin/users/list/" + query + ".json", {
data: filter data: filter
}).then(function(users) { }).then(function(users) {
return users.map((u) => AdminUser.create(u)); return users.map((u) => AdminUser.create(u));

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
const ApiKey = Discourse.Model.extend({ const ApiKey = Discourse.Model.extend({
/** /**
@ -8,7 +9,7 @@ const ApiKey = Discourse.Model.extend({
**/ **/
regenerate: function() { regenerate: function() {
var self = this; var self = this;
return Discourse.ajax('/admin/api/key', {type: 'PUT', data: {id: this.get('id')}}).then(function (result) { return ajax('/admin/api/key', {type: 'PUT', data: {id: this.get('id')}}).then(function (result) {
self.set('key', result.api_key.key); self.set('key', result.api_key.key);
return self; return self;
}); });
@ -21,7 +22,7 @@ const ApiKey = Discourse.Model.extend({
@returns {Promise} a promise that resolves when the key has been revoked @returns {Promise} a promise that resolves when the key has been revoked
**/ **/
revoke: function() { revoke: function() {
return Discourse.ajax('/admin/api/key', {type: 'DELETE', data: {id: this.get('id')}}); return ajax('/admin/api/key', {type: 'DELETE', data: {id: this.get('id')}});
} }
}); });
@ -51,7 +52,7 @@ ApiKey.reopenClass({
@returns {Promise} a promise that resolves to the array of `ApiKey` instances @returns {Promise} a promise that resolves to the array of `ApiKey` instances
**/ **/
find: function() { find: function() {
return Discourse.ajax("/admin/api").then(function(keys) { return ajax("/admin/api").then(function(keys) {
return keys.map(function (key) { return keys.map(function (key) {
return ApiKey.create(key); return ApiKey.create(key);
}); });
@ -65,7 +66,7 @@ ApiKey.reopenClass({
@returns {Promise} a promise that resolves to a master `ApiKey` @returns {Promise} a promise that resolves to a master `ApiKey`
**/ **/
generateMasterKey: function() { generateMasterKey: function() {
return Discourse.ajax("/admin/api/key", {type: 'POST'}).then(function (result) { return ajax("/admin/api/key", {type: 'POST'}).then(function (result) {
return ApiKey.create(result.api_key); return ApiKey.create(result.api_key);
}); });
} }

View file

@ -1,11 +1,12 @@
import { ajax } from 'discourse/lib/ajax';
const Backup = Discourse.Model.extend({ const Backup = Discourse.Model.extend({
destroy() { destroy() {
return Discourse.ajax("/admin/backups/" + this.get("filename"), { type: "DELETE" }); return ajax("/admin/backups/" + this.get("filename"), { type: "DELETE" });
}, },
restore() { restore() {
return Discourse.ajax("/admin/backups/" + this.get("filename") + "/restore", { return ajax("/admin/backups/" + this.get("filename") + "/restore", {
type: "POST", type: "POST",
data: { client_id: window.MessageBus.clientId } data: { client_id: window.MessageBus.clientId }
}); });
@ -16,13 +17,13 @@ const Backup = Discourse.Model.extend({
Backup.reopenClass({ Backup.reopenClass({
find() { find() {
return PreloadStore.getAndRemove("backups", () => Discourse.ajax("/admin/backups.json")) return PreloadStore.getAndRemove("backups", () => ajax("/admin/backups.json"))
.then(backups => backups.map(backup => Backup.create(backup))); .then(backups => backups.map(backup => Backup.create(backup)));
}, },
start(withUploads) { start(withUploads) {
if (withUploads === undefined) { withUploads = true; } if (withUploads === undefined) { withUploads = true; }
return Discourse.ajax("/admin/backups", { return ajax("/admin/backups", {
type: "POST", type: "POST",
data: { data: {
with_uploads: withUploads, with_uploads: withUploads,
@ -34,14 +35,14 @@ Backup.reopenClass({
}, },
cancel() { cancel() {
return Discourse.ajax("/admin/backups/cancel.json") return ajax("/admin/backups/cancel.json")
.then(result => { .then(result => {
if (!result.success) { bootbox.alert(result.message); } if (!result.success) { bootbox.alert(result.message); }
}); });
}, },
rollback() { rollback() {
return Discourse.ajax("/admin/backups/rollback.json") return ajax("/admin/backups/rollback.json")
.then(result => { .then(result => {
if (!result.success) { if (!result.success) {
bootbox.alert(result.message); bootbox.alert(result.message);

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import ColorSchemeColor from 'admin/models/color-scheme-color'; import ColorSchemeColor from 'admin/models/color-scheme-color';
const ColorScheme = Discourse.Model.extend(Ember.Copyable, { const ColorScheme = Discourse.Model.extend(Ember.Copyable, {
@ -65,7 +66,7 @@ const ColorScheme = Discourse.Model.extend(Ember.Copyable, {
}); });
} }
return Discourse.ajax("/admin/color_schemes" + (this.id ? '/' + this.id : '') + '.json', { return ajax("/admin/color_schemes" + (this.id ? '/' + this.id : '') + '.json', {
data: JSON.stringify({"color_scheme": data}), data: JSON.stringify({"color_scheme": data}),
type: this.id ? 'PUT' : 'POST', type: this.id ? 'PUT' : 'POST',
dataType: 'json', dataType: 'json',
@ -88,7 +89,7 @@ const ColorScheme = Discourse.Model.extend(Ember.Copyable, {
destroy: function() { destroy: function() {
if (this.id) { if (this.id) {
return Discourse.ajax("/admin/color_schemes/" + this.id, { type: 'DELETE' }); return ajax("/admin/color_schemes/" + this.id, { type: 'DELETE' });
} }
} }
@ -106,7 +107,7 @@ var ColorSchemes = Ember.ArrayProxy.extend({
ColorScheme.reopenClass({ ColorScheme.reopenClass({
findAll: function() { findAll: function() {
var colorSchemes = ColorSchemes.create({ content: [], loading: true }); var colorSchemes = ColorSchemes.create({ content: [], loading: true });
Discourse.ajax('/admin/color_schemes').then(function(all) { ajax('/admin/color_schemes').then(function(all) {
_.each(all, function(colorScheme){ _.each(all, function(colorScheme){
colorSchemes.pushObject(ColorScheme.create({ colorSchemes.pushObject(ColorScheme.create({
id: colorScheme.id, id: colorScheme.id,

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import AdminUser from 'admin/models/admin-user'; import AdminUser from 'admin/models/admin-user';
const EmailLog = Discourse.Model.extend({}); const EmailLog = Discourse.Model.extend({});
@ -21,7 +22,7 @@ EmailLog.reopenClass({
const status = filter.status || "sent"; const status = filter.status || "sent";
filter = _.omit(filter, "status"); filter = _.omit(filter, "status");
return Discourse.ajax(`/admin/email/${status}.json?offset=${offset}`, { data: filter }) return ajax(`/admin/email/${status}.json?offset=${offset}`, { data: filter })
.then(logs => _.map(logs, log => EmailLog.create(log))); .then(logs => _.map(logs, log => EmailLog.create(log)));
} }
}); });

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
const EmailPreview = Discourse.Model.extend({}); const EmailPreview = Discourse.Model.extend({});
EmailPreview.reopenClass({ EmailPreview.reopenClass({
@ -11,7 +12,7 @@ EmailPreview.reopenClass({
username = Discourse.User.current().username; username = Discourse.User.current().username;
} }
return Discourse.ajax("/admin/email/preview-digest.json", { return ajax("/admin/email/preview-digest.json", {
data: { last_seen_at: lastSeenAt, username: username } data: { last_seen_at: lastSeenAt, username: username }
}).then(function (result) { }).then(function (result) {
return EmailPreview.create(result); return EmailPreview.create(result);

View file

@ -1,8 +1,9 @@
import { ajax } from 'discourse/lib/ajax';
const EmailSettings = Discourse.Model.extend({}); const EmailSettings = Discourse.Model.extend({});
EmailSettings.reopenClass({ EmailSettings.reopenClass({
find: function() { find: function() {
return Discourse.ajax("/admin/email.json").then(function (settings) { return ajax("/admin/email.json").then(function (settings) {
return EmailSettings.create(settings); return EmailSettings.create(settings);
}); });
} }

View file

@ -1,9 +1,10 @@
import { ajax } from 'discourse/lib/ajax';
import RestModel from 'discourse/models/rest'; import RestModel from 'discourse/models/rest';
const { getProperties } = Ember; const { getProperties } = Ember;
export default RestModel.extend({ export default RestModel.extend({
revert() { revert() {
return Discourse.ajax(`/admin/customize/email_templates/${this.get('id')}`, { return ajax(`/admin/customize/email_templates/${this.get('id')}`, {
method: 'DELETE' method: 'DELETE'
}).then(result => getProperties(result.email_template, 'subject', 'body', 'can_revert')); }).then(result => getProperties(result.email_template, 'subject', 'body', 'can_revert'));
} }

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import AdminUser from 'admin/models/admin-user'; import AdminUser from 'admin/models/admin-user';
import Topic from 'discourse/models/topic'; import Topic from 'discourse/models/topic';
import Post from 'discourse/models/post'; import Post from 'discourse/models/post';
@ -106,22 +107,22 @@ const FlaggedPost = Post.extend({
deletePost: function() { deletePost: function() {
if (this.get('post_number') === 1) { if (this.get('post_number') === 1) {
return Discourse.ajax('/t/' + this.topic_id, { type: 'DELETE', cache: false }); return ajax('/t/' + this.topic_id, { type: 'DELETE', cache: false });
} else { } else {
return Discourse.ajax('/posts/' + this.id, { type: 'DELETE', cache: false }); return ajax('/posts/' + this.id, { type: 'DELETE', cache: false });
} }
}, },
disagreeFlags: function () { disagreeFlags: function () {
return Discourse.ajax('/admin/flags/disagree/' + this.id, { type: 'POST', cache: false }); return ajax('/admin/flags/disagree/' + this.id, { type: 'POST', cache: false });
}, },
deferFlags: function (deletePost) { deferFlags: function (deletePost) {
return Discourse.ajax('/admin/flags/defer/' + this.id, { type: 'POST', cache: false, data: { delete_post: deletePost } }); return ajax('/admin/flags/defer/' + this.id, { type: 'POST', cache: false, data: { delete_post: deletePost } });
}, },
agreeFlags: function (actionOnPost) { agreeFlags: function (actionOnPost) {
return Discourse.ajax('/admin/flags/agree/' + this.id, { type: 'POST', cache: false, data: { action_on_post: actionOnPost } }); return ajax('/admin/flags/agree/' + this.id, { type: 'POST', cache: false, data: { action_on_post: actionOnPost } });
}, },
postHidden: Em.computed.alias('hidden'), postHidden: Em.computed.alias('hidden'),
@ -144,7 +145,7 @@ FlaggedPost.reopenClass({
var result = Em.A(); var result = Em.A();
result.set('loading', true); result.set('loading', true);
return Discourse.ajax('/admin/flags/' + filter + '.json?offset=' + offset).then(function (data) { return ajax('/admin/flags/' + filter + '.json?offset=' + offset).then(function (data) {
// users // users
var userLookup = {}; var userLookup = {};
_.each(data.users, function (user) { _.each(data.users, function (user) {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import AdminUser from 'admin/models/admin-user'; import AdminUser from 'admin/models/admin-user';
const IncomingEmail = Discourse.Model.extend({}); const IncomingEmail = Discourse.Model.extend({});
@ -15,7 +16,7 @@ IncomingEmail.reopenClass({
}, },
find(id) { find(id) {
return Discourse.ajax(`/admin/email/incoming/${id}.json`); return ajax(`/admin/email/incoming/${id}.json`);
}, },
findAll(filter, offset) { findAll(filter, offset) {
@ -25,12 +26,12 @@ IncomingEmail.reopenClass({
const status = filter.status || "received"; const status = filter.status || "received";
filter = _.omit(filter, "status"); filter = _.omit(filter, "status");
return Discourse.ajax(`/admin/email/${status}.json?offset=${offset}`, { data: filter }) return ajax(`/admin/email/${status}.json?offset=${offset}`, { data: filter })
.then(incomings => _.map(incomings, incoming => IncomingEmail.create(incoming))); .then(incomings => _.map(incomings, incoming => IncomingEmail.create(incoming)));
}, },
loadRawEmail(id) { loadRawEmail(id) {
return Discourse.ajax(`/admin/email/incoming/${id}/raw.json`); return ajax(`/admin/email/incoming/${id}/raw.json`);
} }
}); });

View file

@ -1,19 +1,20 @@
import { ajax } from 'discourse/lib/ajax';
const Permalink = Discourse.Model.extend({ const Permalink = Discourse.Model.extend({
save: function() { save: function() {
return Discourse.ajax("/admin/permalinks.json", { return ajax("/admin/permalinks.json", {
type: 'POST', type: 'POST',
data: {url: this.get('url'), permalink_type: this.get('permalink_type'), permalink_type_value: this.get('permalink_type_value')} data: {url: this.get('url'), permalink_type: this.get('permalink_type'), permalink_type_value: this.get('permalink_type_value')}
}); });
}, },
destroy: function() { destroy: function() {
return Discourse.ajax("/admin/permalinks/" + this.get('id') + ".json", {type: 'DELETE'}); return ajax("/admin/permalinks/" + this.get('id') + ".json", {type: 'DELETE'});
} }
}); });
Permalink.reopenClass({ Permalink.reopenClass({
findAll: function(filter) { findAll: function(filter) {
return Discourse.ajax("/admin/permalinks.json", { data: { filter: filter } }).then(function(permalinks) { return ajax("/admin/permalinks.json", { data: { filter: filter } }).then(function(permalinks) {
return permalinks.map(p => Permalink.create(p)); return permalinks.map(p => Permalink.create(p));
}); });
} }

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import round from "discourse/lib/round"; import round from "discourse/lib/round";
import { fmt } from 'discourse/lib/computed'; import { fmt } from 'discourse/lib/computed';
@ -132,7 +133,7 @@ const Report = Discourse.Model.extend({
Report.reopenClass({ Report.reopenClass({
find(type, startDate, endDate, categoryId, groupId) { find(type, startDate, endDate, categoryId, groupId) {
return Discourse.ajax("/admin/reports/" + type, { return ajax("/admin/reports/" + type, {
data: { data: {
start_date: startDate, start_date: startDate,
end_date: endDate, end_date: endDate,

View file

@ -1,16 +1,17 @@
import { ajax } from 'discourse/lib/ajax';
const ScreenedEmail = Discourse.Model.extend({ const ScreenedEmail = Discourse.Model.extend({
actionName: function() { actionName: function() {
return I18n.t("admin.logs.screened_actions." + this.get('action')); return I18n.t("admin.logs.screened_actions." + this.get('action'));
}.property('action'), }.property('action'),
clearBlock: function() { clearBlock: function() {
return Discourse.ajax('/admin/logs/screened_emails/' + this.get('id'), {method: 'DELETE'}); return ajax('/admin/logs/screened_emails/' + this.get('id'), {method: 'DELETE'});
} }
}); });
ScreenedEmail.reopenClass({ ScreenedEmail.reopenClass({
findAll: function() { findAll: function() {
return Discourse.ajax("/admin/logs/screened_emails.json").then(function(screened_emails) { return ajax("/admin/logs/screened_emails.json").then(function(screened_emails) {
return screened_emails.map(function(b) { return screened_emails.map(function(b) {
return ScreenedEmail.create(b); return ScreenedEmail.create(b);
}); });

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import computed from 'ember-addons/ember-computed-decorators'; import computed from 'ember-addons/ember-computed-decorators';
const ScreenedIpAddress = Discourse.Model.extend({ const ScreenedIpAddress = Discourse.Model.extend({
@ -14,25 +15,25 @@ const ScreenedIpAddress = Discourse.Model.extend({
}, },
save() { save() {
return Discourse.ajax("/admin/logs/screened_ip_addresses" + (this.id ? '/' + this.id : '') + ".json", { return ajax("/admin/logs/screened_ip_addresses" + (this.id ? '/' + this.id : '') + ".json", {
type: this.id ? 'PUT' : 'POST', type: this.id ? 'PUT' : 'POST',
data: {ip_address: this.get('ip_address'), action_name: this.get('action_name')} data: {ip_address: this.get('ip_address'), action_name: this.get('action_name')}
}); });
}, },
destroy() { destroy() {
return Discourse.ajax("/admin/logs/screened_ip_addresses/" + this.get('id') + ".json", {type: 'DELETE'}); return ajax("/admin/logs/screened_ip_addresses/" + this.get('id') + ".json", {type: 'DELETE'});
} }
}); });
ScreenedIpAddress.reopenClass({ ScreenedIpAddress.reopenClass({
findAll(filter) { findAll(filter) {
return Discourse.ajax("/admin/logs/screened_ip_addresses.json", { data: { filter: filter } }) return ajax("/admin/logs/screened_ip_addresses.json", { data: { filter: filter } })
.then(screened_ips => screened_ips.map(b => ScreenedIpAddress.create(b))); .then(screened_ips => screened_ips.map(b => ScreenedIpAddress.create(b)));
}, },
rollUp() { rollUp() {
return Discourse.ajax("/admin/logs/screened_ip_addresses/roll_up", { type: "POST" }); return ajax("/admin/logs/screened_ip_addresses/roll_up", { type: "POST" });
} }
}); });

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
const ScreenedUrl = Discourse.Model.extend({ const ScreenedUrl = Discourse.Model.extend({
actionName: function() { actionName: function() {
return I18n.t("admin.logs.screened_actions." + this.get('action')); return I18n.t("admin.logs.screened_actions." + this.get('action'));
@ -6,7 +7,7 @@ const ScreenedUrl = Discourse.Model.extend({
ScreenedUrl.reopenClass({ ScreenedUrl.reopenClass({
findAll: function() { findAll: function() {
return Discourse.ajax("/admin/logs/screened_urls.json").then(function(screened_urls) { return ajax("/admin/logs/screened_urls.json").then(function(screened_urls) {
return screened_urls.map(function(b) { return screened_urls.map(function(b) {
return ScreenedUrl.create(b); return ScreenedUrl.create(b);
}); });

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
const SiteSetting = Discourse.Model.extend({ const SiteSetting = Discourse.Model.extend({
overridden: function() { overridden: function() {
let val = this.get('value'), let val = this.get('value'),
@ -28,7 +29,7 @@ const SiteSetting = Discourse.Model.extend({
SiteSetting.reopenClass({ SiteSetting.reopenClass({
findAll() { findAll() {
return Discourse.ajax("/admin/site_settings").then(function (settings) { return ajax("/admin/site_settings").then(function (settings) {
// Group the results by category // Group the results by category
const categories = {}; const categories = {};
settings.site_settings.forEach(function(s) { settings.site_settings.forEach(function(s) {
@ -47,7 +48,7 @@ SiteSetting.reopenClass({
update(key, value) { update(key, value) {
const data = {}; const data = {};
data[key] = value; data[key] = value;
return Discourse.ajax("/admin/site_settings/" + key, { type: 'PUT', data }); return ajax("/admin/site_settings/" + key, { type: 'PUT', data });
} }
}); });

View file

@ -1,9 +1,10 @@
import { ajax } from 'discourse/lib/ajax';
import RestModel from 'discourse/models/rest'; import RestModel from 'discourse/models/rest';
const { getProperties } = Ember; const { getProperties } = Ember;
export default RestModel.extend({ export default RestModel.extend({
revert() { revert() {
return Discourse.ajax(`/admin/customize/site_texts/${this.get('id')}`, { return ajax(`/admin/customize/site_texts/${this.get('id')}`, {
method: 'DELETE' method: 'DELETE'
}).then(result => getProperties(result.site_text, 'value', 'can_revert')); }).then(result => getProperties(result.site_text, 'value', 'can_revert'));
} }

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import AdminUser from 'admin/models/admin-user'; import AdminUser from 'admin/models/admin-user';
import { escapeExpression } from 'discourse/lib/utilities'; import { escapeExpression } from 'discourse/lib/utilities';
@ -56,7 +57,7 @@ StaffActionLog.reopenClass({
}, },
findAll: function(filters) { findAll: function(filters) {
return Discourse.ajax("/admin/logs/staff_action_logs.json", { data: filters }).then(function(staff_actions) { return ajax("/admin/logs/staff_action_logs.json", { data: filters }).then(function(staff_actions) {
return staff_actions.map(function(s) { return staff_actions.map(function(s) {
return StaffActionLog.create(s); return StaffActionLog.create(s);
}); });

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
const VersionCheck = Discourse.Model.extend({ const VersionCheck = Discourse.Model.extend({
noCheckPerformed: function() { noCheckPerformed: function() {
@ -33,7 +34,7 @@ const VersionCheck = Discourse.Model.extend({
VersionCheck.reopenClass({ VersionCheck.reopenClass({
find: function() { find: function() {
return Discourse.ajax('/admin/version_check').then(function(json) { return ajax('/admin/version_check').then(function(json) {
return VersionCheck.create(json); return VersionCheck.create(json);
}); });
} }

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import showModal from 'discourse/lib/show-modal'; import showModal from 'discourse/lib/show-modal';
import BackupStatus from 'admin/models/backup-status'; import BackupStatus from 'admin/models/backup-status';
import Backup from 'admin/models/backup'; import Backup from 'admin/models/backup';
@ -31,7 +32,7 @@ export default Discourse.Route.extend({
model() { model() {
return PreloadStore.getAndRemove("operations_status", function() { return PreloadStore.getAndRemove("operations_status", function() {
return Discourse.ajax("/admin/backups/status.json"); return ajax("/admin/backups/status.json");
}).then(status => { }).then(status => {
return BackupStatus.create({ return BackupStatus.create({
isOperationRunning: status.is_operation_running, isOperationRunning: status.is_operation_running,

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import Badge from 'discourse/models/badge'; import Badge from 'discourse/models/badge';
import showModal from 'discourse/lib/show-modal'; import showModal from 'discourse/lib/show-modal';
@ -31,7 +32,7 @@ export default Ember.Route.extend({
preview(badge, explain) { preview(badge, explain) {
badge.set('preview_loading', true); badge.set('preview_loading', true);
Discourse.ajax('/admin/badges/preview.json', { ajax('/admin/badges/preview.json', {
method: 'post', method: 'post',
data: { data: {
sql: badge.get('query'), sql: badge.get('query'),

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import Badge from 'discourse/models/badge'; import Badge from 'discourse/models/badge';
import BadgeGrouping from 'discourse/models/badge-grouping'; import BadgeGrouping from 'discourse/models/badge-grouping';
@ -6,7 +7,7 @@ export default Discourse.Route.extend({
model: function() { model: function() {
var self = this; var self = this;
return Discourse.ajax('/admin/badges.json').then(function(json) { return ajax('/admin/badges.json').then(function(json) {
self._json = json; self._json = json;
return Badge.createFromJson(json); return Badge.createFromJson(json);
}); });

View file

@ -1,6 +1,7 @@
import { ajax } from 'discourse/lib/ajax';
export default Discourse.Route.extend({ export default Discourse.Route.extend({
model: function() { model: function() {
return Discourse.ajax("/admin/customize/emojis.json").then(function(emojis) { return ajax("/admin/customize/emojis.json").then(function(emojis) {
return emojis.map(function (emoji) { return Ember.Object.create(emoji); }); return emojis.map(function (emoji) { return Ember.Object.create(emoji); });
}); });
} }

View file

@ -8,7 +8,7 @@ define('ember', ['exports'], function(__exports__) {
var _pluginCallbacks = []; var _pluginCallbacks = [];
window.Discourse = Ember.Application.extend(Discourse.Ajax, { window.Discourse = Ember.Application.extend({
rootElement: '#main', rootElement: '#main',
_docTitle: document.title, _docTitle: document.title,
__TAGS_INCLUDED__: true, __TAGS_INCLUDED__: true,
@ -179,6 +179,12 @@ window.Discourse = Ember.Application.extend(Discourse.Ajax, {
}) })
}).create(); }).create();
Discourse.ajax = function() {
var ajax = require('discourse/lib/ajax').ajax;
Ember.warn("Discourse.ajax is deprecated. Import the module and use it instead");
return ajax.apply(this, arguments);
};
Discourse.Markdown = { Discourse.Markdown = {
whiteListTag: Ember.K, whiteListTag: Ember.K,
whiteListIframe: Ember.K whiteListIframe: Ember.K

View file

@ -1,9 +1,10 @@
import { ajax } from 'discourse/lib/ajax';
import RestAdapter from 'discourse/adapters/rest'; import RestAdapter from 'discourse/adapters/rest';
export default RestAdapter.extend({ export default RestAdapter.extend({
find(store, type, findArgs) { find(store, type, findArgs) {
const maxReplies = Discourse.SiteSettings.max_reply_history; const maxReplies = Discourse.SiteSettings.max_reply_history;
return Discourse.ajax(`/posts/${findArgs.postId}/reply-history?max_replies=${maxReplies}`).then(replies => { return ajax(`/posts/${findArgs.postId}/reply-history?max_replies=${maxReplies}`).then(replies => {
return { post_reply_histories: replies }; return { post_reply_histories: replies };
}); });
}, },

View file

@ -1,8 +1,9 @@
import { ajax } from 'discourse/lib/ajax';
import RestAdapter from 'discourse/adapters/rest'; import RestAdapter from 'discourse/adapters/rest';
export default RestAdapter.extend({ export default RestAdapter.extend({
find(store, type, findArgs) { find(store, type, findArgs) {
return Discourse.ajax(`/posts/${findArgs.postId}/replies`).then(replies => { return ajax(`/posts/${findArgs.postId}/replies`).then(replies => {
return { post_replies: replies }; return { post_replies: replies };
}); });
}, },

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import RestAdapter from 'discourse/adapters/rest'; import RestAdapter from 'discourse/adapters/rest';
import { Result } from 'discourse/adapters/rest'; import { Result } from 'discourse/adapters/rest';
@ -12,7 +13,7 @@ export default RestAdapter.extend({
createRecord(store, type, args) { createRecord(store, type, args) {
const typeField = Ember.String.underscore(type); const typeField = Ember.String.underscore(type);
args.nested_post = true; args.nested_post = true;
return Discourse.ajax(this.pathFor(store, type), { method: 'POST', data: args }).then(function (json) { return ajax(this.pathFor(store, type), { method: 'POST', data: args }).then(function (json) {
return new Result(json[typeField], json); return new Result(json[typeField], json);
}); });
} }

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import { hashString } from 'discourse/lib/hash'; import { hashString } from 'discourse/lib/hash';
const ADMIN_MODELS = ['plugin', 'site-customization', 'embeddable-host']; const ADMIN_MODELS = ['plugin', 'site-customization', 'embeddable-host'];
@ -9,8 +10,6 @@ export function Result(payload, responseJson) {
this.target = null; this.target = null;
} }
const ajax = Discourse.ajax;
// We use this to make sure 404s are caught // We use this to make sure 404s are caught
function rethrow(error) { function rethrow(error) {
if (error.status === 404) { if (error.status === 404) {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import RestAdapter from 'discourse/adapters/rest'; import RestAdapter from 'discourse/adapters/rest';
export function finderFor(filter, params) { export function finderFor(filter, params) {
@ -19,7 +20,7 @@ export function finderFor(filter, params) {
url += "?" + encoded.join('&'); url += "?" + encoded.join('&');
} }
} }
return Discourse.ajax(url); return ajax(url);
}; };
} }

View file

@ -1,9 +1,10 @@
import { ajax } from 'discourse/lib/ajax';
import RestAdapter from 'discourse/adapters/rest'; import RestAdapter from 'discourse/adapters/rest';
export default RestAdapter.extend({ export default RestAdapter.extend({
find(store, type, findArgs) { find(store, type, findArgs) {
if (findArgs.similar) { if (findArgs.similar) {
return Discourse.ajax("/topics/similar_to", { data: findArgs.similar }); return ajax("/topics/similar_to", { data: findArgs.similar });
} else { } else {
return this._super(store, type, findArgs); return this._super(store, type, findArgs);
} }

View file

@ -4,6 +4,7 @@ import { linkSeenMentions, fetchUnseenMentions } from 'discourse/lib/link-mentio
import { linkSeenCategoryHashtags, fetchUnseenCategoryHashtags } from 'discourse/lib/link-category-hashtags'; import { linkSeenCategoryHashtags, fetchUnseenCategoryHashtags } from 'discourse/lib/link-category-hashtags';
import { fetchUnseenTagHashtags, linkSeenTagHashtags } from 'discourse/lib/link-tag-hashtag'; import { fetchUnseenTagHashtags, linkSeenTagHashtags } from 'discourse/lib/link-tag-hashtag';
import { load } from 'pretty-text/oneboxer'; import { load } from 'pretty-text/oneboxer';
import { ajax } from 'discourse/lib/ajax';
import InputValidation from 'discourse/models/input-validation'; import InputValidation from 'discourse/models/input-validation';
import { tinyAvatar, import { tinyAvatar,
@ -499,7 +500,7 @@ export default Ember.Component.extend({
} }
// Paint oneboxes // Paint oneboxes
$('a.onebox', $preview).each((i, e) => load(e, refresh)); $('a.onebox', $preview).each((i, e) => load(e, refresh, ajax));
this.trigger('previewRefreshed', $preview); this.trigger('previewRefreshed', $preview);
this.sendAction('afterRefresh', $preview); this.sendAction('afterRefresh', $preview);
}, },

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import debounce from 'discourse/lib/debounce'; import debounce from 'discourse/lib/debounce';
import ModalFunctionality from 'discourse/mixins/modal-functionality'; import ModalFunctionality from 'discourse/mixins/modal-functionality';
import { setting } from 'discourse/lib/computed'; import { setting } from 'discourse/lib/computed';
@ -336,7 +337,7 @@ export default Ember.Controller.extend(ModalFunctionality, {
@on('init') @on('init')
fetchConfirmationValue() { fetchConfirmationValue() {
return Discourse.ajax('/users/hp.json').then(json => { return ajax('/users/hp.json').then(json => {
this.set('accountPasswordConfirm', json.value); this.set('accountPasswordConfirm', json.value);
this.set('accountChallenge', json.challenge.split("").reverse().join("")); this.set('accountChallenge', json.challenge.split("").reverse().join(""));
}); });

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import { observes } from "ember-addons/ember-computed-decorators"; import { observes } from "ember-addons/ember-computed-decorators";
import ModalFunctionality from 'discourse/mixins/modal-functionality'; import ModalFunctionality from 'discourse/mixins/modal-functionality';
@ -32,7 +33,7 @@ export default Ember.Controller.extend(ModalFunctionality, {
setAutoClose(time) { setAutoClose(time) {
const self = this; const self = this;
this.set('loading', true); this.set('loading', true);
Discourse.ajax({ ajax({
url: `/t/${this.get('model.id')}/autoclose`, url: `/t/${this.get('model.id')}/autoclose`,
type: 'PUT', type: 'PUT',
dataType: 'json', dataType: 'json',

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import ModalFunctionality from 'discourse/mixins/modal-functionality'; import ModalFunctionality from 'discourse/mixins/modal-functionality';
import { categoryLinkHTML } from 'discourse/helpers/category-link'; import { categoryLinkHTML } from 'discourse/helpers/category-link';
import computed from 'ember-addons/ember-computed-decorators'; import computed from 'ember-addons/ember-computed-decorators';
@ -91,7 +92,7 @@ export default Ember.Controller.extend(ModalFunctionality, {
onShow() { onShow() {
this.set("loading", true); this.set("loading", true);
return Discourse.ajax("/topics/feature_stats.json", { return ajax("/topics/feature_stats.json", {
data: { category_id: this.get("model.category.id") } data: { category_id: this.get("model.category.id") }
}).then(result => { }).then(result => {
if (result) { if (result) {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import ModalFunctionality from 'discourse/mixins/modal-functionality'; import ModalFunctionality from 'discourse/mixins/modal-functionality';
import { escapeExpression } from 'discourse/lib/utilities'; import { escapeExpression } from 'discourse/lib/utilities';
@ -49,7 +50,7 @@ export default Ember.Controller.extend(ModalFunctionality, {
self.flash(e.responseJSON.errors[0], 'error'); self.flash(e.responseJSON.errors[0], 'error');
}; };
Discourse.ajax('/session/forgot_password', { ajax('/session/forgot_password', {
data: { login: this.get('accountEmailOrUsername').trim() }, data: { login: this.get('accountEmailOrUsername').trim() },
type: 'POST' type: 'POST'
}).then(success, fail).finally(function(){ }).then(success, fail).finally(function(){

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import { translateResults, searchContextDescription, getSearchKey, isValidSearchTerm } from "discourse/lib/search"; import { translateResults, searchContextDescription, getSearchKey, isValidSearchTerm } from "discourse/lib/search";
import showModal from 'discourse/lib/show-modal'; import showModal from 'discourse/lib/show-modal';
import { default as computed, observes } from 'ember-addons/ember-computed-decorators'; import { default as computed, observes } from 'ember-addons/ember-computed-decorators';
@ -157,7 +158,7 @@ export default Ember.Controller.extend({
const searchKey = getSearchKey(args); const searchKey = getSearchKey(args);
Discourse.ajax("/search", { data: args }).then(results => { ajax("/search", { data: args }).then(results => {
const model = translateResults(results) || {}; const model = translateResults(results) || {};
router.transientCache('lastSearch', { searchKey, model }, 5); router.transientCache('lastSearch', { searchKey, model }, 5);
this.set("model", model); this.set("model", model);
@ -194,7 +195,7 @@ export default Ember.Controller.extend({
showSearchHelp() { showSearchHelp() {
// TODO: dupe code should be centralized // TODO: dupe code should be centralized
Discourse.ajax("/static/search_help.html", { dataType: 'html' }).then((model) => { ajax("/static/search_help.html", { dataType: 'html' }).then((model) => {
showModal('searchHelp', { model }); showModal('searchHelp', { model });
}); });
}, },

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import ModalFunctionality from 'discourse/mixins/modal-functionality'; import ModalFunctionality from 'discourse/mixins/modal-functionality';
import showModal from 'discourse/lib/show-modal'; import showModal from 'discourse/lib/show-modal';
import { setting } from 'discourse/lib/computed'; import { setting } from 'discourse/lib/computed';
@ -55,7 +56,7 @@ export default Ember.Controller.extend(ModalFunctionality, {
this.set('loggingIn', true); this.set('loggingIn', true);
Discourse.ajax("/session", { ajax("/session", {
data: { login: this.get('loginName'), password: this.get('loginPassword') }, data: { login: this.get('loginName'), password: this.get('loginPassword') },
type: 'POST' type: 'POST'
}).then(function (result) { }).then(function (result) {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import ModalFunctionality from 'discourse/mixins/modal-functionality'; import ModalFunctionality from 'discourse/mixins/modal-functionality';
export default Ember.Controller.extend(ModalFunctionality, { export default Ember.Controller.extend(ModalFunctionality, {
@ -9,7 +10,7 @@ export default Ember.Controller.extend(ModalFunctionality, {
actions: { actions: {
sendActivationEmail: function() { sendActivationEmail: function() {
Discourse.ajax('/users/action/send_activation_email', {data: {username: this.get('username')}, type: 'POST'}); ajax('/users/action/send_activation_email', {data: {username: this.get('username')}, type: 'POST'});
this.set('emailSent', true); this.set('emailSent', true);
} }
} }

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import BadgeSelectController from "discourse/mixins/badge-select-controller"; import BadgeSelectController from "discourse/mixins/badge-select-controller";
export default Ember.ArrayController.extend(BadgeSelectController, { export default Ember.ArrayController.extend(BadgeSelectController, {
@ -11,7 +12,7 @@ export default Ember.ArrayController.extend(BadgeSelectController, {
this.setProperties({ saved: false, saving: true }); this.setProperties({ saved: false, saving: true });
var self = this; var self = this;
Discourse.ajax(this.get('user.path') + "/preferences/badge_title", { ajax(this.get('user.path') + "/preferences/badge_title", {
type: "PUT", type: "PUT",
data: { user_badge_id: self.get('selectedUserBadgeId') } data: { user_badge_id: self.get('selectedUserBadgeId') }
}).then(function() { }).then(function() {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import BadgeSelectController from "discourse/mixins/badge-select-controller"; import BadgeSelectController from "discourse/mixins/badge-select-controller";
export default Ember.ArrayController.extend(BadgeSelectController, { export default Ember.ArrayController.extend(BadgeSelectController, {
@ -12,7 +13,7 @@ export default Ember.ArrayController.extend(BadgeSelectController, {
this.setProperties({ saved: false, saving: true }); this.setProperties({ saved: false, saving: true });
var self = this; var self = this;
Discourse.ajax(this.get('user.path') + "/preferences/card-badge", { ajax(this.get('user.path') + "/preferences/card-badge", {
type: "PUT", type: "PUT",
data: { user_badge_id: self.get('selectedUserBadgeId') } data: { user_badge_id: self.get('selectedUserBadgeId') }
}).then(function() { }).then(function() {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import ModalFunctionality from 'discourse/mixins/modal-functionality'; import ModalFunctionality from 'discourse/mixins/modal-functionality';
const BufferedProxy = window.BufferedProxy; // import BufferedProxy from 'ember-buffered-proxy/proxy'; const BufferedProxy = window.BufferedProxy; // import BufferedProxy from 'ember-buffered-proxy/proxy';
import { popupAjaxError } from 'discourse/lib/ajax-error'; import { popupAjaxError } from 'discourse/lib/ajax-error';
@ -90,7 +91,7 @@ export default Ember.Controller.extend(ModalFunctionality, Ember.Evented, {
this.get('categoriesBuffered').forEach((cat) => { this.get('categoriesBuffered').forEach((cat) => {
data[cat.get('id')] = cat.get('position'); data[cat.get('id')] = cat.get('position');
}); });
Discourse.ajax('/categories/reorder', ajax('/categories/reorder',
{type: 'POST', data: {mapping: JSON.stringify(data)}}). {type: 'POST', data: {mapping: JSON.stringify(data)}}).
then(() => this.send("closeModal")). then(() => this.send("closeModal")).
catch(popupAjaxError); catch(popupAjaxError);

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import computed from 'ember-addons/ember-computed-decorators'; import computed from 'ember-addons/ember-computed-decorators';
export default Ember.Controller.extend({ export default Ember.Controller.extend({
@ -15,7 +16,7 @@ export default Ember.Controller.extend({
markFaqRead() { markFaqRead() {
const currentUser = this.currentUser; const currentUser = this.currentUser;
if (currentUser) { if (currentUser) {
Discourse.ajax("/users/read-faq", { method: "POST" }).then(() => { ajax("/users/read-faq", { method: "POST" }).then(() => {
currentUser.set('read_faq', true); currentUser.set('read_faq', true);
}); });
} }

View file

@ -1,3 +1,5 @@
import { ajax } from 'discourse/lib/ajax';
import { observes } from 'ember-addons/ember-computed-decorators';
import { default as computed, observes } from 'ember-addons/ember-computed-decorators'; import { default as computed, observes } from 'ember-addons/ember-computed-decorators';
export default Ember.ArrayController.extend({ export default Ember.ArrayController.extend({
@ -17,7 +19,7 @@ export default Ember.ArrayController.extend({
actions: { actions: {
resetNew() { resetNew() {
Discourse.ajax('/notifications/mark-read', { method: 'PUT' }).then(() => { ajax('/notifications/mark-read', { method: 'PUT' }).then(() => {
this.setEach('read', true); this.setEach('read', true);
}); });
}, },

View file

@ -1,5 +1,6 @@
import { cleanDOM } from 'discourse/routes/discourse'; import { cleanDOM } from 'discourse/routes/discourse';
import { startPageTracking, onPageChange } from 'discourse/lib/page-tracker'; import { startPageTracking, onPageChange } from 'discourse/lib/page-tracker';
import { viewTrackingRequired } from 'discourse/lib/ajax';
export default { export default {
name: "page-tracking", name: "page-tracking",
@ -11,9 +12,7 @@ export default {
// Tell our AJAX system to track a page transition // Tell our AJAX system to track a page transition
const router = container.lookup('router:main'); const router = container.lookup('router:main');
router.on('willTransition', function() { router.on('willTransition', viewTrackingRequired);
Discourse.viewTrackingRequired();
});
router.on('didTransition', function() { router.on('didTransition', function() {
Em.run.scheduleOnce('afterRender', Ember.Route, cleanDOM); Em.run.scheduleOnce('afterRender', Ember.Route, cleanDOM);

View file

@ -0,0 +1,122 @@
let _trackView = false;
let _transientHeader = null;
export function setTransientHeader(key, value) {
_transientHeader = {key, value};
}
export function viewTrackingRequired() {
_trackView = true;
}
/**
Our own $.ajax method. Makes sure the .then method executes in an Ember runloop
for performance reasons. Also automatically adjusts the URL to support installs
in subfolders.
**/
export function ajax() {
let url, args;
let ajaxObj;
if (arguments.length === 1) {
if (typeof arguments[0] === "string") {
url = arguments[0];
args = {};
} else {
args = arguments[0];
url = args.url;
delete args.url;
}
} else if (arguments.length === 2) {
url = arguments[0];
args = arguments[1];
}
function performAjax(resolve, reject) {
args.headers = args.headers || {};
if (_transientHeader) {
args.headers[_transientHeader.key] = _transientHeader.value;
_transientHeader = null;
}
if (_trackView && (!args.type || args.type === "GET")) {
_trackView = false;
// DON'T CHANGE: rack is prepending "HTTP_" in the header's name
args.headers['Discourse-Track-View'] = "true";
}
args.success = (data, textStatus, xhr) => {
if (xhr.getResponseHeader('Discourse-Readonly')) {
Ember.run(() => Discourse.Site.currentProp('isReadOnly', true));
}
if (args.returnXHR) {
data = { result: data, xhr: xhr };
}
Ember.run(null, resolve, data);
};
args.error = (xhr, textStatus, errorThrown) => {
// note: for bad CSRF we don't loop an extra request right away.
// this allows us to eliminate the possibility of having a loop.
if (xhr.status === 403 && xhr.responseText === "['BAD CSRF']") {
Discourse.Session.current().set('csrfToken', null);
}
// If it's a parsererror, don't reject
if (xhr.status === 200) return args.success(xhr);
// Fill in some extra info
xhr.jqTextStatus = textStatus;
xhr.requestedUrl = url;
Ember.run(null, reject, {
jqXHR: xhr,
textStatus: textStatus,
errorThrown: errorThrown
});
};
// We default to JSON on GET. If we don't, sometimes if the server doesn't return the proper header
// it will not be parsed as an object.
if (!args.type) args.type = 'GET';
if (!args.dataType && args.type.toUpperCase() === 'GET') args.dataType = 'json';
if (args.dataType === "script") {
args.headers['Discourse-Script'] = true;
}
if (args.type === 'GET' && args.cache !== true) {
args.cache = false;
}
ajaxObj = $.ajax(Discourse.getURL(url), args);
};
let promise;
// For cached pages we strip out CSRF tokens, need to round trip to server prior to sending the
// request (bypass for GET, not needed)
if(args.type && args.type.toUpperCase() !== 'GET' && !Discourse.Session.currentProp('csrfToken')){
promise = new Ember.RSVP.Promise((resolve, reject) => {
ajaxObj = $.ajax(Discourse.getURL('/session/csrf'), {cache: false})
.success(result => {
Discourse.Session.currentProp('csrfToken', result.csrf);
performAjax(resolve, reject);
});
});
} else {
promise = new Ember.RSVP.Promise(performAjax);
}
promise.abort = () => {
if (ajaxObj) {
ajaxObj.abort();
}
};
return promise;
}

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import DiscourseURL from 'discourse/lib/url'; import DiscourseURL from 'discourse/lib/url';
import { wantsNewWindow } from 'discourse/lib/intercept-click'; import { wantsNewWindow } from 'discourse/lib/intercept-click';
import { selectedText } from 'discourse/lib/utilities'; import { selectedText } from 'discourse/lib/utilities';
@ -64,7 +65,7 @@ export default {
// if they want to open in a new tab, do an AJAX request // if they want to open in a new tab, do an AJAX request
if (wantsNewWindow(e)) { if (wantsNewWindow(e)) {
Discourse.ajax("/clicks/track", { ajax("/clicks/track", {
data: { data: {
url: href, url: href,
post_id: postId, post_id: postId,
@ -105,7 +106,7 @@ export default {
// If we're on the same site, use the router and track via AJAX // If we're on the same site, use the router and track via AJAX
if (DiscourseURL.isInternal(href) && !$link.hasClass('attachment')) { if (DiscourseURL.isInternal(href) && !$link.hasClass('attachment')) {
Discourse.ajax("/clicks/track", { ajax("/clicks/track", {
data: { data: {
url: href, url: href,
post_id: postId, post_id: postId,

View file

@ -1,5 +1,6 @@
import { ajax } from 'discourse/lib/ajax';
function exportEntityByType(type, entity, args) { function exportEntityByType(type, entity, args) {
return Discourse.ajax("/export_csv/export_entity.json", { return ajax("/export_csv/export_entity.json", {
method: 'POST', method: 'POST',
data: {entity_type: type, entity, args} data: {entity_type: type, entity, args}
}); });

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import { replaceSpan } from 'discourse/lib/category-hashtags'; import { replaceSpan } from 'discourse/lib/category-hashtags';
const validCategoryHashtags = {}; const validCategoryHashtags = {};
@ -41,7 +42,7 @@ export function linkSeenCategoryHashtags($elem) {
}; };
export function fetchUnseenCategoryHashtags(categorySlugs) { export function fetchUnseenCategoryHashtags(categorySlugs) {
return Discourse.ajax("/category_hashtags/check", { data: { category_slugs: categorySlugs } }) return ajax("/category_hashtags/check", { data: { category_slugs: categorySlugs } })
.then((response) => { .then((response) => {
response.valid.forEach((category) => { response.valid.forEach((category) => {
validCategoryHashtags[category.slug] = category.url; validCategoryHashtags[category.slug] = category.url;

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
function replaceSpan($e, username, opts) { function replaceSpan($e, username, opts) {
if (opts && opts.group) { if (opts && opts.group) {
var extra = "", extraClass = ""; var extra = "", extraClass = "";
@ -52,7 +53,7 @@ export function linkSeenMentions($elem, siteSettings) {
} }
export function fetchUnseenMentions($elem, usernames) { export function fetchUnseenMentions($elem, usernames) {
return Discourse.ajax("/users/is_local_username", { data: { usernames } }).then(function(r) { return ajax("/users/is_local_username", { data: { usernames } }).then(function(r) {
found.push.apply(found, r.valid); found.push.apply(found, r.valid);
foundGroups.push.apply(foundGroups, r.valid_groups); foundGroups.push.apply(foundGroups, r.valid_groups);
mentionableGroups.push.apply(mentionableGroups, r.mentionable_groups); mentionableGroups.push.apply(mentionableGroups, r.mentionable_groups);

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import { replaceSpan } from 'discourse/lib/category-hashtags'; import { replaceSpan } from 'discourse/lib/category-hashtags';
import { TAG_HASHTAG_POSTFIX } from 'discourse/lib/tag-hashtags'; import { TAG_HASHTAG_POSTFIX } from 'discourse/lib/tag-hashtags';
@ -42,7 +43,7 @@ export function linkSeenTagHashtags($elem) {
}; };
export function fetchUnseenTagHashtags(tagValues) { export function fetchUnseenTagHashtags(tagValues) {
return Discourse.ajax("/tags/check", { data: { tag_values: tagValues } }) return ajax("/tags/check", { data: { tag_values: tagValues } })
.then((response) => { .then((response) => {
response.valid.forEach((tag) => { response.valid.forEach((tag) => {
validTagHashtags[tag.value] = tag.url; validTagHashtags[tag.value] = tag.url;

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
const _loaded = {}; const _loaded = {};
const _loading = {}; const _loading = {};
@ -58,7 +59,7 @@ export default function loadScript(url, opts) {
if (opts.scriptTag) { if (opts.scriptTag) {
loadWithTag(cdnUrl, cb); loadWithTag(cdnUrl, cb);
} else { } else {
Discourse.ajax({url: cdnUrl, dataType: "script", cache: true}).then(cb); ajax({url: cdnUrl, dataType: "script", cache: true}).then(cb);
} }
}); });
} }

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
// We use this class to track how long posts in a topic are on the screen. // We use this class to track how long posts in a topic are on the screen.
const PAUSE_UNLESS_SCROLLED = 1000 * 60 * 3; const PAUSE_UNLESS_SCROLLED = 1000 * 60 * 3;
const MAX_TRACKING_TIME = 1000 * 60 * 6; const MAX_TRACKING_TIME = 1000 * 60 * 6;
@ -107,7 +108,7 @@ export default class {
if (!$.isEmptyObject(newTimings)) { if (!$.isEmptyObject(newTimings)) {
if (this.currentUser) { if (this.currentUser) {
Discourse.ajax('/topics/timings', { ajax('/topics/timings', {
data: { data: {
timings: newTimings, timings: newTimings,
topic_time: this._topicTime, topic_time: this._topicTime,

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
export function translateResults(results, opts) { export function translateResults(results, opts) {
@ -82,7 +83,7 @@ function searchForTerm(term, opts) {
}; };
} }
var promise = Discourse.ajax('/search/query', { data: data }); var promise = ajax('/search/query', { data: data });
promise.then(function(results){ promise.then(function(results){
return translateResults(results, opts); return translateResults(results, opts);

View file

@ -1,138 +0,0 @@
/**
This mixin provides an 'ajax' method that can be used to perform ajax requests that
respect Discourse paths and the run loop.
**/
var _trackView = false;
var _transientHeader = null;
Discourse.Ajax = Em.Mixin.create({
setTransientHeader: function(k, v) {
_transientHeader = {key: k, value: v};
},
viewTrackingRequired: function() {
_trackView = true;
},
/**
Our own $.ajax method. Makes sure the .then method executes in an Ember runloop
for performance reasons. Also automatically adjusts the URL to support installs
in subfolders.
@method ajax
**/
ajax: function() {
var url, args;
var ajax;
if (arguments.length === 1) {
if (typeof arguments[0] === "string") {
url = arguments[0];
args = {};
} else {
args = arguments[0];
url = args.url;
delete args.url;
}
} else if (arguments.length === 2) {
url = arguments[0];
args = arguments[1];
}
if (args.success || args.error) {
throw "Discourse.ajax should use promises";
}
var performAjax = function(resolve, reject) {
args.headers = args.headers || {};
if (_transientHeader) {
args.headers[_transientHeader.key] = _transientHeader.value;
_transientHeader = null;
}
if (_trackView && (!args.type || args.type === "GET")) {
_trackView = false;
// DON'T CHANGE: rack is prepending "HTTP_" in the header's name
args.headers['Discourse-Track-View'] = "true";
}
args.success = function(data, textStatus, xhr) {
if (xhr.getResponseHeader('Discourse-Readonly')) {
Ember.run(function() {
Discourse.Site.currentProp('isReadOnly', true);
});
}
if (args.returnXHR) {
data = { result: data, xhr: xhr };
}
Ember.run(null, resolve, data);
};
args.error = function(xhr, textStatus, errorThrown) {
// note: for bad CSRF we don't loop an extra request right away.
// this allows us to eliminate the possibility of having a loop.
if (xhr.status === 403 && xhr.responseText === "['BAD CSRF']") {
Discourse.Session.current().set('csrfToken', null);
}
// If it's a parsererror, don't reject
if (xhr.status === 200) return args.success(xhr);
// Fill in some extra info
xhr.jqTextStatus = textStatus;
xhr.requestedUrl = url;
Ember.run(null, reject, {
jqXHR: xhr,
textStatus: textStatus,
errorThrown: errorThrown
});
};
// We default to JSON on GET. If we don't, sometimes if the server doesn't return the proper header
// it will not be parsed as an object.
if (!args.type) args.type = 'GET';
if (!args.dataType && args.type.toUpperCase() === 'GET') args.dataType = 'json';
if (args.dataType === "script") {
args.headers['Discourse-Script'] = true;
}
if (args.type === 'GET' && args.cache !== true) {
args.cache = false;
}
ajax = $.ajax(Discourse.getURL(url), args);
};
var promise;
// For cached pages we strip out CSRF tokens, need to round trip to server prior to sending the
// request (bypass for GET, not needed)
if(args.type && args.type.toUpperCase() !== 'GET' && !Discourse.Session.currentProp('csrfToken')){
promise = new Ember.RSVP.Promise(function(resolve, reject){
ajax = $.ajax(Discourse.getURL('/session/csrf'), {cache: false})
.success(function(result){
Discourse.Session.currentProp('csrfToken', result.csrf);
performAjax(resolve, reject);
});
});
} else {
promise = new Ember.RSVP.Promise(performAjax);
}
promise.abort = function(){
if (ajax) {
ajax.abort();
}
};
return promise;
}
});

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import RestModel from 'discourse/models/rest'; import RestModel from 'discourse/models/rest';
import { popupAjaxError } from 'discourse/lib/ajax-error'; import { popupAjaxError } from 'discourse/lib/ajax-error';
@ -53,7 +54,7 @@ export default RestModel.extend({
// Create our post action // Create our post action
const self = this; const self = this;
return Discourse.ajax("/post_actions", { return ajax("/post_actions", {
type: 'POST', type: 'POST',
data: { data: {
id: this.get('flagTopic') ? this.get('flagTopic.id') : post.get('id'), id: this.get('flagTopic') ? this.get('flagTopic.id') : post.get('id'),
@ -82,7 +83,7 @@ export default RestModel.extend({
this.removeAction(post); this.removeAction(post);
// Remove our post action // Remove our post action
return Discourse.ajax("/post_actions/" + post.get('id'), { return ajax("/post_actions/" + post.get('id'), {
type: 'DELETE', type: 'DELETE',
data: { post_action_type_id: this.get('id') } data: { post_action_type_id: this.get('id') }
}).then(result => { }).then(result => {
@ -92,7 +93,7 @@ export default RestModel.extend({
}, },
deferFlags(post) { deferFlags(post) {
return Discourse.ajax("/post_actions/defer_flags", { return ajax("/post_actions/defer_flags", {
type: "POST", type: "POST",
data: { post_action_type_id: this.get("id"), id: post.get('id') } data: { post_action_type_id: this.get("id"), id: post.get('id') }
}).then(() => this.set('count', 0)); }).then(() => this.set('count', 0));

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import BadgeGrouping from 'discourse/models/badge-grouping'; import BadgeGrouping from 'discourse/models/badge-grouping';
import RestModel from 'discourse/models/rest'; import RestModel from 'discourse/models/rest';
@ -53,7 +54,7 @@ const Badge = RestModel.extend({
requestType = "PUT"; requestType = "PUT";
} }
return Discourse.ajax(url, { return ajax(url, {
type: requestType, type: requestType,
data: data data: data
}).then(function(json) { }).then(function(json) {
@ -72,7 +73,7 @@ const Badge = RestModel.extend({
**/ **/
destroy: function() { destroy: function() {
if (this.get('newBadge')) return Ember.RSVP.resolve(); if (this.get('newBadge')) return Ember.RSVP.resolve();
return Discourse.ajax("/admin/badges/" + this.get('id'), { return ajax("/admin/badges/" + this.get('id'), {
type: "DELETE" type: "DELETE"
}); });
} }
@ -134,7 +135,7 @@ Badge.reopenClass({
if(opts && opts.onlyListable){ if(opts && opts.onlyListable){
listable = "?only_listable=true"; listable = "?only_listable=true";
} }
return Discourse.ajax('/badges.json' + listable).then(function(badgesJson) { return ajax('/badges.json' + listable).then(function(badgesJson) {
return Badge.createFromJson(badgesJson); return Badge.createFromJson(badgesJson);
}); });
}, },
@ -147,7 +148,7 @@ Badge.reopenClass({
@returns {Promise} a promise that resolves to a `Badge` @returns {Promise} a promise that resolves to a `Badge`
**/ **/
findById: function(id) { findById: function(id) {
return Discourse.ajax("/badges/" + id).then(function(badgeJson) { return ajax("/badges/" + id).then(function(badgeJson) {
return Badge.createFromJson(badgeJson); return Badge.createFromJson(badgeJson);
}); });
} }

View file

@ -1,3 +1,5 @@
import { ajax } from 'discourse/lib/ajax';
const CategoryList = Ember.ArrayProxy.extend({ const CategoryList = Ember.ArrayProxy.extend({
init() { init() {
this.set('content', []); this.set('content', []);
@ -34,7 +36,7 @@ CategoryList.reopenClass({
}, },
listForParent(store, category) { listForParent(store, category) {
return Discourse.ajax(`/categories.json?parent_category_id=${category.get("id")}`).then(result => { return ajax(`/categories.json?parent_category_id=${category.get("id")}`).then(result => {
return CategoryList.create({ return CategoryList.create({
categories: this.categoriesFrom(store, result), categories: this.categoriesFrom(store, result),
parentCategory: category parentCategory: category
@ -43,7 +45,7 @@ CategoryList.reopenClass({
}, },
list(store) { list(store) {
const getCategories = () => Discourse.ajax("/categories.json"); const getCategories = () => ajax("/categories.json");
return PreloadStore.getAndRemove("categories_list", getCategories).then(result => { return PreloadStore.getAndRemove("categories_list", getCategories).then(result => {
return CategoryList.create({ return CategoryList.create({
categories: this.categoriesFrom(store, result), categories: this.categoriesFrom(store, result),

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import RestModel from 'discourse/models/rest'; import RestModel from 'discourse/models/rest';
import { on } from 'ember-addons/ember-computed-decorators'; import { on } from 'ember-addons/ember-computed-decorators';
import PermissionType from 'discourse/models/permission-type'; import PermissionType from 'discourse/models/permission-type';
@ -67,7 +68,7 @@ const Category = RestModel.extend({
url = "/categories/" + this.get('id'); url = "/categories/" + this.get('id');
} }
return Discourse.ajax(url, { return ajax(url, {
data: { data: {
name: this.get('name'), name: this.get('name'),
slug: this.get('slug'), slug: this.get('slug'),
@ -103,7 +104,7 @@ const Category = RestModel.extend({
}.property("permissions"), }.property("permissions"),
destroy: function() { destroy: function() {
return Discourse.ajax("/categories/" + (this.get('id') || this.get('slug')), { type: 'DELETE' }); return ajax("/categories/" + (this.get('id') || this.get('slug')), { type: 'DELETE' });
}, },
addPermission: function(permission){ addPermission: function(permission){
@ -170,7 +171,7 @@ const Category = RestModel.extend({
setNotification: function(notification_level) { setNotification: function(notification_level) {
var url = "/category/" + this.get('id')+"/notifications"; var url = "/category/" + this.get('id')+"/notifications";
this.set('notification_level', notification_level); this.set('notification_level', notification_level);
return Discourse.ajax(url, { return ajax(url, {
data: { data: {
notification_level: notification_level notification_level: notification_level
}, },
@ -285,11 +286,11 @@ Category.reopenClass({
}, },
reloadById(id) { reloadById(id) {
return Discourse.ajax(`/c/${id}/show.json`); return ajax(`/c/${id}/show.json`);
}, },
reloadBySlug(slug, parentSlug) { reloadBySlug(slug, parentSlug) {
return parentSlug ? Discourse.ajax(`/c/${parentSlug}/${slug}/find_by_slug.json`) : Discourse.ajax(`/c/${slug}/find_by_slug.json`); return parentSlug ? ajax(`/c/${parentSlug}/${slug}/find_by_slug.json`) : ajax(`/c/${slug}/find_by_slug.json`);
}, },
search(term, opts) { search(term, opts) {

View file

@ -1,9 +1,10 @@
import { ajax } from 'discourse/lib/ajax';
const Draft = Discourse.Model.extend(); const Draft = Discourse.Model.extend();
Draft.reopenClass({ Draft.reopenClass({
clear(key, sequence) { clear(key, sequence) {
return Discourse.ajax("/draft.json", { return ajax("/draft.json", {
type: 'DELETE', type: 'DELETE',
data: { data: {
draft_key: key, draft_key: key,
@ -13,7 +14,7 @@ Draft.reopenClass({
}, },
get(key) { get(key) {
return Discourse.ajax('/draft.json', { return ajax('/draft.json', {
data: { draft_key: key }, data: { draft_key: key },
dataType: 'json' dataType: 'json'
}); });
@ -26,7 +27,7 @@ Draft.reopenClass({
save(key, sequence, data) { save(key, sequence, data) {
data = typeof data === "string" ? data : JSON.stringify(data); data = typeof data === "string" ? data : JSON.stringify(data);
return Discourse.ajax("/draft.json", { return ajax("/draft.json", {
type: 'POST', type: 'POST',
data: { data: {
draft_key: key, draft_key: key,

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import computed from 'ember-addons/ember-computed-decorators'; import computed from 'ember-addons/ember-computed-decorators';
const Group = Discourse.Model.extend({ const Group = Discourse.Model.extend({
@ -49,7 +50,7 @@ const Group = Discourse.Model.extend({
removeOwner(member) { removeOwner(member) {
var self = this; var self = this;
return Discourse.ajax('/admin/groups/' + this.get('id') + '/owners.json', { return ajax('/admin/groups/' + this.get('id') + '/owners.json', {
type: "DELETE", type: "DELETE",
data: { user_id: member.get("id") } data: { user_id: member.get("id") }
}).then(function() { }).then(function() {
@ -60,7 +61,7 @@ const Group = Discourse.Model.extend({
removeMember(member) { removeMember(member) {
var self = this; var self = this;
return Discourse.ajax('/groups/' + this.get('id') + '/members.json', { return ajax('/groups/' + this.get('id') + '/members.json', {
type: "DELETE", type: "DELETE",
data: { user_id: member.get("id") } data: { user_id: member.get("id") }
}).then(function() { }).then(function() {
@ -71,7 +72,7 @@ const Group = Discourse.Model.extend({
addMembers(usernames) { addMembers(usernames) {
var self = this; var self = this;
return Discourse.ajax('/groups/' + this.get('id') + '/members.json', { return ajax('/groups/' + this.get('id') + '/members.json', {
type: "PUT", type: "PUT",
data: { usernames: usernames } data: { usernames: usernames }
}).then(function() { }).then(function() {
@ -81,7 +82,7 @@ const Group = Discourse.Model.extend({
addOwners(usernames) { addOwners(usernames) {
var self = this; var self = this;
return Discourse.ajax('/admin/groups/' + this.get('id') + '/owners.json', { return ajax('/admin/groups/' + this.get('id') + '/owners.json', {
type: "PUT", type: "PUT",
data: { usernames: usernames } data: { usernames: usernames }
}).then(function() { }).then(function() {
@ -105,18 +106,18 @@ const Group = Discourse.Model.extend({
create() { create() {
var self = this; var self = this;
return Discourse.ajax("/admin/groups", { type: "POST", data: this.asJSON() }).then(function(resp) { return ajax("/admin/groups", { type: "POST", data: this.asJSON() }).then(function(resp) {
self.set('id', resp.basic_group.id); self.set('id', resp.basic_group.id);
}); });
}, },
save() { save() {
return Discourse.ajax("/admin/groups/" + this.get('id'), { type: "PUT", data: this.asJSON() }); return ajax("/admin/groups/" + this.get('id'), { type: "PUT", data: this.asJSON() });
}, },
destroy() { destroy() {
if (!this.get('id')) { return; } if (!this.get('id')) { return; }
return Discourse.ajax("/admin/groups/" + this.get('id'), { type: "DELETE" }); return ajax("/admin/groups/" + this.get('id'), { type: "DELETE" });
}, },
findPosts(opts) { findPosts(opts) {
@ -127,7 +128,7 @@ const Group = Discourse.Model.extend({
var data = {}; var data = {};
if (opts.beforePostId) { data.before_post_id = opts.beforePostId; } if (opts.beforePostId) { data.before_post_id = opts.beforePostId; }
return Discourse.ajax(`/groups/${this.get('name')}/${type}.json`, { data: data }).then(posts => { return ajax(`/groups/${this.get('name')}/${type}.json`, { data: data }).then(posts => {
return posts.map(p => { return posts.map(p => {
p.user = Discourse.User.create(p.user); p.user = Discourse.User.create(p.user);
p.topic = Discourse.Topic.create(p.topic); p.topic = Discourse.Topic.create(p.topic);
@ -138,7 +139,7 @@ const Group = Discourse.Model.extend({
setNotification(notification_level) { setNotification(notification_level) {
this.set("notification_level", notification_level); this.set("notification_level", notification_level);
return Discourse.ajax(`/groups/${this.get("name")}/notifications`, { return ajax(`/groups/${this.get("name")}/notifications`, {
data: { notification_level }, data: { notification_level },
type: "POST" type: "POST"
}); });
@ -147,21 +148,21 @@ const Group = Discourse.Model.extend({
Group.reopenClass({ Group.reopenClass({
findAll(opts) { findAll(opts) {
return Discourse.ajax("/admin/groups.json", { data: opts }).then(function (groups){ return ajax("/admin/groups.json", { data: opts }).then(function (groups){
return groups.map(g => Group.create(g)); return groups.map(g => Group.create(g));
}); });
}, },
findGroupCounts(name) { findGroupCounts(name) {
return Discourse.ajax("/groups/" + name + "/counts.json").then(result => Em.Object.create(result.counts)); return ajax("/groups/" + name + "/counts.json").then(result => Em.Object.create(result.counts));
}, },
find(name) { find(name) {
return Discourse.ajax("/groups/" + name + ".json").then(result => Group.create(result.basic_group)); return ajax("/groups/" + name + ".json").then(result => Group.create(result.basic_group));
}, },
loadMembers(name, offset, limit) { loadMembers(name, offset, limit) {
return Discourse.ajax('/groups/' + name + '/members.json', { return ajax('/groups/' + name + '/members.json', {
data: { data: {
limit: limit || 50, limit: limit || 50,
offset: offset || 0 offset: offset || 0

View file

@ -1,9 +1,10 @@
import { ajax } from 'discourse/lib/ajax';
import { popupAjaxError } from 'discourse/lib/ajax-error'; import { popupAjaxError } from 'discourse/lib/ajax-error';
const Invite = Discourse.Model.extend({ const Invite = Discourse.Model.extend({
rescind() { rescind() {
Discourse.ajax('/invites', { ajax('/invites', {
type: 'DELETE', type: 'DELETE',
data: { email: this.get('email') } data: { email: this.get('email') }
}); });
@ -12,7 +13,7 @@ const Invite = Discourse.Model.extend({
reinvite() { reinvite() {
const self = this; const self = this;
return Discourse.ajax('/invites/reinvite', { return ajax('/invites/reinvite', {
type: 'POST', type: 'POST',
data: { email: this.get('email') } data: { email: this.get('email') }
}).then(function() { }).then(function() {
@ -40,7 +41,7 @@ Invite.reopenClass({
if (!Em.isNone(search)) { data.search = search; } if (!Em.isNone(search)) { data.search = search; }
data.offset = offset || 0; data.offset = offset || 0;
return Discourse.ajax("/users/" + user.get('username_lower') + "/invited.json", {data}).then(function (result) { return ajax("/users/" + user.get('username_lower') + "/invited.json", {data}).then(function (result) {
result.invites = result.invites.map(function (i) { result.invites = result.invites.map(function (i) {
return Invite.create(i); return Invite.create(i);
}); });
@ -51,11 +52,11 @@ Invite.reopenClass({
findInvitedCount(user) { findInvitedCount(user) {
if (!user) { return Em.RSVP.resolve(); } if (!user) { return Em.RSVP.resolve(); }
return Discourse.ajax("/users/" + user.get('username_lower') + "/invited_count.json").then(result => Em.Object.create(result.counts)); return ajax("/users/" + user.get('username_lower') + "/invited_count.json").then(result => Em.Object.create(result.counts));
}, },
reinviteAll() { reinviteAll() {
return Discourse.ajax('/invites/reinvite-all', { type: 'POST' }); return ajax('/invites/reinvite-all', { type: 'POST' });
} }
}); });

View file

@ -1,8 +1,9 @@
import { ajax } from 'discourse/lib/ajax';
const LivePostCounts = Discourse.Model.extend({}); const LivePostCounts = Discourse.Model.extend({});
LivePostCounts.reopenClass({ LivePostCounts.reopenClass({
find() { find() {
return Discourse.ajax("/about/live_post_counts.json").then(result => LivePostCounts.create(result)); return ajax("/about/live_post_counts.json").then(result => LivePostCounts.create(result));
} }
}); });

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import DiscourseURL from 'discourse/lib/url'; import DiscourseURL from 'discourse/lib/url';
import RestModel from 'discourse/models/rest'; import RestModel from 'discourse/models/rest';
import PostsWithPlaceholders from 'discourse/lib/posts-with-placeholders'; import PostsWithPlaceholders from 'discourse/lib/posts-with-placeholders';
@ -455,7 +456,7 @@ export default RestModel.extend({
const url = "/posts/" + postId; const url = "/posts/" + postId;
const store = this.store; const store = this.store;
return Discourse.ajax(url).then(p => this.storePost(store.createRecord('post', p))); return ajax(url).then(p => this.storePost(store.createRecord('post', p)));
}, },
/** /**
@ -497,7 +498,7 @@ export default RestModel.extend({
// need to insert into stream // need to insert into stream
const url = "/posts/" + postId; const url = "/posts/" + postId;
const store = this.store; const store = this.store;
return Discourse.ajax(url).then(p => { return ajax(url).then(p => {
const post = store.createRecord('post', p); const post = store.createRecord('post', p);
const stream = this.get("stream"); const stream = this.get("stream");
const posts = this.get("posts"); const posts = this.get("posts");
@ -538,7 +539,7 @@ export default RestModel.extend({
const url = "/posts/" + postId; const url = "/posts/" + postId;
const store = this.store; const store = this.store;
return Discourse.ajax(url).then(p => { return ajax(url).then(p => {
this.storePost(store.createRecord('post', p)); this.storePost(store.createRecord('post', p));
}).catch(() => { }).catch(() => {
this.removePosts([existing]); this.removePosts([existing]);
@ -555,7 +556,7 @@ export default RestModel.extend({
if (existing && existing.updated_at !== updatedAt) { if (existing && existing.updated_at !== updatedAt) {
const url = "/posts/" + postId; const url = "/posts/" + postId;
const store = this.store; const store = this.store;
return Discourse.ajax(url).then(p => this.storePost(store.createRecord('post', p))); return ajax(url).then(p => this.storePost(store.createRecord('post', p)));
} }
return resolved; return resolved;
}, },
@ -727,7 +728,7 @@ export default RestModel.extend({
const url = "/t/" + this.get('topic.id') + "/posts.json"; const url = "/t/" + this.get('topic.id') + "/posts.json";
const data = { post_ids: postIds }; const data = { post_ids: postIds };
const store = this.store; const store = this.store;
return Discourse.ajax(url, {data}).then(result => { return ajax(url, {data}).then(result => {
const posts = Ember.get(result, "post_stream.posts"); const posts = Ember.get(result, "post_stream.posts");
if (posts) { if (posts) {
posts.forEach(p => this.storePost(store.createRecord('post', p))); posts.forEach(p => this.storePost(store.createRecord('post', p)));

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import RestModel from 'discourse/models/rest'; import RestModel from 'discourse/models/rest';
import { popupAjaxError } from 'discourse/lib/ajax-error'; import { popupAjaxError } from 'discourse/lib/ajax-error';
import ActionSummary from 'discourse/models/action-summary'; import ActionSummary from 'discourse/models/action-summary';
@ -67,7 +68,7 @@ const Post = RestModel.extend({
const data = {}; const data = {};
data[field] = value; data[field] = value;
return Discourse.ajax(`/posts/${this.get('id')}/${field}`, { type: 'PUT', data }).then(() => { return ajax(`/posts/${this.get('id')}/${field}`, { type: 'PUT', data }).then(() => {
this.set(field, value); this.set(field, value);
this.incrementProperty("version"); this.incrementProperty("version");
}).catch(popupAjaxError); }).catch(popupAjaxError);
@ -119,7 +120,7 @@ const Post = RestModel.extend({
// Expands the first post's content, if embedded and shortened. // Expands the first post's content, if embedded and shortened.
expand() { expand() {
const self = this; const self = this;
return Discourse.ajax("/posts/" + this.get('id') + "/expand-embed").then(function(post) { return ajax("/posts/" + this.get('id') + "/expand-embed").then(function(post) {
self.set('cooked', "<section class='expanded-embed'>" + post.cooked + "</section>" ); self.set('cooked', "<section class='expanded-embed'>" + post.cooked + "</section>" );
}); });
}, },
@ -136,7 +137,7 @@ const Post = RestModel.extend({
can_delete: false can_delete: false
}); });
return Discourse.ajax("/posts/" + (this.get('id')) + "/recover", { type: 'PUT', cache: false }).then(function(data){ return ajax("/posts/" + (this.get('id')) + "/recover", { type: 'PUT', cache: false }).then(function(data){
post.setProperties({ post.setProperties({
cooked: data.cooked, cooked: data.cooked,
raw: data.raw, raw: data.raw,
@ -198,7 +199,7 @@ const Post = RestModel.extend({
destroy(deletedBy) { destroy(deletedBy) {
this.setDeletedState(deletedBy); this.setDeletedState(deletedBy);
return Discourse.ajax("/posts/" + this.get('id'), { return ajax("/posts/" + this.get('id'), {
data: { context: window.location.pathname }, data: { context: window.location.pathname },
type: 'DELETE' type: 'DELETE'
}); });
@ -232,17 +233,17 @@ const Post = RestModel.extend({
}, },
expandHidden() { expandHidden() {
return Discourse.ajax("/posts/" + this.get('id') + "/cooked.json").then(result => { return ajax("/posts/" + this.get('id') + "/cooked.json").then(result => {
this.setProperties({ cooked: result.cooked, cooked_hidden: false }); this.setProperties({ cooked: result.cooked, cooked_hidden: false });
}); });
}, },
rebake() { rebake() {
return Discourse.ajax("/posts/" + this.get("id") + "/rebake", { type: "PUT" }); return ajax("/posts/" + this.get("id") + "/rebake", { type: "PUT" });
}, },
unhide() { unhide() {
return Discourse.ajax("/posts/" + this.get("id") + "/unhide", { type: "PUT" }); return ajax("/posts/" + this.get("id") + "/unhide", { type: "PUT" });
}, },
toggleBookmark() { toggleBookmark() {
@ -277,7 +278,7 @@ const Post = RestModel.extend({
}, },
revertToRevision(version) { revertToRevision(version) {
return Discourse.ajax(`/posts/${this.get('id')}/revisions/${version}/revert`, { type: 'PUT' }); return ajax(`/posts/${this.get('id')}/revisions/${version}/revert`, { type: 'PUT' });
} }
}); });
@ -311,14 +312,14 @@ Post.reopenClass({
}, },
updateBookmark(postId, bookmarked) { updateBookmark(postId, bookmarked) {
return Discourse.ajax("/posts/" + postId + "/bookmark", { return ajax("/posts/" + postId + "/bookmark", {
type: 'PUT', type: 'PUT',
data: { bookmarked: bookmarked } data: { bookmarked: bookmarked }
}); });
}, },
deleteMany(selectedPosts, selectedReplies) { deleteMany(selectedPosts, selectedReplies) {
return Discourse.ajax("/posts/destroy_many", { return ajax("/posts/destroy_many", {
type: 'DELETE', type: 'DELETE',
data: { data: {
post_ids: selectedPosts.map(function(p) { return p.get('id'); }), post_ids: selectedPosts.map(function(p) { return p.get('id'); }),
@ -328,27 +329,27 @@ Post.reopenClass({
}, },
loadRevision(postId, version) { loadRevision(postId, version) {
return Discourse.ajax("/posts/" + postId + "/revisions/" + version + ".json") return ajax("/posts/" + postId + "/revisions/" + version + ".json")
.then(result => Ember.Object.create(result)); .then(result => Ember.Object.create(result));
}, },
hideRevision(postId, version) { hideRevision(postId, version) {
return Discourse.ajax("/posts/" + postId + "/revisions/" + version + "/hide", { type: 'PUT' }); return ajax("/posts/" + postId + "/revisions/" + version + "/hide", { type: 'PUT' });
}, },
showRevision(postId, version) { showRevision(postId, version) {
return Discourse.ajax("/posts/" + postId + "/revisions/" + version + "/show", { type: 'PUT' }); return ajax("/posts/" + postId + "/revisions/" + version + "/show", { type: 'PUT' });
}, },
loadQuote(postId) { loadQuote(postId) {
return Discourse.ajax("/posts/" + postId + ".json").then(result => { return ajax("/posts/" + postId + ".json").then(result => {
const post = Discourse.Post.create(result); const post = Discourse.Post.create(result);
return Quote.build(post, post.get('raw'), {raw: true, full: true}); return Quote.build(post, post.get('raw'), {raw: true, full: true});
}); });
}, },
loadRawEmail(postId) { loadRawEmail(postId) {
return Discourse.ajax(`/posts/${postId}/raw-email.json`); return ajax(`/posts/${postId}/raw-email.json`);
} }
}); });

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
const StaticPage = Ember.Object.extend(); const StaticPage = Ember.Object.extend();
StaticPage.reopenClass({ StaticPage.reopenClass({
@ -11,7 +12,7 @@ StaticPage.reopenClass({
text = text.match(/<!-- preload-content: -->((?:.|[\n\r])*)<!-- :preload-content -->/)[1]; text = text.match(/<!-- preload-content: -->((?:.|[\n\r])*)<!-- :preload-content -->/)[1];
resolve(StaticPage.create({path: path, html: text})); resolve(StaticPage.create({path: path, html: text}));
} else { } else {
Discourse.ajax(path + ".html", {dataType: 'html'}).then(function (result) { ajax(path + ".html", {dataType: 'html'}).then(function (result) {
resolve(StaticPage.create({path: path, html: result})); resolve(StaticPage.create({path: path, html: result}));
}); });
} }

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import RestModel from 'discourse/models/rest'; import RestModel from 'discourse/models/rest';
import ResultSet from 'discourse/models/result-set'; import ResultSet from 'discourse/models/result-set';
@ -114,7 +115,7 @@ export default Ember.Object.extend({
refreshResults(resultSet, type, url) { refreshResults(resultSet, type, url) {
const self = this; const self = this;
return Discourse.ajax(url).then(result => { return ajax(url).then(result => {
const typeName = Ember.String.underscore(self.pluralize(type)); const typeName = Ember.String.underscore(self.pluralize(type));
const content = result[typeName].map(obj => self._hydrate(type, obj, result)); const content = result[typeName].map(obj => self._hydrate(type, obj, result));
resultSet.set('content', content); resultSet.set('content', content);
@ -124,7 +125,7 @@ export default Ember.Object.extend({
appendResults(resultSet, type, url) { appendResults(resultSet, type, url) {
const self = this; const self = this;
return Discourse.ajax(url).then(function(result) { return ajax(url).then(function(result) {
const typeName = Ember.String.underscore(self.pluralize(type)), const typeName = Ember.String.underscore(self.pluralize(type)),
totalRows = result["total_rows_" + typeName] || result.get('totalRows'), totalRows = result["total_rows_" + typeName] || result.get('totalRows'),
loadMoreUrl = result["load_more_" + typeName], loadMoreUrl = result["load_more_" + typeName],

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import RestModel from 'discourse/models/rest'; import RestModel from 'discourse/models/rest';
import computed from 'ember-addons/ember-computed-decorators'; import computed from 'ember-addons/ember-computed-decorators';
@ -17,7 +18,7 @@ const TagGroup = RestModel.extend({
this.set('savingStatus', I18n.t('saving')); this.set('savingStatus', I18n.t('saving'));
this.set('saving', true); this.set('saving', true);
return Discourse.ajax(url, { return ajax(url, {
data: { data: {
name: this.get('name'), name: this.get('name'),
tag_names: this.get('tag_names'), tag_names: this.get('tag_names'),
@ -33,7 +34,7 @@ const TagGroup = RestModel.extend({
}, },
destroy() { destroy() {
return Discourse.ajax("/tag_groups/" + this.get('id'), {type: "DELETE"}); return ajax("/tag_groups/" + this.get('id'), {type: "DELETE"});
} }
}); });

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
/** /**
A model representing a Topic's details that aren't always present, such as a list of participants. A model representing a Topic's details that aren't always present, such as a list of participants.
When showing topics in lists and such this information should not be required. When showing topics in lists and such this information should not be required.
@ -57,7 +58,7 @@ const TopicDetails = RestModel.extend({
updateNotifications(v) { updateNotifications(v) {
this.set('notification_level', v); this.set('notification_level', v);
this.set('notifications_reason_id', null); this.set('notifications_reason_id', null);
return Discourse.ajax("/t/" + (this.get('topic.id')) + "/notifications", { return ajax("/t/" + (this.get('topic.id')) + "/notifications", {
type: 'POST', type: 'POST',
data: { notification_level: v } data: { notification_level: v }
}); });
@ -67,7 +68,7 @@ const TopicDetails = RestModel.extend({
const groups = this.get('allowed_groups'); const groups = this.get('allowed_groups');
const name = group.name; const name = group.name;
return Discourse.ajax("/t/" + this.get('topic.id') + "/remove-allowed-group", { return ajax("/t/" + this.get('topic.id') + "/remove-allowed-group", {
type: 'PUT', type: 'PUT',
data: { name: name } data: { name: name }
}).then(() => { }).then(() => {
@ -79,7 +80,7 @@ const TopicDetails = RestModel.extend({
const users = this.get('allowed_users'); const users = this.get('allowed_users');
const username = user.get('username'); const username = user.get('username');
return Discourse.ajax("/t/" + this.get('topic.id') + "/remove-allowed-user", { return ajax("/t/" + this.get('topic.id') + "/remove-allowed-user", {
type: 'PUT', type: 'PUT',
data: { username: username } data: { username: username }
}).then(() => { }).then(() => {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import RestModel from 'discourse/models/rest'; import RestModel from 'discourse/models/rest';
import Model from 'discourse/models/model'; import Model from 'discourse/models/model';
@ -60,7 +61,7 @@ const TopicList = RestModel.extend({
this.set('loadingMore', true); this.set('loadingMore', true);
const store = this.store; const store = this.store;
return Discourse.ajax({url: moreUrl}).then(function (result) { return ajax({url: moreUrl}).then(function (result) {
let topicsAdded = 0; let topicsAdded = 0;
if (result) { if (result) {
@ -100,7 +101,7 @@ const TopicList = RestModel.extend({
const url = `${Discourse.getURL("/")}${this.get('filter')}?topic_ids=${topic_ids.join(",")}`; const url = `${Discourse.getURL("/")}${this.get('filter')}?topic_ids=${topic_ids.join(",")}`;
const store = this.store; const store = this.store;
return Discourse.ajax({ url }).then(result => { return ajax({ url }).then(result => {
let i = 0; let i = 0;
topicList.forEachNew(topicsFrom(result, store), function(t) { topicList.forEachNew(topicsFrom(result, store), function(t) {
// highlight the first of the new topics so we can get a visual feedback // highlight the first of the new topics so we can get a visual feedback

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import { flushMap } from 'discourse/models/store'; import { flushMap } from 'discourse/models/store';
import RestModel from 'discourse/models/rest'; import RestModel from 'discourse/models/rest';
import { propertyEqual } from 'discourse/lib/computed'; import { propertyEqual } from 'discourse/lib/computed';
@ -19,7 +20,7 @@ export function loadTopicView(topic, args) {
delete data.store; delete data.store;
return PreloadStore.getAndRemove(`topic_${topicId}`, () => { return PreloadStore.getAndRemove(`topic_${topicId}`, () => {
return Discourse.ajax(jsonUrl, {data}); return ajax(jsonUrl, {data});
}).then(json => { }).then(json => {
topic.updateFromJson(json); topic.updateFromJson(json);
return json; return json;
@ -225,7 +226,7 @@ const Topic = RestModel.extend({
this.set('details.auto_close_at', null); this.set('details.auto_close_at', null);
} }
} }
return Discourse.ajax(this.get('url') + "/status", { return ajax(this.get('url') + "/status", {
type: 'PUT', type: 'PUT',
data: { data: {
status: property, status: property,
@ -237,13 +238,13 @@ const Topic = RestModel.extend({
makeBanner() { makeBanner() {
const self = this; const self = this;
return Discourse.ajax('/t/' + this.get('id') + '/make-banner', { type: 'PUT' }) return ajax('/t/' + this.get('id') + '/make-banner', { type: 'PUT' })
.then(function () { self.set('archetype', 'banner'); }); .then(function () { self.set('archetype', 'banner'); });
}, },
removeBanner() { removeBanner() {
const self = this; const self = this;
return Discourse.ajax('/t/' + this.get('id') + '/remove-banner', { type: 'PUT' }) return ajax('/t/' + this.get('id') + '/remove-banner', { type: 'PUT' })
.then(function () { self.set('archetype', 'regular'); }); .then(function () { self.set('archetype', 'regular'); });
}, },
@ -258,7 +259,7 @@ const Topic = RestModel.extend({
const path = bookmark ? '/bookmark' : '/remove_bookmarks'; const path = bookmark ? '/bookmark' : '/remove_bookmarks';
const toggleBookmarkOnServer = () => { const toggleBookmarkOnServer = () => {
return Discourse.ajax(`/t/${this.get('id')}${path}`, { type: 'PUT' }).then(() => { return ajax(`/t/${this.get('id')}${path}`, { type: 'PUT' }).then(() => {
this.toggleProperty('bookmarked'); this.toggleProperty('bookmarked');
if (bookmark && firstPost) { if (bookmark && firstPost) {
firstPost.set('bookmarked', true); firstPost.set('bookmarked', true);
@ -314,21 +315,21 @@ const Topic = RestModel.extend({
}, },
createGroupInvite(group) { createGroupInvite(group) {
return Discourse.ajax("/t/" + this.get('id') + "/invite-group", { return ajax("/t/" + this.get('id') + "/invite-group", {
type: 'POST', type: 'POST',
data: { group } data: { group }
}); });
}, },
createInvite(user, group_names, custom_message) { createInvite(user, group_names, custom_message) {
return Discourse.ajax("/t/" + this.get('id') + "/invite", { return ajax("/t/" + this.get('id') + "/invite", {
type: 'POST', type: 'POST',
data: { user, group_names, custom_message } data: { user, group_names, custom_message }
}); });
}, },
generateInviteLink: function(email, groupNames, topicId) { generateInviteLink: function(email, groupNames, topicId) {
return Discourse.ajax('/invites/link', { return ajax('/invites/link', {
type: 'POST', type: 'POST',
data: {email: email, group_names: groupNames, topic_id: topicId} data: {email: email, group_names: groupNames, topic_id: topicId}
}); });
@ -342,7 +343,7 @@ const Topic = RestModel.extend({
'details.can_delete': false, 'details.can_delete': false,
'details.can_recover': true 'details.can_recover': true
}); });
return Discourse.ajax("/t/" + this.get('id'), { return ajax("/t/" + this.get('id'), {
data: { context: window.location.pathname }, data: { context: window.location.pathname },
type: 'DELETE' type: 'DELETE'
}); });
@ -356,7 +357,7 @@ const Topic = RestModel.extend({
'details.can_delete': true, 'details.can_delete': true,
'details.can_recover': false 'details.can_recover': false
}); });
return Discourse.ajax("/t/" + this.get('id') + "/recover", { type: 'PUT' }); return ajax("/t/" + this.get('id') + "/recover", { type: 'PUT' });
}, },
// Update our attributes from a JSON result // Update our attributes from a JSON result
@ -372,7 +373,7 @@ const Topic = RestModel.extend({
reload() { reload() {
const self = this; const self = this;
return Discourse.ajax('/t/' + this.get('id'), { type: 'GET' }).then(function(topic_json) { return ajax('/t/' + this.get('id'), { type: 'GET' }).then(function(topic_json) {
self.updateFromJson(topic_json); self.updateFromJson(topic_json);
}); });
}, },
@ -388,7 +389,7 @@ const Topic = RestModel.extend({
topic.set('pinned', false); topic.set('pinned', false);
topic.set('unpinned', true); topic.set('unpinned', true);
Discourse.ajax("/t/" + this.get('id') + "/clear-pin", { ajax("/t/" + this.get('id') + "/clear-pin", {
type: 'PUT' type: 'PUT'
}).then(null, function() { }).then(null, function() {
// On error, put the pin back // On error, put the pin back
@ -412,7 +413,7 @@ const Topic = RestModel.extend({
topic.set('pinned', true); topic.set('pinned', true);
topic.set('unpinned', false); topic.set('unpinned', false);
Discourse.ajax("/t/" + this.get('id') + "/re-pin", { ajax("/t/" + this.get('id') + "/re-pin", {
type: 'PUT' type: 'PUT'
}).then(null, function() { }).then(null, function() {
// On error, put the pin back // On error, put the pin back
@ -434,7 +435,7 @@ const Topic = RestModel.extend({
archiveMessage() { archiveMessage() {
this.set("archiving", true); this.set("archiving", true);
var promise = Discourse.ajax(`/t/${this.get('id')}/archive-message`, {type: 'PUT'}); var promise = ajax(`/t/${this.get('id')}/archive-message`, {type: 'PUT'});
promise.then((msg)=> { promise.then((msg)=> {
this.set('message_archived', true); this.set('message_archived', true);
@ -448,7 +449,7 @@ const Topic = RestModel.extend({
moveToInbox() { moveToInbox() {
this.set("archiving", true); this.set("archiving", true);
var promise = Discourse.ajax(`/t/${this.get('id')}/move-to-inbox`, {type: 'PUT'}); var promise = ajax(`/t/${this.get('id')}/move-to-inbox`, {type: 'PUT'});
promise.then((msg)=> { promise.then((msg)=> {
this.set('message_archived', false); this.set('message_archived', false);
@ -461,7 +462,7 @@ const Topic = RestModel.extend({
}, },
convertTopic(type) { convertTopic(type) {
return Discourse.ajax(`/t/${this.get('id')}/convert-topic/${type}`, {type: 'PUT'}).then(() => { return ajax(`/t/${this.get('id')}/convert-topic/${type}`, {type: 'PUT'}).then(() => {
window.location.reload(); window.location.reload();
}).catch(popupAjaxError); }).catch(popupAjaxError);
} }
@ -511,7 +512,7 @@ Topic.reopenClass({
} }
}); });
return Discourse.ajax(topic.get('url'), { type: 'PUT', data: props }).then(function(result) { return ajax(topic.get('url'), { type: 'PUT', data: props }).then(function(result) {
// The title can be cleaned up server side // The title can be cleaned up server side
props.title = result.basic_topic.title; props.title = result.basic_topic.title;
props.fancy_title = result.basic_topic.fancy_title; props.fancy_title = result.basic_topic.fancy_title;
@ -558,11 +559,11 @@ Topic.reopenClass({
} }
// Check the preload store. If not, load it via JSON // Check the preload store. If not, load it via JSON
return Discourse.ajax(url + ".json", {data: data}); return ajax(url + ".json", {data: data});
}, },
changeOwners(topicId, opts) { changeOwners(topicId, opts) {
const promise = Discourse.ajax("/t/" + topicId + "/change-owner", { const promise = ajax("/t/" + topicId + "/change-owner", {
type: 'POST', type: 'POST',
data: opts data: opts
}).then(function (result) { }).then(function (result) {
@ -573,7 +574,7 @@ Topic.reopenClass({
}, },
changeTimestamp(topicId, timestamp) { changeTimestamp(topicId, timestamp) {
const promise = Discourse.ajax("/t/" + topicId + '/change-timestamp', { const promise = ajax("/t/" + topicId + '/change-timestamp', {
type: 'PUT', type: 'PUT',
data: { timestamp: timestamp }, data: { timestamp: timestamp },
}).then(function(result) { }).then(function(result) {
@ -584,7 +585,7 @@ Topic.reopenClass({
}, },
bulkOperation(topics, operation) { bulkOperation(topics, operation) {
return Discourse.ajax("/topics/bulk", { return ajax("/topics/bulk", {
type: 'PUT', type: 'PUT',
data: { data: {
topic_ids: topics.map(function(t) { return t.get('id'); }), topic_ids: topics.map(function(t) { return t.get('id'); }),
@ -596,18 +597,18 @@ Topic.reopenClass({
bulkOperationByFilter(filter, operation, categoryId) { bulkOperationByFilter(filter, operation, categoryId) {
const data = { filter: filter, operation: operation }; const data = { filter: filter, operation: operation };
if (categoryId) data['category_id'] = categoryId; if (categoryId) data['category_id'] = categoryId;
return Discourse.ajax("/topics/bulk", { return ajax("/topics/bulk", {
type: 'PUT', type: 'PUT',
data: data data: data
}); });
}, },
resetNew() { resetNew() {
return Discourse.ajax("/topics/reset-new", {type: 'PUT'}); return ajax("/topics/reset-new", {type: 'PUT'});
}, },
idForSlug(slug) { idForSlug(slug) {
return Discourse.ajax("/t/id_for/" + slug); return ajax("/t/id_for/" + slug);
} }
}); });
@ -621,11 +622,11 @@ function moveResult(result) {
} }
export function movePosts(topicId, data) { export function movePosts(topicId, data) {
return Discourse.ajax("/t/" + topicId + "/move-posts", { type: 'POST', data }).then(moveResult); return ajax("/t/" + topicId + "/move-posts", { type: 'POST', data }).then(moveResult);
} }
export function mergeTopic(topicId, destinationTopicId) { export function mergeTopic(topicId, destinationTopicId) {
return Discourse.ajax("/t/" + topicId + "/merge-topic", { return ajax("/t/" + topicId + "/merge-topic", {
type: 'POST', type: 'POST',
data: {destination_topic_id: destinationTopicId} data: {destination_topic_id: destinationTopicId}
}).then(moveResult); }).then(moveResult);

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import Badge from 'discourse/models/badge'; import Badge from 'discourse/models/badge';
const UserBadge = Discourse.Model.extend({ const UserBadge = Discourse.Model.extend({
@ -8,7 +9,7 @@ const UserBadge = Discourse.Model.extend({
}.property(), // avoid the extra bindings for now }.property(), // avoid the extra bindings for now
revoke() { revoke() {
return Discourse.ajax("/user_badges/" + this.get('id'), { return ajax("/user_badges/" + this.get('id'), {
type: "DELETE" type: "DELETE"
}); });
} }
@ -89,7 +90,7 @@ UserBadge.reopenClass({
if (options && options.grouped) { if (options && options.grouped) {
url += "?grouped=true"; url += "?grouped=true";
} }
return Discourse.ajax(url).then(function(json) { return ajax(url).then(function(json) {
return UserBadge.createFromJson(json); return UserBadge.createFromJson(json);
}); });
}, },
@ -105,7 +106,7 @@ UserBadge.reopenClass({
if (!options) { options = {}; } if (!options) { options = {}; }
options.badge_id = badgeId; options.badge_id = badgeId;
return Discourse.ajax("/user_badges.json", { return ajax("/user_badges.json", {
data: options data: options
}).then(function(json) { }).then(function(json) {
return UserBadge.createFromJson(json); return UserBadge.createFromJson(json);
@ -121,7 +122,7 @@ UserBadge.reopenClass({
@returns {Promise} a promise that resolves to an instance of `UserBadge`. @returns {Promise} a promise that resolves to an instance of `UserBadge`.
**/ **/
grant: function(badgeId, username, reason) { grant: function(badgeId, username, reason) {
return Discourse.ajax("/user_badges", { return ajax("/user_badges", {
type: "POST", type: "POST",
data: { data: {
username: username, username: username,

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import { url } from 'discourse/lib/computed'; import { url } from 'discourse/lib/computed';
import AdminPost from 'discourse/models/admin-post'; import AdminPost from 'discourse/models/admin-post';
@ -33,7 +34,7 @@ export default Discourse.Model.extend({
this.set("loading", true); this.set("loading", true);
return Discourse.ajax(this.get("url"), { cache: false }).then(function (result) { return ajax(this.get("url"), { cache: false }).then(function (result) {
if (result) { if (result) {
const posts = result.map(function (post) { return AdminPost.create(post); }); const posts = result.map(function (post) { return AdminPost.create(post); });
self.get("content").pushObjects(posts); self.get("content").pushObjects(posts);

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import { url } from 'discourse/lib/computed'; import { url } from 'discourse/lib/computed';
import RestModel from 'discourse/models/rest'; import RestModel from 'discourse/models/rest';
import UserAction from 'discourse/models/user-action'; import UserAction from 'discourse/models/user-action';
@ -67,7 +68,7 @@ export default RestModel.extend({
if (this.get('loading')) { return Ember.RSVP.resolve(); } if (this.get('loading')) { return Ember.RSVP.resolve(); }
this.set('loading', true); this.set('loading', true);
return Discourse.ajax(findUrl, {cache: 'false'}).then( function(result) { return ajax(findUrl, {cache: 'false'}).then( function(result) {
if (result && result.user_actions) { if (result && result.user_actions) {
const copy = Em.A(); const copy = Em.A();
result.user_actions.forEach(function(action) { result.user_actions.forEach(function(action) {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import { url } from 'discourse/lib/computed'; import { url } from 'discourse/lib/computed';
import RestModel from 'discourse/models/rest'; import RestModel from 'discourse/models/rest';
import UserStream from 'discourse/models/user-stream'; import UserStream from 'discourse/models/user-stream';
@ -39,7 +40,7 @@ const User = RestModel.extend({
staff: Em.computed.or('admin', 'moderator'), staff: Em.computed.or('admin', 'moderator'),
destroySession() { destroySession() {
return Discourse.ajax(`/session/${this.get('username')}`, { type: 'DELETE'}); return ajax(`/session/${this.get('username')}`, { type: 'DELETE'});
}, },
@computed("username_lower") @computed("username_lower")
@ -125,14 +126,14 @@ const User = RestModel.extend({
}, },
changeUsername(new_username) { changeUsername(new_username) {
return Discourse.ajax(`/users/${this.get('username_lower')}/preferences/username`, { return ajax(`/users/${this.get('username_lower')}/preferences/username`, {
type: 'PUT', type: 'PUT',
data: { new_username } data: { new_username }
}); });
}, },
changeEmail(email) { changeEmail(email) {
return Discourse.ajax(`/users/${this.get('username_lower')}/preferences/email`, { return ajax(`/users/${this.get('username_lower')}/preferences/email`, {
type: 'PUT', type: 'PUT',
data: { email } data: { email }
}); });
@ -202,7 +203,7 @@ const User = RestModel.extend({
// TODO: We can remove this when migrated fully to rest model. // TODO: We can remove this when migrated fully to rest model.
this.set('isSaving', true); this.set('isSaving', true);
return Discourse.ajax(`/users/${this.get('username_lower')}`, { return ajax(`/users/${this.get('username_lower')}`, {
data: data, data: data,
type: 'PUT' type: 'PUT'
}).then(result => { }).then(result => {
@ -216,7 +217,7 @@ const User = RestModel.extend({
}, },
changePassword() { changePassword() {
return Discourse.ajax("/session/forgot_password", { return ajax("/session/forgot_password", {
dataType: 'json', dataType: 'json',
data: { login: this.get('username') }, data: { login: this.get('username') },
type: 'POST' type: 'POST'
@ -225,7 +226,7 @@ const User = RestModel.extend({
loadUserAction(id) { loadUserAction(id) {
const stream = this.get('stream'); const stream = this.get('stream');
return Discourse.ajax(`/user_actions/${id}.json`, { cache: 'false' }).then(result => { return ajax(`/user_actions/${id}.json`, { cache: 'false' }).then(result => {
if (result && result.user_action) { if (result && result.user_action) {
const ua = result.user_action; const ua = result.user_action;
@ -278,7 +279,7 @@ const User = RestModel.extend({
const user = this; const user = this;
return PreloadStore.getAndRemove(`user_${user.get('username')}`, () => { return PreloadStore.getAndRemove(`user_${user.get('username')}`, () => {
return Discourse.ajax(`/users/${user.get('username')}.json`, { data: options }); return ajax(`/users/${user.get('username')}.json`, { data: options });
}).then(json => { }).then(json => {
if (!Em.isEmpty(json.user.stats)) { if (!Em.isEmpty(json.user.stats)) {
@ -315,13 +316,13 @@ const User = RestModel.extend({
findStaffInfo() { findStaffInfo() {
if (!Discourse.User.currentProp("staff")) { return Ember.RSVP.resolve(null); } if (!Discourse.User.currentProp("staff")) { return Ember.RSVP.resolve(null); }
return Discourse.ajax(`/users/${this.get("username_lower")}/staff-info.json`).then(info => { return ajax(`/users/${this.get("username_lower")}/staff-info.json`).then(info => {
this.setProperties(info); this.setProperties(info);
}); });
}, },
pickAvatar(upload_id, type, avatar_template) { pickAvatar(upload_id, type, avatar_template) {
return Discourse.ajax(`/users/${this.get("username_lower")}/preferences/avatar/pick`, { return ajax(`/users/${this.get("username_lower")}/preferences/avatar/pick`, {
type: 'PUT', type: 'PUT',
data: { upload_id, type } data: { upload_id, type }
}).then(() => this.setProperties({ }).then(() => this.setProperties({
@ -337,14 +338,14 @@ const User = RestModel.extend({
}, },
createInvite(email, group_names, custom_message) { createInvite(email, group_names, custom_message) {
return Discourse.ajax('/invites', { return ajax('/invites', {
type: 'POST', type: 'POST',
data: { email, group_names, custom_message } data: { email, group_names, custom_message }
}); });
}, },
generateInviteLink(email, group_names, topic_id) { generateInviteLink(email, group_names, topic_id) {
return Discourse.ajax('/invites/link', { return ajax('/invites/link', {
type: 'POST', type: 'POST',
data: { email, group_names, topic_id } data: { email, group_names, topic_id }
}); });
@ -377,7 +378,7 @@ const User = RestModel.extend({
"delete": function() { "delete": function() {
if (this.get('can_delete_account')) { if (this.get('can_delete_account')) {
return Discourse.ajax("/users/" + this.get('username'), { return ajax("/users/" + this.get('username'), {
type: 'DELETE', type: 'DELETE',
data: {context: window.location.pathname} data: {context: window.location.pathname}
}); });
@ -388,14 +389,14 @@ const User = RestModel.extend({
dismissBanner(bannerKey) { dismissBanner(bannerKey) {
this.set("dismissed_banner_key", bannerKey); this.set("dismissed_banner_key", bannerKey);
Discourse.ajax(`/users/${this.get('username')}`, { ajax(`/users/${this.get('username')}`, {
type: 'PUT', type: 'PUT',
data: { dismissed_banner_key: bannerKey } data: { dismissed_banner_key: bannerKey }
}); });
}, },
checkEmail() { checkEmail() {
return Discourse.ajax(`/users/${this.get("username_lower")}/emails.json`, { return ajax(`/users/${this.get("username_lower")}/emails.json`, {
type: "PUT", type: "PUT",
data: { context: window.location.pathname } data: { context: window.location.pathname }
}).then(result => { }).then(result => {
@ -409,7 +410,7 @@ const User = RestModel.extend({
}, },
summary() { summary() {
return Discourse.ajax(`/users/${this.get("username_lower")}/summary.json`) return ajax(`/users/${this.get("username_lower")}/summary.json`)
.then(json => { .then(json => {
const summary = json["user_summary"]; const summary = json["user_summary"];
const topicMap = {}; const topicMap = {};
@ -464,7 +465,7 @@ User.reopenClass(Singleton, {
}, },
checkUsername(username, email, for_user_id) { checkUsername(username, email, for_user_id) {
return Discourse.ajax('/users/check_username', { return ajax('/users/check_username', {
data: { username, email, for_user_id } data: { username, email, for_user_id }
}); });
}, },
@ -495,7 +496,7 @@ User.reopenClass(Singleton, {
}, },
createAccount(attrs) { createAccount(attrs) {
return Discourse.ajax("/users", { return ajax("/users", {
data: { data: {
name: attrs.accountName, name: attrs.accountName,
email: attrs.accountEmail, email: attrs.accountEmail,

View file

@ -1,6 +1,7 @@
import { ajax } from 'discourse/lib/ajax';
export default Discourse.Route.extend({ export default Discourse.Route.extend({
model() { model() {
return Discourse.ajax("/about.json").then(result => result.about); return ajax("/about.json").then(result => result.about);
}, },
titleToken() { titleToken() {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import { setting } from 'discourse/lib/computed'; import { setting } from 'discourse/lib/computed';
import logout from 'discourse/lib/logout'; import logout from 'discourse/lib/logout';
import showModal from 'discourse/lib/show-modal'; import showModal from 'discourse/lib/show-modal';
@ -28,13 +29,13 @@ const ApplicationRoute = Discourse.Route.extend(OpenComposer, {
actions: { actions: {
showSearchHelp() { showSearchHelp() {
Discourse.ajax("/static/search_help.html", { dataType: 'html' }).then(model => { ajax("/static/search_help.html", { dataType: 'html' }).then(model => {
showModal('searchHelp', { model }); showModal('searchHelp', { model });
}); });
}, },
toggleAnonymous() { toggleAnonymous() {
Discourse.ajax("/users/toggle-anon", {method: 'POST'}).then(() => { ajax("/users/toggle-anon", {method: 'POST'}).then(() => {
window.location.reload(); window.location.reload();
}); });
}, },

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import { translateResults, getSearchKey, isValidSearchTerm } from "discourse/lib/search"; import { translateResults, getSearchKey, isValidSearchTerm } from "discourse/lib/search";
import Composer from 'discourse/models/composer'; import Composer from 'discourse/models/composer';
@ -25,7 +26,7 @@ export default Discourse.Route.extend({
return PreloadStore.getAndRemove("search", function() { return PreloadStore.getAndRemove("search", function() {
if (isValidSearchTerm(params.q)) { if (isValidSearchTerm(params.q)) {
return Discourse.ajax("/search", { data: args }); return ajax("/search", { data: args });
} else { } else {
return null; return null;
} }

View file

@ -1,5 +1,6 @@
import { ajax } from 'discourse/lib/ajax';
export default Discourse.Route.extend({ export default Discourse.Route.extend({
model: function() { model: function() {
return Discourse.ajax("/404-body", { dataType: 'html' }); return ajax("/404-body", { dataType: 'html' });
} }
}); });

View file

@ -5,6 +5,7 @@ import DiscourseURL from 'discourse/lib/url';
import { h } from 'virtual-dom'; import { h } from 'virtual-dom';
import { emojiUnescape } from 'discourse/lib/text'; import { emojiUnescape } from 'discourse/lib/text';
import { postUrl, escapeExpression } from 'discourse/lib/utilities'; import { postUrl, escapeExpression } from 'discourse/lib/utilities';
import { setTransientHeader } from 'discourse/lib/ajax';
const LIKED_TYPE = 5; const LIKED_TYPE = 5;
const INVITED_TYPE = 8; const INVITED_TYPE = 8;
@ -101,7 +102,7 @@ createWidget('notification-item', {
click(e) { click(e) {
this.attrs.set('read', true); this.attrs.set('read', true);
const id = this.attrs.id; const id = this.attrs.id;
Discourse.setTransientHeader("Discourse-Clear-Notifications", id); setTransientHeader("Discourse-Clear-Notifications", id);
if (document && document.cookie) { if (document && document.cookie) {
document.cookie = `cn=${id}; expires=Fri, 31 Dec 9999 23:59:59 GMT`; document.cookie = `cn=${id}; expires=Fri, 31 Dec 9999 23:59:59 GMT`;
} }

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import { isValidLink } from 'discourse/lib/click-track'; import { isValidLink } from 'discourse/lib/click-track';
import { number } from 'discourse/lib/formatter'; import { number } from 'discourse/lib/formatter';
@ -130,7 +131,7 @@ export default class PostCooked {
const postId = parseInt($aside.data('post'), 10); const postId = parseInt($aside.data('post'), 10);
topicId = parseInt(topicId, 10); topicId = parseInt(topicId, 10);
Discourse.ajax(`/posts/by_number/${topicId}/${postId}`).then(result => { ajax(`/posts/by_number/${topicId}/${postId}`).then(result => {
const div = $("<div class='expanded-quote'></div>"); const div = $("<div class='expanded-quote'></div>");
div.html(result.cooked); div.html(result.cooked);
div.highlight(originalText, {caseSensitive: true, element: 'span', className: 'highlighted'}); div.highlight(originalText, {caseSensitive: true, element: 'span', className: 'highlighted'});

View file

@ -1,4 +1,3 @@
//= require ./discourse/mixins/ajax
//= require ./discourse //= require ./discourse
// Stuff we need to load first // Stuff we need to load first
@ -7,6 +6,7 @@
//= require ./ember-addons/macro-alias //= require ./ember-addons/macro-alias
//= require ./ember-addons/ember-computed-decorators //= require ./ember-addons/ember-computed-decorators
//= require ./discourse/lib/utilities //= require ./discourse/lib/utilities
//= require ./discourse/lib/ajax
//= require ./discourse/lib/text //= require ./discourse/lib/text
//= require ./discourse/lib/hash //= require ./discourse/lib/hash
//= require ./discourse/lib/load-script //= require ./discourse/lib/load-script

View file

@ -10,7 +10,7 @@ const failedCache = {};
// Perform a lookup of a onebox based an anchor element. It will insert a loading // Perform a lookup of a onebox based an anchor element. It will insert a loading
// indicator and remove it when the loading is complete or fails. // indicator and remove it when the loading is complete or fails.
export function load(e, refresh) { export function load(e, refresh, ajax) {
var $elem = $(e); var $elem = $(e);
// If the onebox has loaded, return // If the onebox has loaded, return
@ -34,7 +34,7 @@ export function load(e, refresh) {
$elem.addClass('loading-onebox'); $elem.addClass('loading-onebox');
// Retrieve the onebox // Retrieve the onebox
return Discourse.ajax("/onebox", { return ajax("/onebox", {
dataType: 'html', dataType: 'html',
data: { url, refresh }, data: { url, refresh },
cache: true cache: true

View file

@ -245,6 +245,7 @@ define("discourse/initializers/login-method-#{hash}",
name: "login-method-#{hash}", name: "login-method-#{hash}",
after: "inject-objects", after: "inject-objects",
initialize: function() { initialize: function() {
if (Ember.testing) { return; }
module.register(#{auth_json}); module.register(#{auth_json});
} }
}; };

View file

@ -11,7 +11,7 @@ function initializeDetails(api) {
}; };
}); });
const ComposerController = api.container.lookup("controller:composer"); const ComposerController = api.container.lookupFactory("controller:composer");
ComposerController.reopen({ ComposerController.reopen({
actions: { actions: {
insertDetails() { insertDetails() {
@ -27,7 +27,6 @@ function initializeDetails(api) {
export default { export default {
name: "apply-details", name: "apply-details",
after: 'inject-objects',
initialize() { initialize() {
withPluginApi('0.5', initializeDetails); withPluginApi('0.5', initializeDetails);

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
export default Ember.Component.extend({ export default Ember.Component.extend({
layoutName: "components/poll-voters", layoutName: "components/poll-voters",
tagName: 'ul', tagName: 'ul',
@ -16,7 +17,7 @@ export default Ember.Component.extend({
_fetchUsers() { _fetchUsers() {
this.set("loading", true); this.set("loading", true);
Discourse.ajax("/polls/voters.json", { ajax("/polls/voters.json", {
type: "get", type: "get",
data: { user_ids: this.get("voterIds") } data: { user_ids: this.get("voterIds") }
}).then(result => { }).then(result => {

View file

@ -1,3 +1,4 @@
import { ajax } from 'discourse/lib/ajax';
import { default as computed, observes } from "ember-addons/ember-computed-decorators"; import { default as computed, observes } from "ember-addons/ember-computed-decorators";
export default Ember.Controller.extend({ export default Ember.Controller.extend({
@ -137,7 +138,7 @@ export default Ember.Controller.extend({
this.set("loading", true); this.set("loading", true);
Discourse.ajax("/polls/vote", { ajax("/polls/vote", {
type: "PUT", type: "PUT",
data: { data: {
post_id: this.get("post.id"), post_id: this.get("post.id"),
@ -175,7 +176,7 @@ export default Ember.Controller.extend({
if (confirmed) { if (confirmed) {
self.set("loading", true); self.set("loading", true);
Discourse.ajax("/polls/toggle_status", { ajax("/polls/toggle_status", {
type: "PUT", type: "PUT",
data: { data: {
post_id: self.get("post.id"), post_id: self.get("post.id"),

View file

@ -1,8 +1,8 @@
import { withPluginApi } from 'discourse/lib/plugin-api'; import { withPluginApi } from 'discourse/lib/plugin-api';
import showModal from 'discourse/lib/show-modal'; import showModal from 'discourse/lib/show-modal';
import ComposerController from 'discourse/controllers/composer';
function initializePollUIBuilder(api) { function initializePollUIBuilder(api) {
const ComposerController = api.container.lookupFactory("controller:composer");
ComposerController.reopen({ ComposerController.reopen({
actions: { actions: {
showPollBuilder() { showPollBuilder() {

View file

@ -1,13 +0,0 @@
module("adapter:topic-list");
import { finderFor } from 'discourse/adapters/topic-list';
test("finderFor", function() {
// Mocking instead of using a pretender which decodes the path and thus does
// not reflect the behavior of an actual web server.
var mock = sandbox.mock(Discourse);
mock.expects("ajax").withArgs("/search.json?q=test%25%25");
var finderForFunction = finderFor('search', { q: "test%%" });
finderForFunction();
mock.verify();
});

View file

@ -2,32 +2,23 @@ import { blank, present } from 'helpers/qunit-helpers';
import AdminUser from 'admin/models/admin-user'; import AdminUser from 'admin/models/admin-user';
import ApiKey from 'admin/models/api-key'; import ApiKey from 'admin/models/api-key';
module("Discourse.AdminUser"); module("model:admin-user");
asyncTestDiscourse('generate key', function() {
sandbox.stub(Discourse, 'ajax').returns(Ember.RSVP.resolve({api_key: {id: 1234, key: 'asdfasdf'}}));
test('generate key', function() {
var adminUser = AdminUser.create({id: 333}); var adminUser = AdminUser.create({id: 333});
blank(adminUser.get('api_key'), 'it has no api key by default'); blank(adminUser.get('api_key'), 'it has no api key by default');
adminUser.generateApiKey().then(function() { adminUser.generateApiKey().then(function() {
start();
ok(Discourse.ajax.calledWith("/admin/users/333/generate_api_key", { type: 'POST' }), "it POSTed to the url");
present(adminUser.get('api_key'), 'it has an api_key now'); present(adminUser.get('api_key'), 'it has an api_key now');
}); });
}); });
asyncTestDiscourse('revoke key', function() { test('revoke key', function() {
var apiKey = ApiKey.create({id: 1234, key: 'asdfasdf'}), var apiKey = ApiKey.create({id: 1234, key: 'asdfasdf'}),
adminUser = AdminUser.create({id: 333, api_key: apiKey}); adminUser = AdminUser.create({id: 333, api_key: apiKey});
sandbox.stub(Discourse, 'ajax').returns(Ember.RSVP.resolve());
equal(adminUser.get('api_key'), apiKey, 'it has the api key in the beginning'); equal(adminUser.get('api_key'), apiKey, 'it has the api key in the beginning');
adminUser.revokeApiKey().then(function() { adminUser.revokeApiKey().then(function() {
start();
ok(Discourse.ajax.calledWith("/admin/users/333/revoke_api_key", { type: 'DELETE' }), "it DELETEd to the url");
blank(adminUser.get('api_key'), 'it cleared the api_key'); blank(adminUser.get('api_key'), 'it cleared the api_key');
}); });
}); });

View file

@ -1,48 +0,0 @@
import { present } from 'helpers/qunit-helpers';
import ApiKey from 'admin/models/api-key';
module("Discourse.ApiKey");
test('create', function() {
var apiKey = ApiKey.create({id: 123, user: {id: 345}});
present(apiKey, 'it creates the api key');
present(apiKey.get('user'), 'it creates the user inside');
});
asyncTestDiscourse('find', function() {
sandbox.stub(Discourse, 'ajax').returns(Ember.RSVP.resolve([]));
ApiKey.find().then(function() {
start();
ok(Discourse.ajax.calledWith("/admin/api"), "it GETs the keys");
});
});
asyncTestDiscourse('generateMasterKey', function() {
sandbox.stub(Discourse, 'ajax').returns(Ember.RSVP.resolve({api_key: {}}));
ApiKey.generateMasterKey().then(function() {
start();
ok(Discourse.ajax.calledWith("/admin/api/key", {type: 'POST'}), "it POSTs to create a master key");
});
});
asyncTestDiscourse('regenerate', function() {
var apiKey = ApiKey.create({id: 3456});
sandbox.stub(Discourse, 'ajax').returns(Ember.RSVP.resolve({api_key: {id: 3456}}));
apiKey.regenerate().then(function() {
start();
ok(Discourse.ajax.calledWith("/admin/api/key", {type: 'PUT', data: {id: 3456}}), "it PUTs the key");
});
});
asyncTestDiscourse('revoke', function() {
var apiKey = ApiKey.create({id: 3456});
sandbox.stub(Discourse, 'ajax').returns(Ember.RSVP.resolve([]));
apiKey.revoke().then(function() {
start();
ok(Discourse.ajax.calledWith("/admin/api/key", {type: 'DELETE', data: {id: 3456}}), "it DELETES the key");
});
});

View file

@ -1,21 +0,0 @@
import FlaggedPost from 'admin/models/flagged-post';
module("Discourse.FlaggedPost");
test('delete first post', function() {
sandbox.stub(Discourse, 'ajax');
FlaggedPost.create({ id: 1, topic_id: 2, post_number: 1 })
.deletePost();
ok(Discourse.ajax.calledWith("/t/2", { type: 'DELETE', cache: false }), "it deleted the topic");
});
test('delete second post', function() {
sandbox.stub(Discourse, 'ajax');
FlaggedPost.create({ id: 1, topic_id: 2, post_number: 2 })
.deletePost();
ok(Discourse.ajax.calledWith("/posts/1", { type: 'DELETE', cache: false }), "it deleted the post");
});

Some files were not shown because too many files have changed in this diff Show more