This repository has been archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Code.js
1037 lines (891 loc) · 30.3 KB
/
Code.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* The event handler triggered when installing the add-on.
* @param {Event} e The onInstall event.
*/
function onInstall(e) {
onOpen(e);
}
/**
* The event handler triggered when opening the document.
* @param {Event} e The onOpen event.
*
* This adds a "TNC Tools" menu option.
*/
function onOpen(e) {
// display sidebar
DocumentApp.getUi()
.createMenu('TinyCMS Publishing Tools')
.addItem('Publishing Tools', 'showSidebar')
.addItem('Administrator Tools', 'showSidebarManualAssociate')
.addToUi();
}
/**
* Displays the Publishing Tools sidebar
*/
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('Page')
.setTitle('CMS Integration')
.setWidth(300);
DocumentApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showSidebar(html);
}
/**
* Displays the Admin Tools sidebar
*/
function showSidebarManualAssociate() {
var html = HtmlService.createHtmlOutputFromFile('ManualPage')
.setTitle('CMS Integration')
.setWidth(300);
DocumentApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showSidebar(html);
}
//
// Utility functions
//
/*
.* for now this only trims whitespace, but stands to allow for any other text cleaning up we may need
.*/
function cleanContent(content) {
if (content === null || typeof(content) === 'undefined') {
return "";
}
return content.trim();
}
/*
.* condenses text style into one object allowing for bold, italic and underline
.* google docs style attribute often contains unrelated info, sometimes even the text content
.*/
function cleanStyle(incomingStyle) {
var cleanedStyle = {
underline: incomingStyle.underline,
bold: incomingStyle.bold,
italic: incomingStyle.italic
}
return cleanedStyle;
}
// Implementation from https://gist.github.com/codeguy/6684588
// takes a regular string and returns a slug
function slugify(value) {
if (value === null || typeof(value) === 'undefined') {
return "";
}
value = value.trim();
value = value.toLowerCase();
var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
var to = "aaaaeeeeiiiioooouuuunc------";
for (var i=0, l=from.length ; i<l ; i++) {
value = value.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
value = value.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-'); // collapse dashes
return value;
}
/*
.* This uploads an image in the Google Doc to S3
.* destination URL determined by: Organization Name, Article Title, and image ID
.*/
/*
* looks up either an article or a page by google doc ID
*/
async function lookupDataForDocument(documentID, documentType) {
var scriptConfig = getScriptConfig();
var API_TOKEN = scriptConfig['DOCUMENT_API_TOKEN'];
var API_URL = scriptConfig['DOCUMENT_API_URL'];
var SITE = scriptConfig['SITE'];
var options = {
method: 'GET',
muteHttpExceptions: true,
contentType: 'application/json',
};
const requestURL = `${API_URL}/api/sidebar/documents/${documentID}?token=${API_TOKEN}&documentType=${documentType}&site=${SITE}`
Logger.log("REQUEST URL: " + requestURL);
const result = await UrlFetchApp.fetch(
requestURL,
options
);
var responseText = result.getContentText();
var responseData = JSON.parse(responseText);
responseData.site = SITE;
Logger.log(Object.keys(responseData) + " " + responseData.documentType);
return responseData;
}
/*
.* Finds all parent folders for a given Google Drive file object
.* .getParents() only returns immediate parents, so we must recurse.
*/
function findAllParents(file) {
var allParents = [];
function getObjParents(obj, allParents) {
var parents = obj.getParents();
while (parents.hasNext()) {
var parent = parents.next();
allParents.push({
name: parent.getName(),
id: parent.getId()
});
getObjParents(parent, allParents);
}
}
getObjParents(file, allParents);
return allParents;
}
/*
* Gets the script configuration, data available to all users and docs for this add-on
*/
function getScriptConfig() {
// look up org name on this document (scoped doc properties) in case we've figured it out before
var orgName = getOrganizationName();
// otherwise, locate the folder that contains 'articles' or 'pages' - it should be
// named for the organisation; for example: 'oaklyn' > 'articles' > 'Article Document'
if (orgName === null) {
var documentID = DocumentApp.getActiveDocument().getId();
var driveFile = DriveApp.getFileById(documentID);
var fileParents = findAllParents(driveFile);
var articlesFolderData = fileParents.find(function(item) {
return item.name.toLowerCase() === 'articles';
});
var pagesFolderData = fileParents.find(function(item) {
return item.name.toLowerCase() === 'pages';
});
var containerFolderData = articlesFolderData || pagesFolderData;
if (containerFolderData) {
var containerFolder = DriveApp.getFolderById(containerFolderData.id);
var folderParents = containerFolder.getParents();
while (folderParents.hasNext()) {
var grandFolder = folderParents.next();
orgName = grandFolder.getName();
storeOrganizationName(orgName);
}
}
}
// If there's still no org name return an error
if (orgName === null) {
return { "status": "error", "message": "Failed to find an organization name; check the folder structure." }
}
var scriptProperties = PropertiesService.getScriptProperties();
var data = scriptProperties.getProperties();
var orgData = {}
var pattern = `^${orgName}_`;
var orgKeyRegEx = new RegExp(pattern, "i")
// value = value.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
for (var key in data) {
if (orgKeyRegEx.test(key)) {
var plainKey = key.replace(orgKeyRegEx, '');
orgData[plainKey] = data[key];
}
}
return orgData;
}
/*
.* Sets script-wide configuration
.*/
function setScriptConfig(data) {
var orgName = getOrganizationName();
if (orgName === null) {
return { "status": "error", "message": "Failed to find an organization name; check the folder structure." }
}
var scriptProperties = PropertiesService.getScriptProperties();
for (var key in data) {
var orgKey = orgName + "_" + key;
// (orgKey, "=>", data[key]);
scriptProperties.setProperty(orgKey, data[key]);
}
return { status: "success", message: "Saved configuration." };
}
/*
.* general purpose function (called in the other data storage functions) to retrieve a value for a key
.*/
function getValue(key) {
var documentProperties = PropertiesService.getDocumentProperties();
var value = documentProperties.getProperty(key);
return value;
}
function getValueJSON(key) {
var valueString = getValue(key);
var value = [];
if (valueString && valueString !== null) {
try {
value = JSON.parse(valueString);
} catch(e) {
Logger.log("error parsing JSON: ", e)
value = []
}
}
return value;
}
/*
.* general purpose function (called in the other data storage functions) to set a value at a key
.*/
function storeValue(key, value) {
// Logger.log(`${key} => ${value}`);
var documentProperties = PropertiesService.getDocumentProperties();
documentProperties.setProperty(key, value);
}
function storeValueJSON(key, value) {
var valueString;
try {
valueString = JSON.stringify(value);
} catch(e) {
Logger.log("error stringify-ing data: ", e)
valueString = JSON.stringify([]);
}
storeValue(key, valueString);
}
function deleteValue(key) {
var documentProperties = PropertiesService.getDocumentProperties();
documentProperties.deleteProperty(key);
}
function getOrganizationName() {
return getValue("ORG_NAME");
}
function storeOrganizationName(value) {
storeValue("ORG_NAME", value);
}
function getArticleSlug() {
return getValue('ARTICLE_SLUG');
}
function storeArticleSlug(slug) {
storeValue("ARTICLE_SLUG", slug);
}
function deleteArticleSlug() {
deleteValue('ARTICLE_SLUG');
}
function storeImageList(slug, imageList) {
var key = "IMAGE_LIST_" + slug;
storeValue(key, JSON.stringify(imageList));
}
function getImageList(slug) {
var key = "IMAGE_LIST_" + slug;
var imageList = JSON.parse(getValue(key));
if (imageList === null) {
imageList = {};
}
return imageList;
}
async function insertPageGoogleDocs(data) {
var returnValue = {
status: "success",
message: "",
data: {},
documentType: "page"
};
var activeDoc = DocumentApp.getActiveDocument();
var documentID = DocumentApp.getActiveDocument().getId();
var documentURL = DocumentApp.getActiveDocument().getUrl();
if (data['document-id']) {
documentID = data['document-id'];
documentUrl = data['document-url'];
}
var document = Docs.Documents.get(documentID);
var slug = getArticleSlug();
if (!slug) {
slug = data['article-slug'];
}
var elements = document.body.content;
var inlineObjects = document.inlineObjects;
// used to track which images have already been uploaded
var imageList = getImageList(slug);
var listInfo = {};
var listItems = activeDoc.getListItems();
listItems.forEach(li => {
var id = li.getListId();
var glyphType = li.getGlyphType();
listInfo[id] = glyphType;
})
let pageData = {
"id": data['article-id'],
"slug": slug,
"document_id": documentID,
"url": documentURL,
"locale_code": 'en-US',
"headline": data['article-headline'],
"published": data['published'],
"search_description": data['article-search-description'],
"search_title": data['article-search-title'],
"twitter_title": data['article-twitter-title'],
"twitter_description": data['article-twitter-description'],
"facebook_title": data['article-facebook-title'],
"facebook_description": data['article-facebook-description'],
"created_by_email": data['created_by_email'],
"page_authors": data['article-authors'],
};
if (pageData['published']) {
Logger.log("PUBLISH " + typeof(elements) + " (" + elements.length + ") " + JSON.stringify(elements));
let response = await publishPage(pageData, slug, elements, listInfo, imageList, inlineObjects);
Logger.log("publishPageResponse: " + Object.keys(response).sort());
returnValue.data = response.data;
if (response.status && response.status === 'error') {
returnValue.status = 'error';
returnValue.message = "An error occurred saving the page."
} else {
Logger.log("Storing image list.");
storeImageList(slug, response.updatedImageList);
returnValue.publishUrl = response.publishUrl;
returnValue.message = "Successfully saved the page.";
}
} else {
Logger.log("PREVIEW");
let response = await previewPage(pageData, slug, elements, listInfo, imageList, inlineObjects);
Logger.log("previewPageResponse: " + Object.keys(response).sort());
returnValue.data = response.data;
if (response.status && response.status === 'error') {
returnValue.status = 'error';
returnValue.message = "An error occurred saving the page."
} else {
Logger.log("Storing image list.");
storeImageList(slug, response.updatedImageList);
returnValue.previewUrl = response.previewUrl;
returnValue.message = "Successfully saved the page.";
}
}
return returnValue;
}
async function insertArticleGoogleDocs(data) {
var returnValue = {
status: "success",
message: "",
data: {},
documentType: "article"
};
var activeDoc = DocumentApp.getActiveDocument();
var documentID = activeDoc.getId();
var documentUrl = DocumentApp.getActiveDocument().getUrl();
if (data['document-id']) {
documentID = data['document-id'];
documentUrl = data['document-url'];
}
var document = Docs.Documents.get(documentID);
var slug = getArticleSlug();
if (!slug) {
slug = data['article-slug'];
}
var elements = document.body.content;
var inlineObjects = document.inlineObjects;
// used to track which images have already been uploaded
var imageList = getImageList(slug);
var listInfo = {};
var listItems = activeDoc.getListItems();
listItems.forEach(li => {
var id = li.getListId();
var glyphType = li.getGlyphType();
listInfo[id] = glyphType;
})
let articleData = {
"id": data['article-id'],
"slug": slug,
"document_id": documentID,
"url": documentUrl,
"category_id": data['article-category'],
"locale_code": 'en-US',
"headline": data['article-headline'],
"published": data['published'],
"search_description": data['article-search-description'],
"search_title": data['article-search-title'],
"twitter_title": data['article-twitter-title'],
"twitter_description": data['article-twitter-description'],
"facebook_title": data['article-facebook-title'],
"facebook_description": data['article-facebook-description'],
"custom_byline": data['article-custom-byline'],
"created_by_email": data['created_by_email'],
"canonical_url": data['article-custom-canonical-url'],
"article_tags": data['article-tags'],
"article_authors": data['article-authors'],
};
if (data["first-published-at"]) {
articleData["first_published_at"] = data["first-published-at"];
Logger.log("* first published at: " + articleData["first_published_at"]);
}
var dataSources = [];
if (data['sources'] !== {} && Object.keys(data['sources']).length > 0) {
Object.keys(data['sources']).forEach(id => {
Logger.log("id: " + typeof(id) + " -> " + id)
var source = data['sources'][id];
var sourceData = {
name: source['name'],
affiliation: source['affiliation'],
race: source['race'],
ethnicity: source['ethnicity'],
age: source['age'],
gender: source['gender'],
phone: source['phone'],
email: source['email'],
zip: source['zip'],
sexual_orientation: source['sexual_orientation'],
role: source['role'],
};
if (id !== null && id !== undefined && id !== "" && !(/new_/.test(id))) {
sourceData["id"] = parseInt(id);
}
dataSources.push({
source: {
data: sourceData,
on_conflict: {
constraint: "sources_pkey",
update_columns: ["name", "affiliation", "age", "phone", "zip", "race", "gender", "sexual_orientation", "ethnicity", "role", "email"]
}
}
})
})
articleData["article_sources"] = dataSources;
Logger.log("pushed sources onto article data:" + JSON.stringify(articleData['article_sources']));
} else {
articleData['article_sources'] = [];
}
if (articleData['published']) {
Logger.log("PUBLISH");
let response = await apiSaveArticle(articleData, slug, elements, listInfo, imageList, inlineObjects);
Logger.log("publishArticleResponse: " + JSON.stringify(response));
returnValue.data = response.data;
if (response.status && response.status === 'error') {
returnValue.status = 'error';
returnValue.message = "An error occurred saving the article."
} else {
Logger.log("Storing image list.");
storeImageList(slug, response.updatedImageList);
returnValue.publishUrl = response.publishUrl;
returnValue.message = "Successfully saved the article.";
}
} else {
Logger.log("PREVIEW");
let response = await apiSaveArticle(articleData, slug, elements, listInfo, imageList, inlineObjects);
Logger.log("previewArticleResponse: " + Object.keys(response).sort());
returnValue.data = response.data;
if (response.status && response.status === 'error') {
returnValue.status = 'error';
returnValue.message = "An error occurred saving the article."
} else {
Logger.log("Storing image list.");
storeImageList(slug, response.updatedImageList);
returnValue.previewUrl = response.previewUrl;
returnValue.message = "Successfully saved the article.";
}
}
return returnValue;
}
async function hasuraHandleUnpublish(formObject) {
var slug = formObject['article-slug'];
var documentType;
var documentID = DocumentApp.getActiveDocument().getId();
var isStaticPage = isPage(documentID);
if (isStaticPage) {
documentType = "page";
} else {
documentType = "article";
}
var response = await apiUnpublish(documentType, documentID, slug);
var returnValue = {
status: "success",
message: `Successfully unpublished the ${documentType}`,
data: response
};
if (response.errors) {
returnValue.status = "error";
returnValue.message = `An unexpected error occurred trying to unpublish the ${documentType}`;
returnValue.data = response.errors;
}
return returnValue;
}
async function hasuraHandlePublish(formObject) {
// set the email for auditing changes
var currentUserEmail = Session.getActiveUser().getEmail();
formObject["created_by_email"] = currentUserEmail;
var slug = formObject['article-slug'];
var headline = formObject['article-headline'];
if (headline === "" || headline === null || headline === undefined) {
return {
message: "Headline is required",
status: "error",
data: formObject
}
}
if (slug === "" || slug === null || slug === undefined) {
slug = slugify(headline);
formObject['article-slug'] = slug;
} else {
// always ensure the slug is valid, no spaces etc
slug = slugify(slug);
formObject['article-slug'] = slug;
}
// NOTE: this flag tells the insert mutation to mark this new translation record as PUBLISHED
// - this is set to false when the 'preview article' button is clicked instead.
formObject['published'] = true;
var data;
var documentType;
var publishUrl;
var documentID = DocumentApp.getActiveDocument().getId();
var isStaticPage = isPage(documentID);
if (isStaticPage) {
documentType = "page";
Logger.log("publishing a page " + JSON.stringify(formObject))
// insert or update page
var insertPage = await insertPageGoogleDocs(formObject);
if (insertPage.status === "error") {
insertPage["documentID"] = documentID;
return insertPage;
}
data = insertPage.data;
Logger.log("pageResult: " + JSON.stringify(data))
publishUrl = insertPage.publishUrl;
} else {
documentType = "article";
var insertArticle = await insertArticleGoogleDocs(formObject);
if(insertArticle.status === "error") {
insertArticle["documentID"] = documentID;
return insertArticle;
}
Logger.log(JSON.stringify(insertArticle));
publishUrl = insertArticle.publishUrl;
data = insertArticle.data;
}
// open preview url in new window
var message = "Published the " + documentType + ". <a href='" + publishUrl + "' target='_blank'>Click to view</a>."
return {
message: message,
data: data,
documentType: documentType,
documentID: documentID,
status: "success"
}
}
async function hasuraHandlePreview(formObject) {
// set the email for auditing changes
var currentUserEmail = Session.getActiveUser().getEmail();
formObject["created_by_email"] = currentUserEmail;
var slug = formObject['article-slug'];
var headline = formObject['article-headline'];
if (headline === "" || headline === null || headline === undefined) {
return {
message: "Headline is required",
status: "error",
data: formObject
}
}
if (slug === "" || slug === null || slug === undefined) {
slug = slugify(headline)
Logger.log("no slug found, generated from headline: " + headline + " -> " + slug)
formObject['article-slug'] = slug;
} else {
slug = slugify(slug)
formObject['article-slug'] = slug;
}
// NOTE: this flag tells the insert mutation to mark this new translation record as UNPUBLISHED
// - this is set to true when the 'publish article' button is clicked instead.
formObject['published'] = false;
var data;
var documentType;
var previewUrl;
var documentID = DocumentApp.getActiveDocument().getId();
var isStaticPage = isPage(documentID);
if (isStaticPage) {
documentType = "page";
// insert or update page
var insertPage = await insertPageGoogleDocs(formObject);
if (insertPage.status === "error") {
insertPage["documentID"] = documentID;
return insertPage;
}
var data = insertPage.data;
Logger.log("pageResult: " + JSON.stringify(data))
previewUrl = insertPage.previewUrl;
} else {
documentType = "article";
var insertArticle = await insertArticleGoogleDocs(formObject);
Logger.log("insertArticle response: " + JSON.stringify(insertArticle));
if (insertArticle.status === "error") {
insertArticle["documentID"] = documentID;
return insertArticle;
}
previewUrl = insertArticle.previewUrl;
var data = insertArticle.data;
}
var message = "<a href='" + previewUrl + "' target='_blank'>Preview " + documentType + " in new window</a>";
return {
message: message,
data: data,
documentType: documentType,
documentID: documentID,
status: "success"
}
}
// this determines whether the doc is in an "articles" or "pages" folder
// otherwise, it's in the wrong spot and we should throw an error
function isValid(documentID) {
var driveFile = DriveApp.getFileById(documentID)
var fileParents = findAllParents(driveFile);
var articlesFolderData = fileParents.find(function(item) {
return item.name.toLowerCase() === 'articles';
});
var pagesFolderData = fileParents.find(function(item) {
return item.name.toLowerCase() === 'pages';
});
if (articlesFolderData || pagesFolderData) {
return true;
} else {
return false;
}
}
// determine if this is a static page or an article - it will usually be an article
function isPage(documentID) {
var driveFile = DriveApp.getFileById(documentID)
var fileParents = findAllParents(driveFile)
var isStaticPage = false;
var pagesFolderData = fileParents.find(function(item) {
return item.name.toLowerCase() === 'pages';
});
if (pagesFolderData) {
isStaticPage = true;
}
return isStaticPage;
}
/*
. * Returns metadata about the article, including its id, whether it was published
. * headline and byline
. */
async function hasuraGetArticle() {
var returnValue = {
status: "",
message: "",
data: {}
};
var document = DocumentApp.getActiveDocument();
var documentID = document.getId();
var documentTitle = document.getName();
Logger.log("documentID: " + documentID);
returnValue.documentId = documentID;
let documentType = 'article';
let isStaticPage = isPage(documentID);
if (isStaticPage) {
documentType = 'page';
}
var valid = isValid(documentID);
if (!valid) {
returnValue.status = "error";
returnValue.message = "Documents must be in the right folder to be published: orgName/articles (and subfolders) for articles and orgName/pages for static pages (like About or Contact); please move this document and try again."
return returnValue;
}
let data = await lookupDataForDocument(documentID, documentType);
if (!data.documentType) {
data.documentType = documentType;
}
returnValue.documentType = data.documentType;
if (data && data.documentType === 'page' && data.page && data.page.slug) {
storeArticleSlug(data.page.slug);
returnValue.data = data;
returnValue.status = "success";
returnValue.message = "Retrieved page with ID: " + data.page.id;
} else if (data && data.documentType === 'page' && !data.page) {
Logger.log("page not found: " + JSON.stringify(data));
returnValue.data = data;
returnValue.status = "notFound";
returnValue.message = "Page not found";
} else if (data && data.documentType === 'article' && data.article && data.article.slug) {
storeArticleSlug(data.article.slug);
data.headline = documentTitle;
data.searchTitle = documentTitle;
returnValue.data = data;
returnValue.status = "success";
returnValue.message = "Retrieved article with ID: " + data.article.id;
} else if (data && data.documentType === 'article' && !data.article) {
Logger.log("article not found: " + JSON.stringify(data));
data.headline = documentTitle;
data.searchTitle = documentTitle;
returnValue.data = data;
returnValue.status = "notFound";
returnValue.message = "Article not found";
} else {
Logger.log("Something went wrong looking up the document: " + JSON.stringify(data));
returnValue.data = data;
returnValue.status = "error";
returnValue.message = "Something went wrong looking up the document" + JSON.stringify(data);
}
Logger.log("returnValue: " + JSON.stringify(returnValue));
return returnValue;
}
async function apiSaveArticle(articleData, slug, contents, listInfo, imageList, inlineObjects) {
var scriptConfig = getScriptConfig();
var API_TOKEN = scriptConfig['DOCUMENT_API_TOKEN'];
var API_URL = scriptConfig['DOCUMENT_API_URL'];
var SITE = scriptConfig['SITE'];
var activeDoc = DocumentApp.getActiveDocument();
var documentID = activeDoc.getId();
let apiAction = 'preview';
if (articleData['published']) {
apiAction = 'publish';
}
const requestURL = `${API_URL}/api/sidebar/documents/${documentID}/${apiAction}?token=${API_TOKEN}&documentType=article&site=${SITE}`
Logger.log("REQUEST URL: " + requestURL);
// TODO Remove TNC-Site header - pretty sure it's NOT required here and is only a relic from when this request was directly sent to Hasura
var options = {
method: 'POST',
muteHttpExceptions: true,
contentType: 'application/json',
headers: {
"TNC-Site": SITE
},
payload: JSON.stringify({
articleData: articleData,
googleAuthToken: ScriptApp.getOAuthToken(),
contents: contents,
slug: slug,
listInfo: listInfo,
imageList: imageList,
inlineObjects: inlineObjects
}),
};
const result = await UrlFetchApp.fetch(
requestURL,
options
);
var responseText = result.getContentText();
var responseData;
try {
responseData = JSON.parse(responseText);
} catch(e) {
console.error(e)
responseData = {
status: 'error',
data: responseText
}
}
return responseData;
}
async function apiUnpublish(documentType, documentID, slug) {
var scriptConfig = getScriptConfig();
var API_TOKEN = scriptConfig['DOCUMENT_API_TOKEN'];
var API_URL = scriptConfig['DOCUMENT_API_URL'];
var SITE = scriptConfig['SITE'];
let apiAction = 'unpublish'; // always, probably doesn't have to be a var, just keeping consistent with apiSaveArticle
let data = {'published': false}; // this value should ALWAYS be false in this function so we hardcode here
const requestURL = `${API_URL}/api/sidebar/documents/${documentID}/${apiAction}?token=${API_TOKEN}&documentType=${documentType}&site=${SITE}`
Logger.log("REQUEST URL: " + requestURL);
let payloadData;
if (documentType === 'page') {
payloadData = JSON.stringify({
pageData: data,
slug: slug,
})
} else {
payloadData = JSON.stringify({
articleData: data,
slug: slug,
})
}
Logger.log(payloadData)
// TODO Remove TNC-Site header - pretty sure it's NOT required here and is only a relic from when this request was directly sent to Hasura
var options = {
method: 'POST',
muteHttpExceptions: true,
contentType: 'application/json',
headers: {
"TNC-Site": SITE
},
payload: payloadData,
};
const result = await UrlFetchApp.fetch(
requestURL,
options
);
var responseText = result.getContentText();
var responseData;
try {
responseData = JSON.parse(responseText);
} catch(e) {
console.error(e)
responseData = {
status: 'error',
data: responseText
}
}
return responseData;
}
async function previewPage(pageData, slug, contents, listInfo, imageList, inlineObjects) {
var scriptConfig = getScriptConfig();
var API_TOKEN = scriptConfig['DOCUMENT_API_TOKEN'];
var API_URL = scriptConfig['DOCUMENT_API_URL'];
var SITE = scriptConfig['SITE'];
var activeDoc = DocumentApp.getActiveDocument();
var documentID = activeDoc.getId();
const requestURL = `${API_URL}/api/sidebar/documents/${documentID}/preview?token=${API_TOKEN}&documentType=page&site=${SITE}`
Logger.log("REQUEST URL: " + requestURL);
// TODO Remove TNC-Site header - pretty sure it's NOT required here and is only a relic from when this request was directly sent to Hasura
var options = {
method: 'POST',
muteHttpExceptions: true,
contentType: 'application/json',
headers: {
"TNC-Site": SITE
},
payload: JSON.stringify({
pageData: pageData,
googleAuthToken: ScriptApp.getOAuthToken(),
contents: contents,
slug: slug,
listInfo: listInfo,
imageList: imageList,
inlineObjects: inlineObjects
}),
};
const result = await UrlFetchApp.fetch(
requestURL,
options
);
var responseText = result.getContentText();
var responseData;
try {
responseData = JSON.parse(responseText);
} catch(e) {
console.error(e)
responseData = {
status: 'error',
data: responseText
}
}
return responseData;
}
async function publishPage(pageData, slug, contents, listInfo, imageList, inlineObjects) {
var scriptConfig = getScriptConfig();
var API_TOKEN = scriptConfig['DOCUMENT_API_TOKEN'];
var API_URL = scriptConfig['DOCUMENT_API_URL'];
var SITE = scriptConfig['SITE'];
var activeDoc = DocumentApp.getActiveDocument();
var documentID = activeDoc.getId();
const requestURL = `${API_URL}/api/sidebar/documents/${documentID}/publish?token=${API_TOKEN}&documentType=page&site=${SITE}`
Logger.log("REQUEST URL: " + requestURL);
// TODO Remove TNC-Site header - pretty sure it's NOT required here and is only a relic from when this request was directly sent to Hasura
var options = {