Plugin Directory

Changeset 2831311


Ignore:
Timestamp:
12/09/2022 06:03:44 PM (3 years ago)
Author:
artpi
Message:

Update to version 0.3.5 from GitHub

Location:
writers-block-block
Files:
4 added
10 edited
1 copied

Legend:

Unmodified
Added
Removed
  • writers-block-block/tags/0.3.5/build/index.asset.php

    r2830213 r2831311  
    1 <?php return array('dependencies' => array('wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-data', 'wp-element', 'wp-i18n'), 'version' => '8e011ee4c2d87fd36bb2');
     1<?php return array('dependencies' => array('wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-data', 'wp-element', 'wp-i18n'), 'version' => '25359036be40bb0f77e9');
  • writers-block-block/tags/0.3.5/build/index.css

    r2830213 r2831311  
    1 .wp-block-coauthor-generate-suggestion{padding:0}.wp-block-coauthor-generate-suggestion .components-text-control__input{margin:10px;width:80%}.wp-block-coauthor-generate-suggestion .components-button.is-primary{margin:10px}
     1.wp-block-coauthor-generate-suggestion{padding:0}.wp-block-coauthor-generate-suggestion .components-text-control__input{margin:10px;width:80%}.wp-block-coauthor-generate-suggestion .components-button.is-primary{margin:10px}.wp-block-coauthor-image-image{cursor:pointer;height:128px;margin:12px;width:128px}.wp-block-coauthor-image-image:hover{height:146px;margin:0;width:146px}
  • writers-block-block/tags/0.3.5/build/index.js

    r2830213 r2831311  
    1 !function(){"use strict";var e,t={75:function(e,t,n){var o=window.wp.blocks,r=window.wp.i18n,a=window.wp.element,c=window.wp.apiFetch,i=n.n(c),l=window.wp.blockEditor,s=window.wp.components,u=window.wp.data;function p(e,t,n,o,r){const a={content:o};t&&(a.token=t,n(!1)),r(!0),e({requestedPrompt:!0}),i()({path:"/coauthor/prompt",method:"POST",data:a}).then((t=>{r(!1);const n=t.prompts[0].text.split(" ");for(let t=0;t<n.length;t++){const o=n.slice(0,t).join(" ");setTimeout((()=>e({content:o})),50*t)}})).catch((t=>{"openai_token_missing"===t.code&&(n(!0),r(!1),e({requestedPrompt:!1}))}))}(0,o.registerBlockType)("coauthor/paragraph",{apiVersion:2,title:(0,r.__)("Coauthor Paragraph","coauthor"),description:(0,r.__)("Automatically generate new paragraphs using your existing content, GPT-3 and robots.","coauthor"),category:"common",icon:"welcome-write-blog",supports:{html:!1},attributes:{content:{type:"string",source:"text"},requestedPrompt:{type:"boolean",default:!1}},transforms:{to:[{type:"block",blocks:["core/paragraph"],transform:e=>{let{content:t}=e;return(0,o.createBlock)("core/paragraph",{content:t})}}]},edit:function(e){let{attributes:t,setAttributes:n}=e;const[o,r]=(0,a.useState)(!1),[c,i]=(0,a.useState)(!1),[m,d]=(0,a.useState)(""),g=(0,u.useSelect)((e=>function(e){const t=e.getBlockInsertionPoint().index-1;return e.getBlocks().slice(0,t).filter((function(e){return e&&e.attributes&&e.attributes.content})).map((function(e){return e.attributes.content.replaceAll("<br>","\n\n")})).join("\n\n")}(e("core/block-editor"))),[]);return(0,a.useEffect)((()=>{t.content||t.requestedPrompt||p(n,!1,r,g,i)}),[]),(0,a.createElement)("div",(0,l.useBlockProps)(),o&&(0,a.createElement)("div",null,(0,a.createElement)(s.TextControl,{label:"Please provide the OpenAI token to continue:",value:m,onChange:e=>d(e)}),(0,a.createElement)(s.Button,{isPrimary:!0,onClick:()=>{p(n,m,r,g,i)}},"Submit")),t.content&&!c&&(0,a.createElement)("div",null,(0,a.createElement)("div",{className:"content"},(0,a.createElement)(a.RawHTML,null,t.content.trim().replaceAll("\n","<br/>")))),c&&(0,a.createElement)("div",{style:{padding:"10px",textAlign:"center"}},(0,a.createElement)(s.Spinner,{style:{height:"calc(4px * 20)",width:"calc(4px * 20)"}})))},saveParagraph:function(e){let{attributes:t}=e;const n=l.useBlockProps.save();return(0,a.createElement)("div",n,t.content)}}),(0,o.registerBlockType)("coauthor/image",{apiVersion:2,title:(0,r.__)("Coauthor Image","coauthor"),description:(0,r.__)("Automatically generate an illustration for your post","coauthor"),category:"common",icon:"welcome-write-blog",supports:{html:!1},attributes:{content:{type:"string",source:"text"},requestedPrompt:{type:"string",default:!1}},edit:function(e){let{attributes:t,setAttributes:n,clientId:r}=e;const[c,p]=(0,a.useState)(!1),[m,d]=(0,a.useState)([]),[g,h]=(0,a.useState)(""),{replaceBlock:f}=(0,u.useDispatch)(l.store),{mediaUpload:b}=(0,u.useSelect)((e=>{const{getSettings:t}=e(l.store);return{mediaUpload:t().mediaUpload}}),[]);return(0,a.createElement)("div",(0,l.useBlockProps)(),(0,a.createElement)(s.Placeholder,{label:"Coauthor Image"},!t.requestedPrompt&&(0,a.createElement)("div",null,(0,a.createElement)(s.TextControl,{label:"What would you like to see?",onChange:h}),(0,a.createElement)(s.Button,{isPrimary:!0,onClick:()=>function(e,t,n,o){n(!0),t({requestedPrompt:e}),i()({path:"/coauthor/image",method:"POST",data:{prompt:e}}).then((e=>{n(!1);const t=e.data.map((e=>"data:image/png;base64,"+e.b64_json));o(t)})).catch((e=>{"openai_token_missing"===e.code&&(setPromptedForToken(!0),n(!1),t({requestedPrompt:""}))}))}(g,n,p,d)},"Submit")),!c&&m.length>0&&(0,a.createElement)("div",null,(0,a.createElement)("div",{style:{textAlign:"center",margin:"12px",fontStyle:"italic"}},t.requestedPrompt),(0,a.createElement)("div",{style:{fontSize:"20px",lineHeight:"38px"}},"Please choose your image"),(0,a.createElement)("div",{style:{flexDirection:"row",justifyContent:"space-between",textAlign:"center"}},m.map((e=>(0,a.createElement)("img",{style:{width:"128px",padding:"8px"},src:e,key:e,onClick:async()=>{const n=await fetch(e),a=await n.blob(),c=new File([a],"coauthor_image.png",{type:"image/png"});b({filesList:[c],onFileChange:e=>{let[n]=e;f(r,(0,o.createBlock)("core/image",{url:n.url,caption:t.requestedPrompt,alt:t.requestedPrompt}))},allowedTypes:["image"],onError:e=>{console.error(e)}})}}))))),t.content&&!c&&(0,a.createElement)("div",null,(0,a.createElement)("div",{className:"content"},t.content)),c&&(0,a.createElement)("div",{style:{padding:"10px",textAlign:"center"}},(0,a.createElement)(s.Spinner,{style:{height:"calc(4px * 20)",width:"calc(4px * 20)"}}))))},save:function(e){let{attributes:t}=e;const n=l.useBlockProps.save();return(0,a.createElement)("div",n,t.content)}})}},n={};function o(e){var r=n[e];if(void 0!==r)return r.exports;var a=n[e]={exports:{}};return t[e](a,a.exports,o),a.exports}o.m=t,e=[],o.O=function(t,n,r,a){if(!n){var c=1/0;for(u=0;u<e.length;u++){n=e[u][0],r=e[u][1],a=e[u][2];for(var i=!0,l=0;l<n.length;l++)(!1&a||c>=a)&&Object.keys(o.O).every((function(e){return o.O[e](n[l])}))?n.splice(l--,1):(i=!1,a<c&&(c=a));if(i){e.splice(u--,1);var s=r();void 0!==s&&(t=s)}}return t}a=a||0;for(var u=e.length;u>0&&e[u-1][2]>a;u--)e[u]=e[u-1];e[u]=[n,r,a]},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,{a:t}),t},o.d=function(e,t){for(var n in t)o.o(t,n)&&!o.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},function(){var e={826:0,431:0};o.O.j=function(t){return 0===e[t]};var t=function(t,n){var r,a,c=n[0],i=n[1],l=n[2],s=0;if(c.some((function(t){return 0!==e[t]}))){for(r in i)o.o(i,r)&&(o.m[r]=i[r]);if(l)var u=l(o)}for(t&&t(n);s<c.length;s++)a=c[s],o.o(e,a)&&e[a]&&e[a][0](),e[a]=0;return o.O(u)},n=self.webpackChunkcoauthor=self.webpackChunkcoauthor||[];n.forEach(t.bind(null,0)),n.push=t.bind(null,n.push.bind(n))}();var r=o.O(void 0,[431],(function(){return o(75)}));r=o.O(r)}();
     1!function(){"use strict";var e,t={75:function(e,t,n){var r=window.wp.blocks,o=window.wp.i18n,a=window.wp.element,l=window.wp.apiFetch,i=n.n(l),c=window.wp.blockEditor,s=window.wp.components,u=window.wp.data;function p(e,t,n,r,o){if(n.length<120)return void o(!0);o(!1);const a={content:n=n.slice(-240)};r(!0),e({requestedPrompt:!0}),i()({path:"/wp/v2/openai/completions",method:"POST",data:a}).then((t=>{r(!1);const n=t.prompts[0].text,o=n.split(" ");for(let t=0;t<o.length;t++){const n=o.slice(0,t).join(" ");setTimeout((()=>e({content:n})),50*t)}setTimeout((()=>e({content:n})),50*o.length)})).catch((n=>{"token_missing"===n.code&&(t(!0),r(!1),e({requestedPrompt:!1}))}))}(0,r.registerBlockType)("coauthor/paragraph",{apiVersion:2,title:(0,o.__)("Coauthor Paragraph","coauthor"),description:(0,o.__)("Automatically generate new paragraphs using your existing content, GPT-3 and robots.","coauthor"),category:"common",icon:"welcome-write-blog",supports:{html:!1},attributes:{content:{type:"string",source:"text"},requestedPrompt:{type:"boolean",default:!1}},transforms:{to:[{type:"block",blocks:["core/paragraph"],transform:e=>{let{content:t}=e;return(0,r.createBlock)("core/paragraph",{content:t})}}]},edit:function(e){let{attributes:t,setAttributes:n}=e;const[r,o]=(0,a.useState)(!1),[l,i]=(0,a.useState)(!1),[m,d]=(0,a.useState)(!1),h=(0,u.useSelect)((e=>function(e){const t=e.getBlockInsertionPoint().index-1;return e.getBlocks().slice(0,t).filter((function(e){return e&&e.attributes&&e.attributes.content})).map((function(e){return e.attributes.content.replaceAll("<br>","\n\n")})).join("\n\n")}(e("core/block-editor"))),[]);return(0,a.useEffect)((()=>{t.content||t.requestedPrompt||p(n,o,h,i,d)}),[]),(0,a.createElement)("div",(0,c.useBlockProps)(),m&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Paragraph",instructions:"Please write a little bit more. Coauthor needs more text to make the gears spin."},(0,a.createElement)(s.Button,{isPrimary:!0,onClick:()=>{p(n,o,h,i,d)}},"Retry")),r&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Paragraph",instructions:"Please visit settings and input valid OpenAI token"},(0,a.createElement)(s.Button,{isPrimary:!0,href:"options-general.php?page=coauthor",target:"_blank"},"Visit Coauthor Settings")),t.content&&!l&&(0,a.createElement)("div",null,(0,a.createElement)("div",{className:"content"},(0,a.createElement)(a.RawHTML,null,t.content.trim().replaceAll("\n","<br/>")))),l&&(0,a.createElement)("div",{style:{padding:"10px",textAlign:"center"}},(0,a.createElement)(s.Spinner,{style:{height:"calc(4px * 20)",width:"calc(4px * 20)"}})))},saveParagraph:function(e){let{attributes:t}=e;const n=c.useBlockProps.save();return(0,a.createElement)("div",n,t.content)}}),(0,r.registerBlockType)("coauthor/image",{apiVersion:2,title:(0,o.__)("Coauthor Image","coauthor"),description:(0,o.__)("Automatically generate an illustration for your post","coauthor"),category:"common",icon:"welcome-write-blog",supports:{html:!1},attributes:{content:{type:"string",source:"text"},requestedPrompt:{type:"string",default:!1}},edit:function(e){let{attributes:t,setAttributes:n,clientId:o}=e;const[l,p]=(0,a.useState)(!1),[m,d]=(0,a.useState)([]),[h,g]=(0,a.useState)(""),{replaceBlock:f}=(0,u.useDispatch)(c.store),[b,v]=(0,a.useState)(""),{mediaUpload:w}=(0,u.useSelect)((e=>{const{getSettings:t}=e(c.store);return{mediaUpload:t().mediaUpload}}),[]),E=()=>function(e,t,n,r,o){n(!0),t({requestedPrompt:e}),i()({path:"/wp/v2/openai/images/generations",method:"POST",data:{prompt:e}}).then((e=>{if(n(!1),e.error&&e.error.message)return void o(e.error.message);const t=e.data.map((e=>"data:image/png;base64,"+e.b64_json));r(t)})).catch((e=>{"token_missing"===e.code&&(o("Please visit settings and input valid OpenAI token"),n(!1))}))}(h,n,p,d,v);return(0,a.createElement)("div",(0,c.useBlockProps)(),!l&&b&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Image",notices:[(0,a.createElement)("div",null,b)]},(0,a.createElement)(s.TextareaControl,{label:"What would you like to see?",value:h,onChange:g}),(0,a.createElement)(s.Flex,{direction:"row"},(0,a.createElement)(s.FlexItem,null,(0,a.createElement)(s.Button,{isPrimary:!0,onClick:()=>{v(""),E()}},"Retry")),"Please visit settings and input valid OpenAI token"===b&&(0,a.createElement)(s.FlexItem,null,(0,a.createElement)(s.Button,{href:"options-general.php?page=coauthor",target:"_blank"},"Visit Coauthor Settings")))),!b&&!t.requestedPrompt&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Image"},(0,a.createElement)("div",null,(0,a.createElement)(s.TextareaControl,{label:"What would you like to see?",onChange:g}),(0,a.createElement)(s.Button,{isPrimary:!0,onClick:E},"Submit"))),!b&&!l&&m.length>0&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Image"},(0,a.createElement)("div",null,(0,a.createElement)("div",{style:{textAlign:"center",margin:"12px",fontStyle:"italic"}},t.requestedPrompt),(0,a.createElement)("div",{style:{fontSize:"20px",lineHeight:"38px"}},"Please choose your image"),(0,a.createElement)(s.Flex,{direction:"row",justify:"space-between"},m.map((e=>(0,a.createElement)(s.FlexBlock,{key:e},(0,a.createElement)("img",{className:"wp-block-coauthor-image-image",src:e,onClick:async()=>{if(l)return;p(!0);const n=await fetch(e),a=await n.blob(),i=new File([a],"coauthor_image.png",{type:"image/png"});w({filesList:[i],onFileChange:e=>{let[n]=e;n.id&&f(o,(0,r.createBlock)("core/image",{url:n.url,caption:t.requestedPrompt,alt:t.requestedPrompt}))},allowedTypes:["image"],onError:e=>{console.error(e),p(!1)}})}}))))))),!b&&t.content&&!l&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Image"},(0,a.createElement)("div",null,(0,a.createElement)("div",{className:"content"},t.content))),!b&&l&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Image"},(0,a.createElement)("div",{style:{padding:"10px",textAlign:"center"}},(0,a.createElement)(s.Spinner,{style:{height:"calc(4px * 20)",width:"calc(4px * 20)"}}))))},save:function(e){let{attributes:t}=e;const n=c.useBlockProps.save();return(0,a.createElement)("div",n,t.content)}})}},n={};function r(e){var o=n[e];if(void 0!==o)return o.exports;var a=n[e]={exports:{}};return t[e](a,a.exports,r),a.exports}r.m=t,e=[],r.O=function(t,n,o,a){if(!n){var l=1/0;for(u=0;u<e.length;u++){n=e[u][0],o=e[u][1],a=e[u][2];for(var i=!0,c=0;c<n.length;c++)(!1&a||l>=a)&&Object.keys(r.O).every((function(e){return r.O[e](n[c])}))?n.splice(c--,1):(i=!1,a<l&&(l=a));if(i){e.splice(u--,1);var s=o();void 0!==s&&(t=s)}}return t}a=a||0;for(var u=e.length;u>0&&e[u-1][2]>a;u--)e[u]=e[u-1];e[u]=[n,o,a]},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},function(){var e={826:0,431:0};r.O.j=function(t){return 0===e[t]};var t=function(t,n){var o,a,l=n[0],i=n[1],c=n[2],s=0;if(l.some((function(t){return 0!==e[t]}))){for(o in i)r.o(i,o)&&(r.m[o]=i[o]);if(c)var u=c(r)}for(t&&t(n);s<l.length;s++)a=l[s],r.o(e,a)&&e[a]&&e[a][0](),e[a]=0;return r.O(u)},n=self.webpackChunkcoauthor=self.webpackChunkcoauthor||[];n.forEach(t.bind(null,0)),n.push=t.bind(null,n.push.bind(n))}();var o=r.O(void 0,[431],(function(){return r(75)}));o=r.O(o)}();
  • writers-block-block/tags/0.3.5/coauthor.php

    r2830231 r2831311  
    33 * Plugin Name:     Coauthor - AI Writing Assistant
    44 * Description:     Coauthor is here to help so you can focus on making your posts shine. You can automatically generate new paragraphs and Images using OpenAI.
    5  * Version:         0.3.2
     5 * Version:         0.3.5
    66 * Author:          Artur Piszek (artpi)
    77 * Author URI:      https://piszek.com
     
    1313 */
    1414
    15 /**
    16  * This is an API endpoint to pass requests on to OpenAI
    17  */
    18 function coauthor_call_openai( WP_REST_Request $request ) {
    19     //We are saving responses as transients, so that we don't spam the API.
    20     $parameters = $request->get_params();
    21     $content    = strip_tags( $parameters['content'] );
    22     // Useful for testing:
    23     // sleep(2);
    24     // return array( 'prompts' => [ [ 'text' => 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?' ] ] );
    25 
    26     if ( ! empty( $parameters['token'] ) ) {
    27         $token = $parameters['token'];
    28         update_option( 'openai-token', $token );
    29     } else {
    30         $token = get_option( 'openai-token' );
    31     }
    32 
    33     // We gotta stop if the token is not there.
    34     if ( empty( $token ) || strlen( $token ) < 5 ) {
    35         //TODO: I'm sure there is a way to pass 401 and not 500 here, but this way is not working.
    36         return new WP_Error( 'openai_token_missing', __( 'Please provide a token' ), [ 'status' => 401 ] );
    37     }
    38 
    39     if ( get_transient( 'openai-response' ) ) {
    40         $result = json_decode( get_transient( 'openai-response' ) );
    41         return array( 'prompts' => $result->choices );
    42     }
    43 
    44     $api_call = wp_remote_post(
    45         'https://api.openai.com/v1/completions',
    46         array(
    47             'headers'     => array(
    48                 'Content-Type'  => 'application/json',
    49                 'Authorization' => 'Bearer ' . $token,
    50             ),
    51             'body'        => json_encode(
    52                 [
    53                     'model'      => 'text-davinci-003',
    54                     'prompt'     => $content,
    55                     'max_tokens' => 110, // This is length of generated prompt. A token is about 4 chars. I took 110 from Lex.page.
    56                 ]
    57             ),
    58             'method'      => 'POST',
    59             'data_format' => 'body',
    60             'timeout'     => 60,
    61         )
    62     );
    63     if ( is_wp_error( $api_call ) ) {
    64         return $api_call;
    65     }
    66     // Only allow a new call every 60s - TODO: Maybe there should be some message in the editor that it's recycled message?
    67     set_transient( 'openai-response', $api_call['body'], 60 );
    68     $result = json_decode( $api_call['body'] );
    69     return array( 'prompts' => $result->choices );
    70 }
    71 
    72 
    73 
    74 /**
    75  * This is an API endpoint to pass requests on to OpenAI
    76  */
    77 function coauthor_call_dalle( WP_REST_Request $request ) {
    78     //We are saving responses as transients, so that we don't spam the API.
    79     $parameters = $request->get_params();
    80 
    81     if ( ! empty( $parameters['token'] ) ) {
    82         $token = $parameters['token'];
    83         update_option( 'openai-token', $token );
    84     } else {
    85         $token = get_option( 'openai-token' );
    86     }
    87 
    88     // We gotta stop if the token is not there.
    89     if ( empty( $token ) || strlen( $token ) < 5 ) {
    90         //TODO: I'm sure there is a way to pass 401 and not 500 here, but this way is not working.
    91         return new WP_Error( 'openai_token_missing', __( 'Please provide a token' ), [ 'status' => 401 ] );
    92     }
    93 
    94     if ( get_transient( 'openai-dalle-response-' . md5( $parameters['prompt'] ) ) ) {
    95         return json_decode( get_transient( 'openai-dalle-response-' . md5( $parameters['prompt'] ) ) );
    96     }
    97 
    98     $api_call = wp_remote_post(
    99         'https://api.openai.com/v1/images/generations',
    100         array(
    101             'headers'     => array(
    102                 'Content-Type'  => 'application/json',
    103                 'Authorization' => 'Bearer ' . $token,
    104             ),
    105             'body'        => json_encode(
    106                 [
    107                     'prompt' => $parameters['prompt'],
    108                     'n'      => 4, // Generate 4 options each time,
    109                     'size'   => '512x512',
    110                     'response_format' => 'b64_json'
    111                 ]
    112             ),
    113             'method'      => 'POST',
    114             'data_format' => 'body',
    115             'timeout'     => 60,
    116         )
    117     );
    118     if ( is_wp_error( $api_call ) ) {
    119         return $api_call;
    120     }
    121     // We cache responses for the same prompts for a month.
    122     set_transient( 'openai-dalle-response-' . md5( $parameters['prompt'] ), $api_call['body'], 3600 * 24 ); // Same prompts only allowed once a day.
    123     $result = json_decode( $api_call['body'] );
    124     return $result;
    125 }
    126 
    127 
    128 /**
    129  * Registers all block assets so that they can be enqueued through the block editor
    130  * in the corresponding context.
    131  *
    132  * @see https://developer.wordpress.org/block-editor/tutorials/block-tutorial/applying-styles-with-stylesheets/
    133  */
    13415function create_block_coauthor_init() {
    13516    $dir = __DIR__;
     17
     18    // If this executes in WordPress.com context, we don't need those.
     19    // We don't even sync the settings file.
     20    if ( ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) && file_exists( __DIR__ . '/class.settings.php' ) ) {
     21        require_once __DIR__ . '/class.openai-rest-controller.php';
     22        new OpenAI_REST_Controller();
     23        require_once __DIR__ . '/class.settings.php';
     24        new \Coauthor\Settings();
     25    }
    13626
    13727    $script_asset_path = "$dir/build/index.asset.php";
     
    14636        'create-block-coauthor-block-editor',
    14737        plugins_url( $index_js, __FILE__ ),
    148         array_merge( $script_asset['dependencies'], [ 'wp-data', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-block-editor' ] ), // This is hardcoded here because Jetpack does not play nice with ES6 dependencies for these.
     38        array_merge( $script_asset['dependencies'], array( 'wp-data', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-block-editor' ) ), // This is hardcoded here because Jetpack does not play nice with ES6 dependencies for these.
    14939        $script_asset['version']
    15040    );
     
    17565        )
    17666    );
    177     add_action(
    178         'rest_api_init',
    179         function () {
    180             register_rest_route(
    181                 'coauthor',
    182                 '/prompt',
    183                 array(
    184                     'methods'             => 'POST',
    185                     'callback'            => 'coauthor_call_openai',
    186                     'args'                => array(
    187                         'content' => array( 'required' => true ),
    188                         'token'   => array( 'required' => false ),
    189                     ),
    190                     'permission_callback' => function () {
    191                         // Only for admins for time being
    192                         return current_user_can( 'edit_posts' );
    193                     },
    194                 )
    195             );
    196             register_rest_route(
    197                 'coauthor',
    198                 '/image',
    199                 array(
    200                     'methods'             => 'POST',
    201                     'callback'            => 'coauthor_call_dalle',
    202                     'args'                => array(
    203                         'prompt' => array( 'required' => true ),
    204                         'token'  => array( 'required' => false ),
    205                     ),
    206                     'permission_callback' => function () {
    207                         // Only for admins for time being
    208                         return current_user_can( 'edit_posts' );
    209                     },
    210                 )
    211             );
    212         }
    213     );
    21467}
    21568
  • writers-block-block/tags/0.3.5/readme.txt

    r2830231 r2831311  
    44Requires at least: 5.3.1
    55Tested up to:      6.1.1
    6 Stable tag:        0.3.2
     6Stable tag:        0.3.5
    77Requires PHP:      7.0.0
    88License:           GPL-2.0-or-later
  • writers-block-block/trunk/build/index.asset.php

    r2830213 r2831311  
    1 <?php return array('dependencies' => array('wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-data', 'wp-element', 'wp-i18n'), 'version' => '8e011ee4c2d87fd36bb2');
     1<?php return array('dependencies' => array('wp-api-fetch', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-data', 'wp-element', 'wp-i18n'), 'version' => '25359036be40bb0f77e9');
  • writers-block-block/trunk/build/index.css

    r2830213 r2831311  
    1 .wp-block-coauthor-generate-suggestion{padding:0}.wp-block-coauthor-generate-suggestion .components-text-control__input{margin:10px;width:80%}.wp-block-coauthor-generate-suggestion .components-button.is-primary{margin:10px}
     1.wp-block-coauthor-generate-suggestion{padding:0}.wp-block-coauthor-generate-suggestion .components-text-control__input{margin:10px;width:80%}.wp-block-coauthor-generate-suggestion .components-button.is-primary{margin:10px}.wp-block-coauthor-image-image{cursor:pointer;height:128px;margin:12px;width:128px}.wp-block-coauthor-image-image:hover{height:146px;margin:0;width:146px}
  • writers-block-block/trunk/build/index.js

    r2830213 r2831311  
    1 !function(){"use strict";var e,t={75:function(e,t,n){var o=window.wp.blocks,r=window.wp.i18n,a=window.wp.element,c=window.wp.apiFetch,i=n.n(c),l=window.wp.blockEditor,s=window.wp.components,u=window.wp.data;function p(e,t,n,o,r){const a={content:o};t&&(a.token=t,n(!1)),r(!0),e({requestedPrompt:!0}),i()({path:"/coauthor/prompt",method:"POST",data:a}).then((t=>{r(!1);const n=t.prompts[0].text.split(" ");for(let t=0;t<n.length;t++){const o=n.slice(0,t).join(" ");setTimeout((()=>e({content:o})),50*t)}})).catch((t=>{"openai_token_missing"===t.code&&(n(!0),r(!1),e({requestedPrompt:!1}))}))}(0,o.registerBlockType)("coauthor/paragraph",{apiVersion:2,title:(0,r.__)("Coauthor Paragraph","coauthor"),description:(0,r.__)("Automatically generate new paragraphs using your existing content, GPT-3 and robots.","coauthor"),category:"common",icon:"welcome-write-blog",supports:{html:!1},attributes:{content:{type:"string",source:"text"},requestedPrompt:{type:"boolean",default:!1}},transforms:{to:[{type:"block",blocks:["core/paragraph"],transform:e=>{let{content:t}=e;return(0,o.createBlock)("core/paragraph",{content:t})}}]},edit:function(e){let{attributes:t,setAttributes:n}=e;const[o,r]=(0,a.useState)(!1),[c,i]=(0,a.useState)(!1),[m,d]=(0,a.useState)(""),g=(0,u.useSelect)((e=>function(e){const t=e.getBlockInsertionPoint().index-1;return e.getBlocks().slice(0,t).filter((function(e){return e&&e.attributes&&e.attributes.content})).map((function(e){return e.attributes.content.replaceAll("<br>","\n\n")})).join("\n\n")}(e("core/block-editor"))),[]);return(0,a.useEffect)((()=>{t.content||t.requestedPrompt||p(n,!1,r,g,i)}),[]),(0,a.createElement)("div",(0,l.useBlockProps)(),o&&(0,a.createElement)("div",null,(0,a.createElement)(s.TextControl,{label:"Please provide the OpenAI token to continue:",value:m,onChange:e=>d(e)}),(0,a.createElement)(s.Button,{isPrimary:!0,onClick:()=>{p(n,m,r,g,i)}},"Submit")),t.content&&!c&&(0,a.createElement)("div",null,(0,a.createElement)("div",{className:"content"},(0,a.createElement)(a.RawHTML,null,t.content.trim().replaceAll("\n","<br/>")))),c&&(0,a.createElement)("div",{style:{padding:"10px",textAlign:"center"}},(0,a.createElement)(s.Spinner,{style:{height:"calc(4px * 20)",width:"calc(4px * 20)"}})))},saveParagraph:function(e){let{attributes:t}=e;const n=l.useBlockProps.save();return(0,a.createElement)("div",n,t.content)}}),(0,o.registerBlockType)("coauthor/image",{apiVersion:2,title:(0,r.__)("Coauthor Image","coauthor"),description:(0,r.__)("Automatically generate an illustration for your post","coauthor"),category:"common",icon:"welcome-write-blog",supports:{html:!1},attributes:{content:{type:"string",source:"text"},requestedPrompt:{type:"string",default:!1}},edit:function(e){let{attributes:t,setAttributes:n,clientId:r}=e;const[c,p]=(0,a.useState)(!1),[m,d]=(0,a.useState)([]),[g,h]=(0,a.useState)(""),{replaceBlock:f}=(0,u.useDispatch)(l.store),{mediaUpload:b}=(0,u.useSelect)((e=>{const{getSettings:t}=e(l.store);return{mediaUpload:t().mediaUpload}}),[]);return(0,a.createElement)("div",(0,l.useBlockProps)(),(0,a.createElement)(s.Placeholder,{label:"Coauthor Image"},!t.requestedPrompt&&(0,a.createElement)("div",null,(0,a.createElement)(s.TextControl,{label:"What would you like to see?",onChange:h}),(0,a.createElement)(s.Button,{isPrimary:!0,onClick:()=>function(e,t,n,o){n(!0),t({requestedPrompt:e}),i()({path:"/coauthor/image",method:"POST",data:{prompt:e}}).then((e=>{n(!1);const t=e.data.map((e=>"data:image/png;base64,"+e.b64_json));o(t)})).catch((e=>{"openai_token_missing"===e.code&&(setPromptedForToken(!0),n(!1),t({requestedPrompt:""}))}))}(g,n,p,d)},"Submit")),!c&&m.length>0&&(0,a.createElement)("div",null,(0,a.createElement)("div",{style:{textAlign:"center",margin:"12px",fontStyle:"italic"}},t.requestedPrompt),(0,a.createElement)("div",{style:{fontSize:"20px",lineHeight:"38px"}},"Please choose your image"),(0,a.createElement)("div",{style:{flexDirection:"row",justifyContent:"space-between",textAlign:"center"}},m.map((e=>(0,a.createElement)("img",{style:{width:"128px",padding:"8px"},src:e,key:e,onClick:async()=>{const n=await fetch(e),a=await n.blob(),c=new File([a],"coauthor_image.png",{type:"image/png"});b({filesList:[c],onFileChange:e=>{let[n]=e;f(r,(0,o.createBlock)("core/image",{url:n.url,caption:t.requestedPrompt,alt:t.requestedPrompt}))},allowedTypes:["image"],onError:e=>{console.error(e)}})}}))))),t.content&&!c&&(0,a.createElement)("div",null,(0,a.createElement)("div",{className:"content"},t.content)),c&&(0,a.createElement)("div",{style:{padding:"10px",textAlign:"center"}},(0,a.createElement)(s.Spinner,{style:{height:"calc(4px * 20)",width:"calc(4px * 20)"}}))))},save:function(e){let{attributes:t}=e;const n=l.useBlockProps.save();return(0,a.createElement)("div",n,t.content)}})}},n={};function o(e){var r=n[e];if(void 0!==r)return r.exports;var a=n[e]={exports:{}};return t[e](a,a.exports,o),a.exports}o.m=t,e=[],o.O=function(t,n,r,a){if(!n){var c=1/0;for(u=0;u<e.length;u++){n=e[u][0],r=e[u][1],a=e[u][2];for(var i=!0,l=0;l<n.length;l++)(!1&a||c>=a)&&Object.keys(o.O).every((function(e){return o.O[e](n[l])}))?n.splice(l--,1):(i=!1,a<c&&(c=a));if(i){e.splice(u--,1);var s=r();void 0!==s&&(t=s)}}return t}a=a||0;for(var u=e.length;u>0&&e[u-1][2]>a;u--)e[u]=e[u-1];e[u]=[n,r,a]},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,{a:t}),t},o.d=function(e,t){for(var n in t)o.o(t,n)&&!o.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},function(){var e={826:0,431:0};o.O.j=function(t){return 0===e[t]};var t=function(t,n){var r,a,c=n[0],i=n[1],l=n[2],s=0;if(c.some((function(t){return 0!==e[t]}))){for(r in i)o.o(i,r)&&(o.m[r]=i[r]);if(l)var u=l(o)}for(t&&t(n);s<c.length;s++)a=c[s],o.o(e,a)&&e[a]&&e[a][0](),e[a]=0;return o.O(u)},n=self.webpackChunkcoauthor=self.webpackChunkcoauthor||[];n.forEach(t.bind(null,0)),n.push=t.bind(null,n.push.bind(n))}();var r=o.O(void 0,[431],(function(){return o(75)}));r=o.O(r)}();
     1!function(){"use strict";var e,t={75:function(e,t,n){var r=window.wp.blocks,o=window.wp.i18n,a=window.wp.element,l=window.wp.apiFetch,i=n.n(l),c=window.wp.blockEditor,s=window.wp.components,u=window.wp.data;function p(e,t,n,r,o){if(n.length<120)return void o(!0);o(!1);const a={content:n=n.slice(-240)};r(!0),e({requestedPrompt:!0}),i()({path:"/wp/v2/openai/completions",method:"POST",data:a}).then((t=>{r(!1);const n=t.prompts[0].text,o=n.split(" ");for(let t=0;t<o.length;t++){const n=o.slice(0,t).join(" ");setTimeout((()=>e({content:n})),50*t)}setTimeout((()=>e({content:n})),50*o.length)})).catch((n=>{"token_missing"===n.code&&(t(!0),r(!1),e({requestedPrompt:!1}))}))}(0,r.registerBlockType)("coauthor/paragraph",{apiVersion:2,title:(0,o.__)("Coauthor Paragraph","coauthor"),description:(0,o.__)("Automatically generate new paragraphs using your existing content, GPT-3 and robots.","coauthor"),category:"common",icon:"welcome-write-blog",supports:{html:!1},attributes:{content:{type:"string",source:"text"},requestedPrompt:{type:"boolean",default:!1}},transforms:{to:[{type:"block",blocks:["core/paragraph"],transform:e=>{let{content:t}=e;return(0,r.createBlock)("core/paragraph",{content:t})}}]},edit:function(e){let{attributes:t,setAttributes:n}=e;const[r,o]=(0,a.useState)(!1),[l,i]=(0,a.useState)(!1),[m,d]=(0,a.useState)(!1),h=(0,u.useSelect)((e=>function(e){const t=e.getBlockInsertionPoint().index-1;return e.getBlocks().slice(0,t).filter((function(e){return e&&e.attributes&&e.attributes.content})).map((function(e){return e.attributes.content.replaceAll("<br>","\n\n")})).join("\n\n")}(e("core/block-editor"))),[]);return(0,a.useEffect)((()=>{t.content||t.requestedPrompt||p(n,o,h,i,d)}),[]),(0,a.createElement)("div",(0,c.useBlockProps)(),m&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Paragraph",instructions:"Please write a little bit more. Coauthor needs more text to make the gears spin."},(0,a.createElement)(s.Button,{isPrimary:!0,onClick:()=>{p(n,o,h,i,d)}},"Retry")),r&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Paragraph",instructions:"Please visit settings and input valid OpenAI token"},(0,a.createElement)(s.Button,{isPrimary:!0,href:"options-general.php?page=coauthor",target:"_blank"},"Visit Coauthor Settings")),t.content&&!l&&(0,a.createElement)("div",null,(0,a.createElement)("div",{className:"content"},(0,a.createElement)(a.RawHTML,null,t.content.trim().replaceAll("\n","<br/>")))),l&&(0,a.createElement)("div",{style:{padding:"10px",textAlign:"center"}},(0,a.createElement)(s.Spinner,{style:{height:"calc(4px * 20)",width:"calc(4px * 20)"}})))},saveParagraph:function(e){let{attributes:t}=e;const n=c.useBlockProps.save();return(0,a.createElement)("div",n,t.content)}}),(0,r.registerBlockType)("coauthor/image",{apiVersion:2,title:(0,o.__)("Coauthor Image","coauthor"),description:(0,o.__)("Automatically generate an illustration for your post","coauthor"),category:"common",icon:"welcome-write-blog",supports:{html:!1},attributes:{content:{type:"string",source:"text"},requestedPrompt:{type:"string",default:!1}},edit:function(e){let{attributes:t,setAttributes:n,clientId:o}=e;const[l,p]=(0,a.useState)(!1),[m,d]=(0,a.useState)([]),[h,g]=(0,a.useState)(""),{replaceBlock:f}=(0,u.useDispatch)(c.store),[b,v]=(0,a.useState)(""),{mediaUpload:w}=(0,u.useSelect)((e=>{const{getSettings:t}=e(c.store);return{mediaUpload:t().mediaUpload}}),[]),E=()=>function(e,t,n,r,o){n(!0),t({requestedPrompt:e}),i()({path:"/wp/v2/openai/images/generations",method:"POST",data:{prompt:e}}).then((e=>{if(n(!1),e.error&&e.error.message)return void o(e.error.message);const t=e.data.map((e=>"data:image/png;base64,"+e.b64_json));r(t)})).catch((e=>{"token_missing"===e.code&&(o("Please visit settings and input valid OpenAI token"),n(!1))}))}(h,n,p,d,v);return(0,a.createElement)("div",(0,c.useBlockProps)(),!l&&b&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Image",notices:[(0,a.createElement)("div",null,b)]},(0,a.createElement)(s.TextareaControl,{label:"What would you like to see?",value:h,onChange:g}),(0,a.createElement)(s.Flex,{direction:"row"},(0,a.createElement)(s.FlexItem,null,(0,a.createElement)(s.Button,{isPrimary:!0,onClick:()=>{v(""),E()}},"Retry")),"Please visit settings and input valid OpenAI token"===b&&(0,a.createElement)(s.FlexItem,null,(0,a.createElement)(s.Button,{href:"options-general.php?page=coauthor",target:"_blank"},"Visit Coauthor Settings")))),!b&&!t.requestedPrompt&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Image"},(0,a.createElement)("div",null,(0,a.createElement)(s.TextareaControl,{label:"What would you like to see?",onChange:g}),(0,a.createElement)(s.Button,{isPrimary:!0,onClick:E},"Submit"))),!b&&!l&&m.length>0&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Image"},(0,a.createElement)("div",null,(0,a.createElement)("div",{style:{textAlign:"center",margin:"12px",fontStyle:"italic"}},t.requestedPrompt),(0,a.createElement)("div",{style:{fontSize:"20px",lineHeight:"38px"}},"Please choose your image"),(0,a.createElement)(s.Flex,{direction:"row",justify:"space-between"},m.map((e=>(0,a.createElement)(s.FlexBlock,{key:e},(0,a.createElement)("img",{className:"wp-block-coauthor-image-image",src:e,onClick:async()=>{if(l)return;p(!0);const n=await fetch(e),a=await n.blob(),i=new File([a],"coauthor_image.png",{type:"image/png"});w({filesList:[i],onFileChange:e=>{let[n]=e;n.id&&f(o,(0,r.createBlock)("core/image",{url:n.url,caption:t.requestedPrompt,alt:t.requestedPrompt}))},allowedTypes:["image"],onError:e=>{console.error(e),p(!1)}})}}))))))),!b&&t.content&&!l&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Image"},(0,a.createElement)("div",null,(0,a.createElement)("div",{className:"content"},t.content))),!b&&l&&(0,a.createElement)(s.Placeholder,{label:"Coauthor Image"},(0,a.createElement)("div",{style:{padding:"10px",textAlign:"center"}},(0,a.createElement)(s.Spinner,{style:{height:"calc(4px * 20)",width:"calc(4px * 20)"}}))))},save:function(e){let{attributes:t}=e;const n=c.useBlockProps.save();return(0,a.createElement)("div",n,t.content)}})}},n={};function r(e){var o=n[e];if(void 0!==o)return o.exports;var a=n[e]={exports:{}};return t[e](a,a.exports,r),a.exports}r.m=t,e=[],r.O=function(t,n,o,a){if(!n){var l=1/0;for(u=0;u<e.length;u++){n=e[u][0],o=e[u][1],a=e[u][2];for(var i=!0,c=0;c<n.length;c++)(!1&a||l>=a)&&Object.keys(r.O).every((function(e){return r.O[e](n[c])}))?n.splice(c--,1):(i=!1,a<l&&(l=a));if(i){e.splice(u--,1);var s=o();void 0!==s&&(t=s)}}return t}a=a||0;for(var u=e.length;u>0&&e[u-1][2]>a;u--)e[u]=e[u-1];e[u]=[n,o,a]},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},function(){var e={826:0,431:0};r.O.j=function(t){return 0===e[t]};var t=function(t,n){var o,a,l=n[0],i=n[1],c=n[2],s=0;if(l.some((function(t){return 0!==e[t]}))){for(o in i)r.o(i,o)&&(r.m[o]=i[o]);if(c)var u=c(r)}for(t&&t(n);s<l.length;s++)a=l[s],r.o(e,a)&&e[a]&&e[a][0](),e[a]=0;return r.O(u)},n=self.webpackChunkcoauthor=self.webpackChunkcoauthor||[];n.forEach(t.bind(null,0)),n.push=t.bind(null,n.push.bind(n))}();var o=r.O(void 0,[431],(function(){return r(75)}));o=r.O(o)}();
  • writers-block-block/trunk/coauthor.php

    r2830231 r2831311  
    33 * Plugin Name:     Coauthor - AI Writing Assistant
    44 * Description:     Coauthor is here to help so you can focus on making your posts shine. You can automatically generate new paragraphs and Images using OpenAI.
    5  * Version:         0.3.2
     5 * Version:         0.3.5
    66 * Author:          Artur Piszek (artpi)
    77 * Author URI:      https://piszek.com
     
    1313 */
    1414
    15 /**
    16  * This is an API endpoint to pass requests on to OpenAI
    17  */
    18 function coauthor_call_openai( WP_REST_Request $request ) {
    19     //We are saving responses as transients, so that we don't spam the API.
    20     $parameters = $request->get_params();
    21     $content    = strip_tags( $parameters['content'] );
    22     // Useful for testing:
    23     // sleep(2);
    24     // return array( 'prompts' => [ [ 'text' => 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?' ] ] );
    25 
    26     if ( ! empty( $parameters['token'] ) ) {
    27         $token = $parameters['token'];
    28         update_option( 'openai-token', $token );
    29     } else {
    30         $token = get_option( 'openai-token' );
    31     }
    32 
    33     // We gotta stop if the token is not there.
    34     if ( empty( $token ) || strlen( $token ) < 5 ) {
    35         //TODO: I'm sure there is a way to pass 401 and not 500 here, but this way is not working.
    36         return new WP_Error( 'openai_token_missing', __( 'Please provide a token' ), [ 'status' => 401 ] );
    37     }
    38 
    39     if ( get_transient( 'openai-response' ) ) {
    40         $result = json_decode( get_transient( 'openai-response' ) );
    41         return array( 'prompts' => $result->choices );
    42     }
    43 
    44     $api_call = wp_remote_post(
    45         'https://api.openai.com/v1/completions',
    46         array(
    47             'headers'     => array(
    48                 'Content-Type'  => 'application/json',
    49                 'Authorization' => 'Bearer ' . $token,
    50             ),
    51             'body'        => json_encode(
    52                 [
    53                     'model'      => 'text-davinci-003',
    54                     'prompt'     => $content,
    55                     'max_tokens' => 110, // This is length of generated prompt. A token is about 4 chars. I took 110 from Lex.page.
    56                 ]
    57             ),
    58             'method'      => 'POST',
    59             'data_format' => 'body',
    60             'timeout'     => 60,
    61         )
    62     );
    63     if ( is_wp_error( $api_call ) ) {
    64         return $api_call;
    65     }
    66     // Only allow a new call every 60s - TODO: Maybe there should be some message in the editor that it's recycled message?
    67     set_transient( 'openai-response', $api_call['body'], 60 );
    68     $result = json_decode( $api_call['body'] );
    69     return array( 'prompts' => $result->choices );
    70 }
    71 
    72 
    73 
    74 /**
    75  * This is an API endpoint to pass requests on to OpenAI
    76  */
    77 function coauthor_call_dalle( WP_REST_Request $request ) {
    78     //We are saving responses as transients, so that we don't spam the API.
    79     $parameters = $request->get_params();
    80 
    81     if ( ! empty( $parameters['token'] ) ) {
    82         $token = $parameters['token'];
    83         update_option( 'openai-token', $token );
    84     } else {
    85         $token = get_option( 'openai-token' );
    86     }
    87 
    88     // We gotta stop if the token is not there.
    89     if ( empty( $token ) || strlen( $token ) < 5 ) {
    90         //TODO: I'm sure there is a way to pass 401 and not 500 here, but this way is not working.
    91         return new WP_Error( 'openai_token_missing', __( 'Please provide a token' ), [ 'status' => 401 ] );
    92     }
    93 
    94     if ( get_transient( 'openai-dalle-response-' . md5( $parameters['prompt'] ) ) ) {
    95         return json_decode( get_transient( 'openai-dalle-response-' . md5( $parameters['prompt'] ) ) );
    96     }
    97 
    98     $api_call = wp_remote_post(
    99         'https://api.openai.com/v1/images/generations',
    100         array(
    101             'headers'     => array(
    102                 'Content-Type'  => 'application/json',
    103                 'Authorization' => 'Bearer ' . $token,
    104             ),
    105             'body'        => json_encode(
    106                 [
    107                     'prompt' => $parameters['prompt'],
    108                     'n'      => 4, // Generate 4 options each time,
    109                     'size'   => '512x512',
    110                     'response_format' => 'b64_json'
    111                 ]
    112             ),
    113             'method'      => 'POST',
    114             'data_format' => 'body',
    115             'timeout'     => 60,
    116         )
    117     );
    118     if ( is_wp_error( $api_call ) ) {
    119         return $api_call;
    120     }
    121     // We cache responses for the same prompts for a month.
    122     set_transient( 'openai-dalle-response-' . md5( $parameters['prompt'] ), $api_call['body'], 3600 * 24 ); // Same prompts only allowed once a day.
    123     $result = json_decode( $api_call['body'] );
    124     return $result;
    125 }
    126 
    127 
    128 /**
    129  * Registers all block assets so that they can be enqueued through the block editor
    130  * in the corresponding context.
    131  *
    132  * @see https://developer.wordpress.org/block-editor/tutorials/block-tutorial/applying-styles-with-stylesheets/
    133  */
    13415function create_block_coauthor_init() {
    13516    $dir = __DIR__;
     17
     18    // If this executes in WordPress.com context, we don't need those.
     19    // We don't even sync the settings file.
     20    if ( ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) && file_exists( __DIR__ . '/class.settings.php' ) ) {
     21        require_once __DIR__ . '/class.openai-rest-controller.php';
     22        new OpenAI_REST_Controller();
     23        require_once __DIR__ . '/class.settings.php';
     24        new \Coauthor\Settings();
     25    }
    13626
    13727    $script_asset_path = "$dir/build/index.asset.php";
     
    14636        'create-block-coauthor-block-editor',
    14737        plugins_url( $index_js, __FILE__ ),
    148         array_merge( $script_asset['dependencies'], [ 'wp-data', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-block-editor' ] ), // This is hardcoded here because Jetpack does not play nice with ES6 dependencies for these.
     38        array_merge( $script_asset['dependencies'], array( 'wp-data', 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-block-editor' ) ), // This is hardcoded here because Jetpack does not play nice with ES6 dependencies for these.
    14939        $script_asset['version']
    15040    );
     
    17565        )
    17666    );
    177     add_action(
    178         'rest_api_init',
    179         function () {
    180             register_rest_route(
    181                 'coauthor',
    182                 '/prompt',
    183                 array(
    184                     'methods'             => 'POST',
    185                     'callback'            => 'coauthor_call_openai',
    186                     'args'                => array(
    187                         'content' => array( 'required' => true ),
    188                         'token'   => array( 'required' => false ),
    189                     ),
    190                     'permission_callback' => function () {
    191                         // Only for admins for time being
    192                         return current_user_can( 'edit_posts' );
    193                     },
    194                 )
    195             );
    196             register_rest_route(
    197                 'coauthor',
    198                 '/image',
    199                 array(
    200                     'methods'             => 'POST',
    201                     'callback'            => 'coauthor_call_dalle',
    202                     'args'                => array(
    203                         'prompt' => array( 'required' => true ),
    204                         'token'  => array( 'required' => false ),
    205                     ),
    206                     'permission_callback' => function () {
    207                         // Only for admins for time being
    208                         return current_user_can( 'edit_posts' );
    209                     },
    210                 )
    211             );
    212         }
    213     );
    21467}
    21568
  • writers-block-block/trunk/readme.txt

    r2830231 r2831311  
    44Requires at least: 5.3.1
    55Tested up to:      6.1.1
    6 Stable tag:        0.3.2
     6Stable tag:        0.3.5
    77Requires PHP:      7.0.0
    88License:           GPL-2.0-or-later
Note: See TracChangeset for help on using the changeset viewer.