summaryrefslogtreecommitdiffstats
path: root/toolkit/jetpack/sdk/places/host/host-bookmarks.js
blob: f6dec40692f7b02478e6bc6faf7c91cc98e4eabf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

module.metadata = {
  "stability": "experimental",
  "engines": {
    "Palemoon": "*",
    "Firefox": "*",
    "SeaMonkey": "*"
  }
};

const { Cc, Ci } = require('chrome');
const browserHistory = Cc["@mozilla.org/browser/nav-history-service;1"].
                       getService(Ci.nsIBrowserHistory);
const asyncHistory = Cc["@mozilla.org/browser/history;1"].
                     getService(Ci.mozIAsyncHistory);
const bmsrv = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
                        getService(Ci.nsINavBookmarksService);
const taggingService = Cc["@mozilla.org/browser/tagging-service;1"].
                       getService(Ci.nsITaggingService);
const ios = Cc['@mozilla.org/network/io-service;1'].
            getService(Ci.nsIIOService);
const { query } = require('./host-query');
const {
  defer, all, resolve, promised, reject
} = require('../../core/promise');
const { request, response } = require('../../addon/host');
const { send } = require('../../addon/events');
const { on, emit } = require('../../event/core');
const { filter } = require('../../event/utils');
const { URL, isValidURI } = require('../../url');
const { newURI } = require('../../url/utils');

const DEFAULT_INDEX = bmsrv.DEFAULT_INDEX;
const UNSORTED_ID = bmsrv.unfiledBookmarksFolder;
const ROOT_FOLDERS = [
  bmsrv.unfiledBookmarksFolder, bmsrv.toolbarFolder,
  bmsrv.tagsFolder, bmsrv.bookmarksMenuFolder
];

const EVENT_MAP = {
  'sdk-places-bookmarks-create': createBookmarkItem,
  'sdk-places-bookmarks-save': saveBookmarkItem,
  'sdk-places-bookmarks-last-updated': getBookmarkLastUpdated,
  'sdk-places-bookmarks-get': getBookmarkItem,
  'sdk-places-bookmarks-remove': removeBookmarkItem,
  'sdk-places-bookmarks-get-all': getAllBookmarks,
  'sdk-places-bookmarks-get-children': getChildren
};

function typeMap (type) {
  if (typeof type === 'number') {
    if (bmsrv.TYPE_BOOKMARK === type) return 'bookmark';
    if (bmsrv.TYPE_FOLDER === type) return 'group';
    if (bmsrv.TYPE_SEPARATOR === type) return 'separator';
  } else {
    if ('bookmark' === type) return bmsrv.TYPE_BOOKMARK;
    if ('group' === type) return bmsrv.TYPE_FOLDER;
    if ('separator' === type) return bmsrv.TYPE_SEPARATOR;
  }
}

function getBookmarkLastUpdated ({id}) {
  return resolve(bmsrv.getItemLastModified(id));
}
exports.getBookmarkLastUpdated;

function createBookmarkItem (data) {
  let error;

  if (data.group == null) data.group = UNSORTED_ID;
  if (data.index == null) data.index = DEFAULT_INDEX;

  if (data.type === 'group')
    data.id = bmsrv.createFolder(
      data.group, data.title, data.index
    );
  else if (data.type === 'separator')
    data.id = bmsrv.insertSeparator(
      data.group, data.index
    );
  else
    data.id = bmsrv.insertBookmark(
      data.group, newURI(data.url), data.index, data.title
    );

  // In the event where default or no index is provided (-1),
  // query the actual index for the response
  if (data.index === -1)
    data.index = bmsrv.getItemIndex(data.id);

  try {
    data.updated = bmsrv.getItemLastModified(data.id);
  }
  catch (e) {
    console.exception(e);
  }

  return tag(data, true).then(() => data);
}
exports.createBookmarkItem = createBookmarkItem;

function saveBookmarkItem (data) {
  let id = data.id;
  if (!id)
    reject('Item is missing id');

  let group = bmsrv.getFolderIdForItem(id);
  let index = bmsrv.getItemIndex(id);
  let type = bmsrv.getItemType(id);
  let title = typeMap(type) !== 'separator' ?
    bmsrv.getItemTitle(id) :
    undefined;
  let url = typeMap(type) === 'bookmark' ?
    bmsrv.getBookmarkURI(id).spec :
    undefined;

  if (url != data.url)
    bmsrv.changeBookmarkURI(id, newURI(data.url));
  else if (typeMap(type) === 'bookmark')
    data.url = url;

  if (title != data.title)
    bmsrv.setItemTitle(id, data.title);
  else if (typeMap(type) !== 'separator')
    data.title = title;

  if (data.group && data.group !== group)
    bmsrv.moveItem(id, data.group, data.index || -1);
  else if (data.index != null && data.index !== index) {
    // We use moveItem here instead of setItemIndex
    // so we don't have to manage the indicies of the siblings
    bmsrv.moveItem(id, group, data.index);
  } else if (data.index == null)
    data.index = index;

  data.updated = bmsrv.getItemLastModified(data.id);

  return tag(data).then(() => data);
}
exports.saveBookmarkItem = saveBookmarkItem;

function removeBookmarkItem (data) {
  let id = data.id;

  if (!id)
    reject('Item is missing id');

  bmsrv.removeItem(id);
  return resolve(null);
}
exports.removeBookmarkItem = removeBookmarkItem;

function getBookmarkItem (data) {
  let id = data.id;

  if (!id)
    reject('Item is missing id');

  let type = bmsrv.getItemType(id);

  data.type = typeMap(type);

  if (type === bmsrv.TYPE_BOOKMARK || type === bmsrv.TYPE_FOLDER)
    data.title = bmsrv.getItemTitle(id);

  if (type === bmsrv.TYPE_BOOKMARK) {
    data.url = bmsrv.getBookmarkURI(id).spec;
    // Should be moved into host-tags as a method
    data.tags = taggingService.getTagsForURI(newURI(data.url), {});
  }

  data.group = bmsrv.getFolderIdForItem(id);
  data.index = bmsrv.getItemIndex(id);
  data.updated = bmsrv.getItemLastModified(data.id);

  return resolve(data);
}
exports.getBookmarkItem = getBookmarkItem;

function getAllBookmarks () {
  return query({}, { queryType: 1 }).then(bookmarks =>
    all(bookmarks.map(getBookmarkItem)));
}
exports.getAllBookmarks = getAllBookmarks;

function getChildren ({ id }) {
  if (typeMap(bmsrv.getItemType(id)) !== 'group') return [];
  let ids = [];
  for (let i = 0; ids[ids.length - 1] !== -1; i++)
    ids.push(bmsrv.getIdForItemAt(id, i));
  ids.pop();
  return all(ids.map(id => getBookmarkItem({ id: id })));
}
exports.getChildren = getChildren;

/*
 * Hook into host
 */

var reqStream = filter(request, (data) => /sdk-places-bookmarks/.test(data.event));
on(reqStream, 'data', ({ event, id, data }) => {
  if (!EVENT_MAP[event]) return;

  let resData = { id: id, event: event };

  promised(EVENT_MAP[event])(data).
  then(res => resData.data = res, e => resData.error = e).
  then(() => emit(response, 'data', resData));
});

function tag (data, isNew) {
  // If a new item, we can skip checking what other tags
  // are on the item
  if (data.type !== 'bookmark') {
    return resolve();
  }
  else if (!isNew) {
    return send('sdk-places-tags-get-tags-by-url', { url: data.url })
      .then(tags => {
        return send('sdk-places-tags-untag', {
          tags: tags.filter(tag => !~data.tags.indexOf(tag)),
          url: data.url
        });
      }).then(() => send('sdk-places-tags-tag', {
        url: data.url, tags: data.tags
      }));
  }
  else if (data.tags && data.tags.length) {
    return send('sdk-places-tags-tag', { url: data.url, tags: data.tags });
  }
  else
    return resolve();
}