-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
314 lines (271 loc) · 9.35 KB
/
index.js
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/**
* @OnlyCurrentDoc
*
* The above comment directs Apps Script to limit the scope of file
* access for this add-on. It specifies that this add-on will only
* attempt to read or modify the files in which the add-on is used,
* and not all of the user's files. The authorization request message
* presented to users will reflect this limited scope.
*/
/* globals PropertiesService, DocumentApp, UrlFetchApp, Utilities, HtmlService, Logger */
import { OAuth2 } from 'imports-loader?_=./Underscore.gs!apps-script-oauth2/dist/OAuth2.gs'
import { WPClient } from './wp-client';
import { DocService } from './doc-service';
import { imageUploadLinker } from './image-upload-linker';
import { ImageCache } from './image-cache';
import { Persistance } from './persistance';
import { getDateFromIso } from './date-utils';
const wpClient = WPClient( PropertiesService, UrlFetchApp )
const store = Persistance( PropertiesService )
/**
* Creates a menu entry in the Google Docs UI when the document is opened.
* This method is only used by the regular add-on, and is never called by
* the mobile add-on version.
*
* @param {object} e The event parameter for a simple onOpen trigger. To
* determine which authorization mode (ScriptApp.AuthMode) the trigger is
* running in, inspect e.authMode.
*/
export function onOpen() {
DocumentApp.getUi().createAddonMenu()
.addItem( 'Open', 'showSidebar' )
// .addItem( 'Clear All Site Data', 'clearSiteData' )
// .addItem( 'Dev Testing', 'devTest' )
.addToUi();
}
/**
* Runs when the add-on is installed.
* This method is only used by the regular add-on, and is never called by
* the mobile add-on version.
*
* @param {object} e The event parameter for a simple onInstall trigger. To
* determine which authorization mode (ScriptApp.AuthMode) the trigger is
* running in, inspect e.authMode. (In practice, onInstall triggers always
* run in AuthMode.FULL, but onOpen triggers may be AuthMode.LIMITED or
* AuthMode.NONE.)
*/
export function onInstall( e ) {
onOpen( e );
}
/**
* Allow the HTML template to include files
*
* @param {string} filename file to include
* @returns {string} rendered content
*/
export function include( filename ) {
return HtmlService.createHtmlOutputFromFile( filename )
.getContent();
}
/**
* Opens a sidebar in the document containing the add-on's user interface.
* This method is only used by the regular add-on, and is never called by
* the mobile add-on version.
*/
export function showSidebar() {
const page = HtmlService.createTemplateFromFile( 'sidebar' ).evaluate();
page.setTitle( 'WordPress' );
DocumentApp.getUi().showSidebar( page );
}
export const getAuthUrl = () => oauthClient().getAuthorizationUrl()
function wpDie( message = '' ) {
const out = HtmlService.createTemplateFromFile( 'wp-die' );
out.message = message;
return out.evaluate();
}
function wpDieTemplate( template, error ) {
const out = HtmlService.createTemplateFromFile( 'wp-die-' + template );
out.error = '';
if ( error ) {
out.error = error.message;
}
return out.evaluate();
}
const updateSiteInfo = site => {
const postTypes = wpClient.getPostTypes( site ).map( postType => {
const taxonomies = wpClient.getTaxonomiesForPostType( site, postType ).map( t => t.name )
return Object.assign( {}, postType, { taxonomies } )
} )
return Object.assign( {}, site, {
info: wpClient.getSiteInfo( site ),
categories: wpClient.getCategories( site ),
postTypes
} )
}
export function authCallback( request ) {
let isAuthorized;
try {
isAuthorized = oauthClient().handleCallback( request );
} catch ( e ) {
return wpDie( 'There was a problem getting access to your site. Please try re-adding it, or <a href="https://support.wordpress.com/">contact support</a>.<pre>' + e );
}
if ( isAuthorized ) {
let site = oauthClient().getToken_()
try {
site = updateSiteInfo( site )
} catch ( e ) {
return wpDieTemplate( 'json-api', e );
}
store.addSite( site )
const template = HtmlService.createTemplateFromFile( 'oauth-success' );
showSidebar(); // reload
return template.evaluate();
}
return wpDieTemplate( 'deny' );
}
export function refreshSite( site_id ) {
const site = store.findSite( site_id )
const updatedSite = updateSiteInfo( site )
const filteredSite = store.updateSite( updatedSite )
const cachedPostData = store.getPostStatus();
filteredSite.post = cachedPostData[ site_id ]
return filteredSite
}
export function postToWordPress( site_id, { categories = [], tags = [], type = 'post' } ) {
const doc = DocumentApp.getActiveDocument();
const docProps = PropertiesService.getDocumentProperties();
const site = store.findSite( site_id );
const title = doc.getName()
const cachedPostData = store.getPostStatus();
let postId, cachedPost;
if ( cachedPostData[ site_id ] ) {
cachedPost = cachedPostData[ site_id ]
postId = cachedPost.ID;
if ( postOnServerIsNewer( site, cachedPost ) && ! confirmOverwrite() ) {
return cachedPost;
}
} else {
const postParams = { title, categories, tags, type, status: 'draft' }
const response = wpClient.postToWordPress( site, 'new', postParams );
store.savePostToSite( response, site )
postId = response.ID;
}
const upload = image => wpClient.uploadImage( site, image, postId )
const imageCache = ImageCache( site, docProps, md5 )
const imageUrlMapper = imageUploadLinker( upload, imageCache )
const renderContainer = DocService( DocumentApp, imageUrlMapper )
const content = renderContainer( doc.getBody() )
const postParams = { title, content, categories, tags, type }
const response = wpClient.postToWordPress( site, postId, postParams )
return store.savePostToSite( response, site )
}
function postOnServerIsNewer( site, cachedPost ) {
let serverPost;
try {
serverPost = wpClient.getPostStatus( site, cachedPost.ID );
} catch ( e ) {
Logger.log( 'Cannot get post status:' + e )
return false;
}
const localDate = getDateFromIso( cachedPost.modified );
const serverDate = getDateFromIso( serverPost.modified );
return ( localDate < serverDate );
}
function confirmOverwrite() {
const ui = DocumentApp.getUi();
const promptResponse = ui.alert(
'The post has been modified on the site',
'If you continue, any changes you made to the post on the site will be overwritten with this document.\n\nDo you want to overwrite the changes on the site?',
ui.ButtonSet.YES_NO
);
return ( promptResponse === ui.Button.YES )
}
export function listSites() {
const sites = store.listSites();
const posts = store.getPostStatus();
sites.forEach( site => site.post = posts[ site.blog_id ] )
return sites;
}
export function deleteSite( site_id ) {
const site = store.findSite( site_id );
if ( !site ) {
return;
}
const ui = DocumentApp.getUi();
const promptResponse = ui.alert(
'Are you sure you want to remove ' + site.info.name + '?',
ui.ButtonSet.YES_NO
);
if ( promptResponse === ui.Button.YES ) {
store.deleteSite( site_id );
}
return;
}
export function unlinkPost( site_id ) {
const ui = DocumentApp.getUi();
const promptResponse = ui.alert(
'Are you sure you want to unlink this document from the WordPress post?',
'If you choose "Yes" you can create a new post for this document.',
ui.ButtonSet.YES_NO
);
if ( promptResponse !== ui.Button.YES ) {
return false;
}
store.removePostFromSite( site_id );
return true;
}
export function devTest() {
// const doc = DocumentApp.getActiveDocument();
// const body = doc.getBody();
// const images = [];
// let imageRange = body.findElement( DocumentApp.ElementType.INLINE_IMAGE );
// while ( imageRange ) {
// const image = imageRange.getElement();
// const blob = image.getBlob();
// images.push( {
// attributes: image.getAttributes(),
// altTitle: image.getAltTitle(),
// altDescription: image.getAltDescription(),
// blob: {
// name: blob.getName(),
// }
// } )
// imageRange = body.findElement( DocumentApp.ElementType.INLINE_IMAGE, imageRange );
// }
// DocumentApp.getUi().alert( JSON.stringify( Object.keys( _ ) ) )
}
export function clearSiteData() {
const ui = DocumentApp.getUi();
const promptResponse = ui.alert(
'Are you sure you want to clear all sites?',
ui.ButtonSet.YES_NO
);
if ( promptResponse === ui.Button.YES ) {
oauthClient().reset();
PropertiesService.getUserProperties().deleteAllProperties();
PropertiesService.getDocumentProperties().deleteAllProperties();
}
showSidebar();
}
let oauthService = undefined;
// Needs to be lazy-instantiated because we don't have permissions to access
// properties until the app is actually open
function oauthClient() {
if ( oauthService ) {
return oauthService;
}
const { OauthClientId, OauthClientSecret } = PropertiesService.getScriptProperties().getProperties();
oauthService = OAuth2.createService( 'overpass' )
.setAuthorizationBaseUrl( 'https://public-api.wordpress.com/oauth2/authorize' )
.setTokenUrl( 'https://public-api.wordpress.com/oauth2/token' )
.setClientId( OauthClientId )
.setClientSecret( OauthClientSecret )
.setCallbackFunction( 'authCallback' )
.setPropertyStore( PropertiesService.getUserProperties() )
return oauthService;
}
function md5( message ) {
return Utilities.computeDigest( Utilities.DigestAlgorithm.MD5, message, Utilities.Charset.US_ASCII )
.map( ( byte ) => {
let char = '';
if ( byte < 0 ) {
byte += 255;
}
char = byte.toString( 16 );
if ( char.length === 1 ) {
char = '0' + char;
}
return char;
} )
.join( '' )
}