@cloudimage-strapi/content-plugin 1.0.1 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,28 +6,6 @@
6
6
 
7
7
  ## Config
8
8
 
9
-
10
- `config/middlewares.js`
11
-
12
- Replace `'strapi::security',` with:
13
-
14
- ```
15
- {
16
- name: 'strapi::security',
17
- config: {
18
- contentSecurityPolicy: {
19
- useDefaults: true,
20
- directives: {
21
- 'connect-src': ["'self'", 'https:'],
22
- 'img-src': ["'self'", 'data:', 'blob:', 'scaleflex.cloudimg.io', 'assets.scaleflex.com', '*.cloudimg.io'],
23
- 'media-src': ["'self'", 'data:', 'blob:', 'scaleflex.cloudimg.io', 'assets.scaleflex.com', '*.cloudimg.io'],
24
- upgradeInsecureRequests: null,
25
- },
26
- },
27
- },
28
- },
29
- ```
30
-
31
9
  `config/server.js`
32
10
 
33
11
  Append `url: 'domain (including the http/https:// part)'`
@@ -60,14 +38,14 @@ If you enter nothing or an invalid token, you will get this error.
60
38
 
61
39
  In the rare case that we can’t auto-detect whether token is v7 or not, you will get the option to manually set it.
62
40
 
63
- ![](https://user-images.githubusercontent.com/20809372/210363178-0bb4c4b7-6fe6-4bee-8226-61fe0128c92f.png)
41
+ ![](https://user-images.githubusercontent.com/20809372/226889919-71a072b9-c648-4fd4-b0c4-e5c89351c302.png)
64
42
 
65
43
  ## What the plugin brings
66
44
 
67
- 1. This plugin simple gives client an interface to save the configuration settings.
68
- 2. It also allows clients to Cloudimage-ize all previous images:
45
+ 1. This plugin simply gives client an interface to save the configuration settings.
46
+ 2. It also allows clients to Optimize (resize and accelerate) all previous images:
69
47
 
70
- ![](https://user-images.githubusercontent.com/20809372/210363230-37094499-ecea-4f14-92e3-0a7217bb9a18.png)
48
+ ![](https://user-images.githubusercontent.com/20809372/226889956-a841eb93-2eaf-4608-ad86-7a4ebcc4aff5.png)
71
49
 
72
- - It will NOT Cloudimage-ize images that are already hosted on Filerobot.
73
- - It will only sync images, no videos nor audios.
50
+ - It will NOT Optimize (resize and accelerate) images that are already hosted on [Filerobot](https://www.scaleflex.com/dam-filerobot)
51
+ - It will only sync images, no other media like video or audio.
@@ -1,12 +1,11 @@
1
- /**
2
- *
3
- * PluginIcon
4
- *
5
- */
6
-
7
- import React from 'react';
8
- import Puzzle from '@strapi/icons/Puzzle';
9
-
10
- const PluginIcon = () => <img src="https://assets.scaleflex.com/Marketing/Logos/Cloudimage+Logos/Favicon/CLOUDIMAGE+favicon.ico" width="16" height="16" />;
11
-
12
- export default PluginIcon;
1
+ /**
2
+ *
3
+ * PluginIcon
4
+ *
5
+ */
6
+
7
+ import React from 'react';
8
+
9
+ const PluginIcon = () => <img src="https://assets.scaleflex.com/Marketing/Logos/Cloudimage+Logos/Logo+icon/icon.svg" width="16" height="16" />;
10
+
11
+ export default PluginIcon;
@@ -4,7 +4,7 @@ import pluginId from './pluginId';
4
4
  import Initializer from './components/Initializer';
5
5
  import PluginIcon from './components/PluginIcon';
6
6
 
7
- const name = "scaleflex-cloudimage";
7
+ const name = "cloudimage-by-scaleflex";
8
8
 
9
9
  export default {
10
10
  register(app) {
@@ -125,11 +125,11 @@ const HomePage = () => {
125
125
 
126
126
  if (result.response === false)
127
127
  {
128
- setUpdateMessage('Update was not successful. Please try again later.');
128
+ setUpdateMessage('Image optimization was not successful. Please try again later.');
129
129
  }
130
130
  else
131
131
  {
132
- setUpdateMessage(`${result.response} updates was successful.`);
132
+ setUpdateMessage(`${result.response} image optimizations were successful.`);
133
133
  }
134
134
 
135
135
  setDisplayUpdateResult(true);
@@ -156,12 +156,12 @@ const HomePage = () => {
156
156
  )}
157
157
  {updateCount > -1 && (
158
158
  <Alert onClose={() => setUpdateCount(-1)} closeLabel="Close alert" variant={'success'}>
159
- There are {updateCount} image URLs to be updated.
159
+ There are {updateCount} image URLs to be optimized.
160
160
  </Alert>
161
161
  )}
162
162
  {displayUpdateResult && (
163
163
  <Alert onClose={() => setDisplayUpdateResult(false)} closeLabel="Close alert" variant={'success'}>
164
- {(updateCount <= 0) ? 'None are to be updated.' : updateMessage}
164
+ {(updateCount <= 0) ? 'None are to be optimized.' : updateMessage}
165
165
  </Alert>
166
166
  )}
167
167
  <Box paddingTop={5} paddingRight={8}>
@@ -188,8 +188,8 @@ const HomePage = () => {
188
188
  <Button disabled={disabledAllButtons} onClick={() => saveConfiguration()}>Save configuration</Button>
189
189
  </Box>
190
190
  <Stack horizontal spacing={4}>
191
- <Button disabled={disabledAllButtons || disableUpdateButtons} onClick={() => countUpdate()}>Count updatable images</Button>
192
- <Button disabled={disabledAllButtons || disableUpdateButtons} onClick={() => updateMedia()}>Update old images</Button>
191
+ <Button disabled={disabledAllButtons || disableUpdateButtons} onClick={() => countUpdate()}>Count optimizable images</Button>
192
+ <Button disabled={disabledAllButtons || disableUpdateButtons} onClick={() => updateMedia()}>Optimize old images</Button>
193
193
  </Stack>
194
194
  </Stack>
195
195
  </>
@@ -1,5 +1,5 @@
1
1
  import pluginPkg from '../../package.json';
2
2
 
3
- const pluginId = "scaleflex-cloudimage".replace(/^(@[^-,.][\w,-]+\/|strapi-)plugin-/i, '');
3
+ const pluginId = "cloudimage-by-scaleflex".replace(/^(@[^-,.][\w,-]+\/|strapi-)plugin-/i, '');
4
4
 
5
5
  export default pluginId;
package/package.json CHANGED
@@ -1,32 +1,87 @@
1
- {
2
- "name": "@cloudimage-strapi/content-plugin",
3
- "version": "1.0.1",
4
- "description": "Strapi v4 plugin for Filerobot by Scaleflex",
5
- "strapi": {
6
- "name": "scaleflex-cloudimage",
7
- "description": "Scaleflex Cloudimage",
8
- "kind": "plugin",
9
- "displayName": "Scaleflex Cloudimage"
10
- },
11
- "peerDependencies": {
12
- "@strapi/strapi": "^4.3.0"
13
- },
14
- "author": {
15
- "name": "Scaleflex"
16
- },
17
- "maintainers": [
18
- {
19
- "name": "Ruslan Aliyev"
20
- }
21
- ],
22
- "engines": {
23
- "node": ">=12.x. <=16.x.x",
24
- "npm": ">=6.0.0"
25
- },
26
- "license": "MIT",
27
- "keywords": [
28
- "scaleflex",
29
- "filerobot",
30
- "strapi"
31
- ]
32
- }
1
+ {
2
+ "name": "@cloudimage-strapi/content-plugin",
3
+ "version": "1.0.4",
4
+ "description": "Strapi v4 plugin for Cloudimage by Scaleflex",
5
+ "strapi": {
6
+ "name": "cloudimage-by-scaleflex",
7
+ "description": "The easiest way to resize, compress, optimize and distribute your images lightning fast to your users on any device via CDN.",
8
+ "kind": "plugin",
9
+ "displayName": "Cloudimage by Scaleflex"
10
+ },
11
+ "devDependencies": {
12
+ "react": "^18.0.0",
13
+ "react-dom": "^18.0.0",
14
+ "react-router-dom": "^5.3.4",
15
+ "styled-components": "5.3.3"
16
+ },
17
+ "peerDependencies": {
18
+ "react": "^17.0.2",
19
+ "react-dom": "^17.0.2",
20
+ "react-router-dom": "^5.3.4",
21
+ "styled-components": "^5.3.6"
22
+ },
23
+ "author": "Scaleflex <register@scaleflex.com> (https://www.scaleflex.com)",
24
+ "maintainers": [
25
+ "Scaleflex <plugins@scaleflex.com>"
26
+ ],
27
+ "engines": {
28
+ "node": ">=18.0.0 <=20.x.x",
29
+ "npm": ">=6.0.0"
30
+ },
31
+ "license": "MIT",
32
+ "keywords": [
33
+ "scaleflex",
34
+ "cloudimage",
35
+ "strapi"
36
+ ],
37
+ "main": "strapi-admin.js",
38
+ "dependencies": {
39
+ "ansi-styles": "^3.2.1",
40
+ "babel-plugin-styled-components": "^2.1.4",
41
+ "camelize": "^1.0.1",
42
+ "chalk": "^2.4.2",
43
+ "color-convert": "^1.9.3",
44
+ "color-name": "^1.1.3",
45
+ "css-color-keywords": "^1.0.0",
46
+ "css-to-react-native": "^3.2.0",
47
+ "debug": "^4.3.4",
48
+ "escape-string-regexp": "^1.0.5",
49
+ "globals": "^11.12.0",
50
+ "has-flag": "^3.0.0",
51
+ "history": "^4.10.1",
52
+ "hoist-non-react-statics": "^3.3.2",
53
+ "isarray": "^0.0.1",
54
+ "js-tokens": "^4.0.0",
55
+ "jsesc": "^2.5.2",
56
+ "lodash": "^4.17.21",
57
+ "loose-envify": "^1.4.0",
58
+ "ms": "^2.1.2",
59
+ "object-assign": "^4.1.1",
60
+ "path-to-regexp": "^1.8.0",
61
+ "picomatch": "^2.3.1",
62
+ "postcss-value-parser": "^4.2.0",
63
+ "prop-types": "^15.8.1",
64
+ "react-is": "^16.13.1",
65
+ "react-router": "^5.3.4",
66
+ "regenerator-runtime": "^0.14.1",
67
+ "resolve-pathname": "^3.0.0",
68
+ "scheduler": "^0.23.0",
69
+ "shallowequal": "^1.1.0",
70
+ "supports-color": "^5.5.0",
71
+ "tiny-invariant": "^1.3.1",
72
+ "tiny-warning": "^1.0.3",
73
+ "to-fast-properties": "^2.0.0",
74
+ "value-equal": "^1.0.1"
75
+ },
76
+ "scripts": {
77
+ "test": "echo \"Error: no test specified\" && exit 1"
78
+ },
79
+ "repository": {
80
+ "type": "git",
81
+ "url": "git+https://github.com/scaleflex/strapi-plugin-cloudimage.git"
82
+ },
83
+ "bugs": {
84
+ "url": "https://github.com/scaleflex/strapi-plugin-cloudimage/issues"
85
+ },
86
+ "homepage": "https://github.com/scaleflex/strapi-plugin-cloudimage#readme"
87
+ }
@@ -1,5 +1,25 @@
1
1
  'use strict';
2
2
 
3
3
  module.exports = ({ strapi }) => {
4
- // bootstrap phase
4
+ strapi.store({
5
+ environment: strapi.config.environment,
6
+ type: 'plugin',
7
+ name: 'cloudimage',
8
+ })
9
+ .get({key: 'options'})
10
+ .then((config) => {
11
+ if (config && config.hasOwnProperty('domain') && config.domain)
12
+ {
13
+ for (let index = 1; index < strapi.config.middlewares.length; index++)
14
+ {
15
+ let item = strapi.config.middlewares[index];
16
+
17
+ if (typeof item === 'object' && item.name === 'strapi::security' && !item.config.contentSecurityPolicy.directives['img-src'].includes(config.domain))
18
+ {
19
+ strapi.config.middlewares[index].config.contentSecurityPolicy.directives['img-src'].push(config.domain);
20
+ strapi.config.middlewares[index].config.contentSecurityPolicy.directives['media-src'].push(config.domain);
21
+ }
22
+ }
23
+ }
24
+ });
5
25
  };
@@ -3,37 +3,37 @@
3
3
  module.exports = ({ strapi }) => ({
4
4
  async index(ctx) {
5
5
  ctx.body = await strapi
6
- .plugin('scaleflex-cloudimage')
6
+ .plugin('cloudimage-by-scaleflex')
7
7
  .service('scaleflexCloudimage')
8
8
  .getWelcomeMessage();
9
9
  },
10
10
  async getConfig(ctx) {
11
11
  ctx.body = await strapi
12
- .plugin('scaleflex-cloudimage')
12
+ .plugin('cloudimage-by-scaleflex')
13
13
  .service('scaleflexCloudimage')
14
14
  .getConfig();
15
15
  },
16
16
  async updateConfig(ctx) {
17
17
  ctx.body = await strapi
18
- .plugin('scaleflex-cloudimage')
18
+ .plugin('cloudimage-by-scaleflex')
19
19
  .service('scaleflexCloudimage')
20
20
  .updateConfig(ctx);
21
21
  },
22
22
  async checkV7(ctx) {
23
23
  ctx.body = await strapi
24
- .plugin('scaleflex-cloudimage')
24
+ .plugin('cloudimage-by-scaleflex')
25
25
  .service('scaleflexCloudimage')
26
26
  .checkV7(ctx);
27
27
  },
28
28
  async countUpdate(ctx) {
29
29
  ctx.body = await strapi
30
- .plugin('scaleflex-cloudimage')
30
+ .plugin('cloudimage-by-scaleflex')
31
31
  .service('scaleflexCloudimage')
32
32
  .countUpdate(ctx);
33
33
  },
34
34
  async updateMedia(ctx) {
35
35
  ctx.body = await strapi
36
- .plugin('scaleflex-cloudimage')
36
+ .plugin('cloudimage-by-scaleflex')
37
37
  .service('scaleflexCloudimage')
38
38
  .updateMedia(ctx);
39
39
  },
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const scaleflexCloudimage = require('./scaleflex-cloudimage');
3
+ const scaleflexCloudimage = require('./cloudimage-by-scaleflex');
4
4
 
5
5
  module.exports = {
6
6
  scaleflexCloudimage,
@@ -1,65 +1,65 @@
1
1
  'use strict';
2
- //@Todo: Think about how this can be done in a cluster of may servers. Maybe persist the plugin's middleware settings in DB, then load it into that memory object upon start
2
+
3
3
  module.exports = ({ strapi }) => {
4
- // const pluginMiddleware = {
5
- // name: 'strapi::security',
6
- // config: {
7
- // contentSecurityPolicy: {
8
- // useDefaults: true,
9
- // directives: {
10
- // 'connect-src': ["'self'", 'https:'],
11
- // 'img-src': ["'self'", 'data:', 'blob:', 'scaleflex.cloudimg.io', 'assets.scaleflex.com', '*.cloudimg.io'],
12
- // 'media-src': ["'self'", 'data:', 'blob:', 'scaleflex.cloudimg.io', 'assets.scaleflex.com', '*.cloudimg.io'],
13
- // upgradeInsecureRequests: null,
14
- // },
15
- // },
16
- // },
17
- // };
4
+ const pluginMiddleware = {
5
+ name: 'strapi::security',
6
+ config: {
7
+ contentSecurityPolicy: {
8
+ useDefaults: true,
9
+ directives: {
10
+ 'connect-src': ["'self'", 'https:'],
11
+ 'img-src': ["'self'", 'data:', 'blob:', 'scaleflex.cloudimg.io', 'assets.scaleflex.com', '*.cloudimg.io'],
12
+ 'media-src': ["'self'", 'data:', 'blob:', 'scaleflex.cloudimg.io', 'assets.scaleflex.com', '*.cloudimg.io'],
13
+ upgradeInsecureRequests: null,
14
+ },
15
+ },
16
+ },
17
+ };
18
18
 
19
- // // Merge a `source` object to a `target` recursively
20
- // const merge = (target, source) => {
21
- // // Iterate through `source` properties and if an `Object` set property to merge of `target` and `source` properties
22
- // for (const key of Object.keys(source))
23
- // {
24
- // if (Array.isArray(source[key]))
25
- // {
26
- // Object.assign(source[key], [...new Set(target[key].concat(source[key]))]);
27
- // }
19
+ // Merge a `source` object to a `target` recursively
20
+ const merge = (target, source) => {
21
+ // Iterate through `source` properties and if an `Object` set property to merge of `target` and `source` properties
22
+ for (const key of Object.keys(source))
23
+ {
24
+ if (Array.isArray(source[key]))
25
+ {
26
+ Object.assign(source[key], [...new Set(target[key].concat(source[key]))]);
27
+ }
28
28
 
29
- // if (source[key] instanceof Object && !Array.isArray(source[key]))
30
- // {
31
- // Object.assign(source[key], merge(target[key], source[key]));
32
- // }
33
- // }
29
+ if (source[key] instanceof Object && !Array.isArray(source[key]))
30
+ {
31
+ Object.assign(source[key], merge(target[key], source[key]));
32
+ }
33
+ }
34
34
 
35
- // // Join `target` and modified `source`
36
- // Object.assign(target || {}, source);
35
+ // Join `target` and modified `source`
36
+ Object.assign(target || {}, source);
37
37
 
38
- // return target;
39
- // };
38
+ return target;
39
+ };
40
40
 
41
- // for (let index = 1; index < strapi.config.middlewares.length; index++)
42
- // {
43
- // let item = strapi.config.middlewares[index];
41
+ for (let index = 1; index < strapi.config.middlewares.length; index++)
42
+ {
43
+ let item = strapi.config.middlewares[index];
44
44
 
45
- // if (typeof item === 'object' && item.name === 'strapi::security')
46
- // {
47
- // let mergedSettings = merge(item.config, pluginMiddleware.config);
48
- // strapi.config.middlewares.splice(index, 1, {name: 'strapi::security', config: mergedSettings});
45
+ if (typeof item === 'object' && item.name === 'strapi::security')
46
+ {
47
+ let mergedSettings = merge(item.config, pluginMiddleware.config);
48
+ strapi.config.middlewares.splice(index, 1, {name: 'strapi::security', config: mergedSettings});
49
49
 
50
- // break;
51
- // }
52
- // else if (typeof item === 'string' && item === 'strapi::security')
53
- // {
54
- // strapi.config.middlewares.splice(index, 1, pluginMiddleware);
50
+ break;
51
+ }
52
+ else if (typeof item === 'string' && item === 'strapi::security')
53
+ {
54
+ strapi.config.middlewares.splice(index, 1, pluginMiddleware);
55
55
 
56
- // break;
57
- // }
58
- // else
59
- // {
60
- // strapi.config.middlewares.push(pluginMiddleware);
56
+ break;
57
+ }
58
+ else
59
+ {
60
+ strapi.config.middlewares.push(pluginMiddleware);
61
61
 
62
- // break;
63
- // }
64
- // }
62
+ break;
63
+ }
64
+ }
65
65
  };
@@ -1,187 +1,172 @@
1
- 'use strict';
2
-
3
- const fs = require('fs');
4
- const path = require('path');
5
- const fetch = require("node-fetch");
6
-
7
- module.exports = ({ strapi }) => ({
8
- getWelcomeMessage() {
9
- return 'Thank you for using Scaleflex Filerobot';
10
- },
11
- getPluginStore() {
12
- return strapi.store({
13
- environment: strapi.config.environment,
14
- type: 'plugin',
15
- name: 'cloudimage',
16
- });
17
- },
18
- async getConfig() {
19
- const pluginStore = this.getPluginStore();
20
-
21
- let config = {
22
- domain: '',
23
- isV7: ''
24
- }
25
-
26
- const storedConfig = await pluginStore.get({key: 'options'})
27
- if (storedConfig) {
28
- config = storedConfig;
29
- }
30
-
31
- return config
32
- },
33
- async updateConfig(ctx) {
34
- const pluginStore = this.getPluginStore();
35
-
36
- await pluginStore.set({
37
- key: 'options',
38
- value: ctx.request.body
39
- });
40
-
41
- const config = await pluginStore.get({key: 'options'});
42
-
43
- // if (config.domain)
44
- // {
45
- // for (let index = 1; index < strapi.config.middlewares.length; index++)
46
- // {
47
- // let item = strapi.config.middlewares[index];
48
-
49
- // if (typeof item === 'object' && item.name === 'strapi::security'
50
- // && !item.config.contentSecurityPolicy.directives['img-src'].includes(config.domain))
51
- // {
52
- // strapi.config.middlewares[index].config.contentSecurityPolicy.directives['img-src'].push(config.domain);
53
- // strapi.config.middlewares[index].config.contentSecurityPolicy.directives['media-src'].push(config.domain);
54
- // }
55
- // }
56
- // }
57
-
58
- return config;
59
- },
60
- async checkV7(ctx) {
61
- let domain = ctx.request.query.domain;
62
-
63
- let response = {};
64
- let responseV7 = {};
65
-
66
- try
67
- {
68
- response = await fetch(`https://${domain}/http://sample.li/blank.png`);
69
- responseV7 = await fetch(`https://${domain}/v7/http://sample.li/blank.png`);
70
- }
71
- catch (error)
72
- {
73
- console.error(error);
74
-
75
- return {domainExists: false};
76
- }
77
-
78
- let isValid = response.status === 200 && !response.headers.get('x-hexa-missingbehavior');
79
- let isV7Valid = responseV7.status === 200 && !responseV7.headers.get('x-hexa-missingbehavior');
80
-
81
- if (isValid && !isV7Valid)
82
- {
83
- return {isSuccess: true, domainExists: true, isV7: false};
84
- }
85
- else if (!isValid && isV7Valid)
86
- {
87
- return {isSuccess: true, domainExists: true, isV7: true};
88
- }
89
- else
90
- {
91
- return {isSuccess: false, domainExists: true};
92
- }
93
- },
94
- async countUpdate(ctx) {
95
- let pluginStore = this.getPluginStore();
96
- let pluginConfig = await pluginStore.get({key: 'options'});
97
- let domain = pluginConfig.domain;
98
-
99
- let media = await strapi.entityService.findMany('plugin::upload.file', {
100
- populate: {category: true},
101
- filters: { // https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/entity-service/filter.html#and
102
- $and: [
103
- {
104
- url: { $notContains: domain, },
105
- },
106
- {
107
- mime: { $contains: 'image', },
108
- },
109
- {
110
- provider: { $notContains: 'filerobot', },
111
- },
112
- ],
113
- },
114
- });
115
-
116
- return media.length;
117
- },
118
- async updateMedia(ctx) {
119
- let baseUrl = strapi.config.get('server.url');
120
- let pluginStore = this.getPluginStore();
121
- let pluginConfig = await pluginStore.get({key: 'options'});
122
- let domain = pluginConfig.domain;
123
- let isV7 = pluginConfig.isV7;
124
-
125
- let media = await strapi.entityService.findMany('plugin::upload.file', {
126
- populate: {category: true},
127
- filters: {
128
- $and: [
129
- {
130
- url: { $notContains: domain, },
131
- },
132
- {
133
- mime: { $contains: 'image', },
134
- },
135
- {
136
- provider: { $notContains: 'filerobot', },
137
- },
138
- ],
139
- },
140
- });
141
-
142
- return Promise.all(media.map((item, index) => {
143
- let prepUrl = '';
144
-
145
- if (/^https?:\/\//.test(item.url))
146
- {
147
- prepUrl = item.url.replace(/^https?:\/\//, '');
148
- }
149
- else
150
- {
151
- prepUrl = `${baseUrl}${item.url}`.replace(/^https?:\/\//, '');
152
- }
153
-
154
- let ciUrl = `https://${pluginConfig.domain}${pluginConfig.isV7 ? '/v7' : ''}/${prepUrl}`;
155
-
156
- return strapi.entityService.update('plugin::upload.file', item.id, {
157
- data: {
158
- url: ciUrl,
159
- formats: null
160
- },
161
- })
162
- .then(function(result) {
163
- return {success: true, result: result};
164
- })
165
- .catch(function(error) {
166
- return {success: false, error: error.message};
167
- });
168
- }))
169
- .then(function(results) {
170
- let successCount = 0;
171
-
172
- results.forEach((result, index) => {
173
- if (result.success)
174
- {
175
- successCount++;
176
- }
177
- });
178
-
179
- return {response: `${successCount} / ${results.length}`};
180
- })
181
- .catch(function(error) {
182
- console.dir(error.message);
183
-
184
- return {response: false};
185
- });
186
- },
187
- });
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const fetch = require("node-fetch");
6
+
7
+ module.exports = ({ strapi }) => ({
8
+ getWelcomeMessage() {
9
+ return 'Thank you for using Cloudimage by Scaleflex';
10
+ },
11
+ getPluginStore() {
12
+ return strapi.store({
13
+ environment: strapi.config.environment,
14
+ type: 'plugin',
15
+ name: 'cloudimage',
16
+ });
17
+ },
18
+ async getConfig() {
19
+ const pluginStore = this.getPluginStore();
20
+
21
+ let config = {
22
+ domain: '',
23
+ isV7: ''
24
+ }
25
+
26
+ const storedConfig = await pluginStore.get({key: 'options'})
27
+ if (storedConfig) {
28
+ config = storedConfig;
29
+ }
30
+
31
+ return config
32
+ },
33
+ async updateConfig(ctx) {
34
+ const pluginStore = this.getPluginStore();
35
+
36
+ await pluginStore.set({
37
+ key: 'options',
38
+ value: ctx.request.body
39
+ });
40
+
41
+ const config = await pluginStore.get({key: 'options'});
42
+
43
+ return config;
44
+ },
45
+ async checkV7(ctx) {
46
+ let domain = ctx.request.query.domain;
47
+
48
+ let response = {};
49
+ let responseV7 = {};
50
+
51
+ try
52
+ {
53
+ response = await fetch(`https://${domain}/http://sample.li/blank.png`);
54
+ responseV7 = await fetch(`https://${domain}/v7/http://sample.li/blank.png`);
55
+ }
56
+ catch (error)
57
+ {
58
+ console.error(error);
59
+
60
+ return {domainExists: false};
61
+ }
62
+
63
+ let isValid = response.status === 200 && !response.headers.get('x-hexa-missingbehavior');
64
+ let isV7Valid = responseV7.status === 200 && !responseV7.headers.get('x-hexa-missingbehavior');
65
+
66
+ if (isValid && !isV7Valid)
67
+ {
68
+ return {isSuccess: true, domainExists: true, isV7: false};
69
+ }
70
+ else if (!isValid && isV7Valid)
71
+ {
72
+ return {isSuccess: true, domainExists: true, isV7: true};
73
+ }
74
+ else
75
+ {
76
+ return {isSuccess: false, domainExists: true};
77
+ }
78
+ },
79
+ async countUpdate(ctx) {
80
+ let pluginStore = this.getPluginStore();
81
+ let pluginConfig = await pluginStore.get({key: 'options'});
82
+ let domain = pluginConfig.domain;
83
+
84
+ let media = await strapi.entityService.findMany('plugin::upload.file', {
85
+ populate: {category: true},
86
+ filters: { // https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/entity-service/filter.html#and
87
+ $and: [
88
+ {
89
+ url: { $notContains: domain, },
90
+ },
91
+ {
92
+ mime: { $contains: 'image', },
93
+ },
94
+ {
95
+ provider: { $notContains: 'filerobot', },
96
+ },
97
+ ],
98
+ },
99
+ });
100
+
101
+ return media.length;
102
+ },
103
+ async updateMedia(ctx) {
104
+ let baseUrl = strapi.config.get('server.url');
105
+ let pluginStore = this.getPluginStore();
106
+ let pluginConfig = await pluginStore.get({key: 'options'});
107
+ let domain = pluginConfig.domain;
108
+ let isV7 = pluginConfig.isV7;
109
+
110
+ let media = await strapi.entityService.findMany('plugin::upload.file', {
111
+ populate: {category: true},
112
+ filters: {
113
+ $and: [
114
+ {
115
+ url: { $notContains: domain, },
116
+ },
117
+ {
118
+ mime: { $contains: 'image', },
119
+ },
120
+ {
121
+ provider: { $notContains: 'filerobot', },
122
+ },
123
+ ],
124
+ },
125
+ });
126
+
127
+ return Promise.all(media.map((item, index) => {
128
+ let prepUrl = '';
129
+
130
+ if (/^https?:\/\//.test(item.url))
131
+ {
132
+ prepUrl = item.url.replace(/^https?:\/\//, '');
133
+ }
134
+ else
135
+ {
136
+ prepUrl = `${baseUrl}${item.url}`.replace(/^https?:\/\//, '');
137
+ }
138
+
139
+ let ciUrl = `https://${pluginConfig.domain}${pluginConfig.isV7 ? '/v7' : ''}/${prepUrl}`;
140
+
141
+ return strapi.entityService.update('plugin::upload.file', item.id, {
142
+ data: {
143
+ url: ciUrl,
144
+ formats: null
145
+ },
146
+ })
147
+ .then(function(result) {
148
+ return {success: true, result: result};
149
+ })
150
+ .catch(function(error) {
151
+ return {success: false, error: error.message};
152
+ });
153
+ }))
154
+ .then(function(results) {
155
+ let successCount = 0;
156
+
157
+ results.forEach((result, index) => {
158
+ if (result.success)
159
+ {
160
+ successCount++;
161
+ }
162
+ });
163
+
164
+ return {response: `${successCount} / ${results.length}`};
165
+ })
166
+ .catch(function(error) {
167
+ console.dir(error.message);
168
+
169
+ return {response: false};
170
+ });
171
+ },
172
+ });
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const scaleflexCloudimage = require('./scaleflex-cloudimage');
3
+ const scaleflexCloudimage = require('./cloudimage-by-scaleflex');
4
4
 
5
5
  module.exports = {
6
6
  scaleflexCloudimage,