// GraalJS Script (engine type: 2)
//////// START "main()" /////////////////////////////////////////////////////////////////
main();
function main(){
//// == Config Retrieving / 工程コンフィグの参照 ==
const strAuthzSetting = configs.get ( "AuthzConfU" ); /// REQUIRED
engine.log( " AutomatedTask Config: Authz Setting: " + strAuthzSetting );
const strWpcomDomain = configs.get ( "StrConfA1" ); /// REQUIRED
if( strWpcomDomain === "" ){
throw new Error( "\n AutomatedTask ConfigError:" +
" Config {A1: WordPress.com domain} is empty \n" );
}
let strPostType = configs.get ( "StrConfA2" ); // NotRequired
if( strPostType === "" ){
engine.log( " AutomatedTask ConfigWarning: " +
" {A2: PostType} is empty (default 'post' applied)" );
strPostType = "post";
} // Post types besides post and page need to be whitelisted using rest_api_allowed_post_types
const strPostParentId = configs.get ( "StrConfA3" ); // NotRequired
const strPostTime = configs.get ( "StrConfB1" ); // NotRequired
const strPostTitle = configs.get ( "StrConfB2" ); // NotRequired
const strPostSlug = configs.get ( "StrConfB3" ); // NotRequired
const strPostExcerpt = configs.get ( "StrConfB4" ); // NotRequired
const strPostCategories = configs.get ( "StrConfB5" ); // NotRequired
const strPostTags = configs.get ( "StrConfB6" ); // NotRequired
const strPostContent = configs.get ( "StrConfC" ); /// REQUIRED
const strPocketPostedId = configs.getObject( "SelectConfD1" ); // NotRequired
const strPocketPostedUrl = configs.getObject( "SelectConfD2" ); // NotRequired
//// == Data Retrieving / ワークフローデータの参照 ==
// (Nothing. Some workflow data is referenced via Expression Language in Config.)
//// == Calculating / 演算 ==
/// Create a post
/// WordPress.com REST API
/// https://developer.wordpress.com/docs/api/1.2/post/sites/%24site/posts/new/
// request1, prepare
let request1Uri = "https://public-api.wordpress.com/rest/v1.2/sites/" +
strWpcomDomain + "/posts/new";
let request1 = httpClient.begin(); // HttpRequestWrapper
request1 = request1.authSetting( strAuthzSetting ); // with "Authorization: Bearer XX"
// https://questetra.zendesk.com/hc/en-us/articles/360024574471-R2300#HttpRequestWrapper
request1 = request1.formParam( "status", "draft" );
request1 = request1.formParam( "type" , strPostType );
if( strPostParentId !== "" ){
request1 = request1.formParam( "parent", strPostParentId );
}
if( strPostTime !== "" ){
let datePostTime = toJsDate( strPostTime );
request1 = request1.formParam( "date" , datePostTime.toISOString() );
engine.log( " AutomatedTask RuntimeLog: date: " + datePostTime.toISOString() );
}
if( strPostTitle !== "" ){
request1 = request1.formParam( "title" , strPostTitle );
}
if( strPostSlug !== "" ){
request1 = request1.formParam( "slug" , strPostSlug );
}
if( strPostExcerpt !== "" ){
request1 = request1.formParam( "excerpt", strPostExcerpt );
}
if( strPostCategories !== "" ){
request1 = request1.formParam( "categories", strPostCategories );
}
if( strPostTags !== "" ){
request1 = request1.formParam( "tags" , strPostTags );
}
request1 = request1.formParam( "content", strPostContent );
// request1, try
const response1 = request1.post( request1Uri ); // HttpResponseWrapper
engine.log( " AutomatedTask ApiRequest1 Start: " + request1Uri );
const response1Code = response1.getStatusCode() + "";
const response1Body = response1.getResponseAsString() + "";
engine.log( " AutomatedTask ApiResponse Status: " + response1Code );
if( response1Code !== "200"){
throw new Error( "\n AutomatedTask UnexpectedResponseError: " +
response1Code + "\n" + response1Body + "\n" );
}
// response1, parse
/*
engine.log( response1Body ); // debug
{
"ID":3812,
"site_ID":999996377,
"author":{
# # #
},
"date":"2021-06-30T00:00:00+09:00",
"modified":"2021-06-30T00:00:00+09:00",
"title":"Soseki NATSUME",
"URL":"https:\/\/example.com\/?p=3812",
"short_URL":"https:\/\/wp.me\/p9egkh-Zu",
"content":"\n<h3>I am a cat.<\/h3>\n\n\n\n<p>As yet # # #",
"excerpt":"<p>This must have been the very first time that ever I set eyes on a human being.<\/p>\n",
"slug":"soseki-natsume",
"guid":"https:\/\/example.com\/?p=3812",
"status":"draft",
"sticky":false,
"password":"",
"parent":false,
"type":"post",
"discussion":{
"comments_open":true,
"comment_status":"open",
"pings_open":true,
"ping_status":"open",
"comment_count":0
},
"likes_enabled":true,
"sharing_enabled":true,
"like_count":0,
"i_like":false,
"is_reblogged":false,
"is_following":true,
"global_ID":"99999xxxxx869f8b171b488508021374",
"featured_image":"",
"format":"standard",
"geo":false,
"menu_order":0,
"page_template":"",
"publicize_URLs":[],
"terms":{
"category":{
"Staff Blog":{"ID":2, # # # }
"post_tag":{
"Remote Work":{"ID":139, # # # },
"Wordpress":{"ID":134, # # # }
},
"post_format":{}
},
"tags":{
"Remote Work":{"ID":139, # # #},
"Wordpress":{"ID":134, # # # }
},
"categories":{
"Staff Blog":{"ID":2, # # # }
},
"attachments":{},
"attachment_count":0,
"metadata":[],
"meta":{"links": # # # },
"capabilities":{"publish_post":true,"delete_post":true,"edit_post":true},
"other_URLs":{
"permalink_URL":"https:\/\/example.com\/blog\/%postname%\/",
"suggested_slug":"soseki-natsume"
}
}
*/
const response1Obj = JSON.parse( response1Body );
//// == Data Updating / ワークフローデータへの代入 ==
if( strPocketPostedId !== null ){
if( strPocketPostedId.matchDataType( "STRING" ) ){
engine.setData( strPocketPostedId, ( response1Obj.ID + "" ) );
}else{
engine.setData( strPocketPostedId, new java.math.BigDecimal( response1Obj.ID - 0 ) );
}
}
if( strPocketPostedUrl !== null ){
engine.setData( strPocketPostedUrl, response1Obj.URL );
}
} //////// END "main()" /////////////////////////////////////////////////////////////////
function toJsDate( bpmsDateOrDatetimeStr ){
// BPMS Date: "2020-04-01" (subtype "Y/M" "M/D" "Y", not supported)
// BPMS Datetime: "2020-04-01 23:59"
let year = 0;
let monthIndex = 0;
let day = 0;
let hours = 0;
let minutes = 0;
// The ECMA/JavaScript Date object has a large number of methods.
// "Date.parse" is danger (strongly discouraged)
// - new Date("2014-11-10") // Mon Nov 10 2014 09:00:00 GMT+0900 (JST)
// - new Date(2014, 10, 10) // Mon Nov 10 2014 00:00:00 GMT+0900 (JST)
let arrDatetime = bpmsDateOrDatetimeStr.split(" ");
if( arrDatetime.length === 1 ){
let arrDateParts = arrDatetime[0].split("-");
year = parseInt(arrDateParts[0], 10);
monthIndex = parseInt(arrDateParts[1], 10) - 1;
day = parseInt(arrDateParts[2], 10);
}
if( arrDatetime.length === 2 ){
let arrDateParts = arrDatetime[0].split("-");
let arrTimeParts = arrDatetime[1].split(":");
year = parseInt(arrDateParts[0], 10);
monthIndex = parseInt(arrDateParts[1], 10) - 1;
day = parseInt(arrDateParts[2], 10);
hours = parseInt(arrTimeParts[0], 10);
minutes = parseInt(arrTimeParts[1], 10);
}
return new Date( year, monthIndex, day, hours, minutes );
}
/*
Notes-en:
- Adds a new article for your WordPress.com account. (Unpublished state)
- WordPress.com is a service that hosts WordPress sites. It is provided by Automattic itself.
- If in HTML code, it will be generated in "Block editor" mode.
- If in plain text, it will be generated in "Classic editor" mode.
- If the datetime are set in date format, considered as "00:00".
- eg: "2021-12-31" to "2021-12-31 00:00"
- If publish for a future date, it will be posted as a schedule.
- "URL" is not always a published URL.
- Anyone who can log in to the WordPress.com site can access it even before it is published.
- `permalink_URL` will be confirmed when it is published.
APPENDIX-en
- Line breaks in Title and Excerpt are not available. (Template compatibility)
- If necessary, manually start a new line when posting.
- To enable line breaks, set TEXTAREA and modify the BR conversion code
- For the ID of the existing article, refer to the URL of the edit screen.
- Number following `post =`
- Will be added as an article of "default language" in the case of WPML plugin (multilingual site).
- There is no way to add it as an article in a translation language.
- You can also refer to it by "Site ID" (blogid) instead of the WordPress.Com domain.
- Site ID (blogid) is obtained from `GET v1.1/sites/example.blog/` and the "View page source".
- Request is made to the "WordPress.com REST API" (WP.COM API).
- https://developer.wordpress.com/docs/api/
- Note: Not the "WP.REST API" for WordPress.Org.
- Setting example of "HTTP Authentication" (OAuth2)
- Authorization Endpoint URL:
- https://public-api.wordpress.com/oauth2/authorize
- Token Endpoint URL:
- https://public-api.wordpress.com/oauth2/token
- Scope:
- "global", "", "auth" or "media"
- (document) https://developer.wordpress.com/docs/oauth2/
- By default, the token will grant the application full access to a single blog.
- Needs a "global" scope, if to access to all the blogs that users have on WordPress.com.
- Client ID, Consumer Secret:
- ( from https://developer.wordpress.com/apps/ )
- Redirect URLs: https://s.questetra.net/oauth2callback
Notes-ja:
- WordPress.com アカウントの記事を新規追加します。(未公開状態)
- WordPress.com は WordPress sites をホストするサービスです。Automattic 社自身が提供しています。
- 原稿が HTML で書かれている場合、"Block editor" モードで生成されます。
- 原稿が Plain テキストで書かれている場合、"Classic editor" モードで生成されます。
- 日時が日付フォーマットで設定された場合、"00:00" とみなされます。
- 例: "2021-12-31" → "2021-12-31 00:00"
- 未来日付がセットされている場合に公開操作を行うと "スケジュール投稿" になります。
- "記事URL" は公開URLとは限りません。
- WordPress.com サイトにログインできるユーザであれば公開前でもアクセス可能です。
- `permalink_URL` は公開された時点で確定します。
APPENDIX-ja:
- TitleとExcerptの改行は不可の仕様となっています。(テンプレート互換性等に配慮)
- 必要あれば、公開作業の際に手動で改行してください。
- 仕様として改行可としたい場合は TEXTAREA 設定とBR変換のコード改変が必要です。
- 既存記事のIDは、編集画面のURL等を参照してください。
- `post=` に続く数字
- WPMLプラグイン環境(多言語サイト)の場合、"デフォルト言語" の記事として追加されます。
- 翻訳言語の記事として追加する方法はありません。
- WordPress.Com ドメインの代わりに「サイトID」(blogid)で参照することも可能です。
- サイトID(blogid)は、"`GET v1.1/sites/example.blog/`" や "ページのソース" 等から取得します。
- "WordPress.com REST API" (WP.COM API) に対してリクエストが投げられます。
- https://developer.wordpress.com/docs/api/
- 注: WordPress.Org 用の "WP.REST API" ではありません。
- "HTTP認証設定" の例 (OAuth2)
- 認可エンドポイント URL:
- https://public-api.wordpress.com/oauth2/authorize
- トークンエンドポイント URL:
- https://public-api.wordpress.com/oauth2/token
- スコープ:
- "global", "", "auth" or "media"
- (document) https://developer.wordpress.com/docs/oauth2/
- デフォルトでは、1つの blog に対するアクセスが認可されます。
- 全保有 blogs へアクセスできるようにするには "global" をセットします。
- クライアントID, クライアントシークレット:
- ( 開発者ページから取得してください⇒ https://developer.wordpress.com/apps/ )
- Redirect URLs: https://s.questetra.net/oauth2callback
*/