@dpgradio/creative 5.0.0

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/.babelrc ADDED
@@ -0,0 +1,4 @@
1
+ // Babel is only used for jest support at the moment. Maybe consider a different testing libary.
2
+ {
3
+ "presets": ["@babel/preset-env"]
4
+ }
package/.eslintrc.cjs ADDED
@@ -0,0 +1,12 @@
1
+ module.exports = {
2
+ env: {
3
+ browser: true,
4
+ es6: true,
5
+ node: true,
6
+ },
7
+ extends: ['@dpgradio/eslint-config-recommended'],
8
+ parserOptions: {
9
+ sourceType: 'module',
10
+ ecmaVersion: 2023,
11
+ },
12
+ }
package/README.md ADDED
@@ -0,0 +1,232 @@
1
+ # @dpgradio/creative
2
+
3
+ ## Installation
4
+
5
+ ```bash
6
+ yarn add @dpgradio/creative
7
+ ```
8
+
9
+ ## CSS: Fonts and Colors
10
+
11
+ Note that version 5 of this package provides fonts and colors as pure css.
12
+ The variables and fonts are no longer available as scss variables/imports.
13
+
14
+ Example:
15
+
16
+ ```css
17
+ @import "q-creative/styles/colors/qmusic";
18
+ @import "q-creative/styles/fonts/qmusic";
19
+
20
+ body, html {
21
+ background-color: rgb(var(--q-teal));
22
+ color: rgb(var(--q-grey) / 0.8);
23
+ font-family: 'QMarkMyWords';
24
+ }
25
+ ```
26
+
27
+ ## Config
28
+
29
+ ### Usage
30
+
31
+ Add the following in the main script of your application to retrieve the configuration.
32
+ The configuration will also be used by other components of this package (e.g. privacy, tracking, etc.).
33
+
34
+ ```js
35
+ import { configuration } from '@dpgradio/creative'
36
+
37
+ await configuration.retrieveConfig(appId, stationIdA, stationIdB, stationIdC)
38
+
39
+ // By default the first station ID (stationIdA) is used as the current station of the configuration.
40
+ // If you want to use a different station, you can do so by calling:
41
+ configuration.setStation(stationIdC)
42
+ ```
43
+ You can change the station later on at any time without having to retrieve the config again.
44
+ The API client will automatically use the correct station.
45
+ Privacy and tracking need to be reinitalized after changing the station.
46
+
47
+ The config can now be used as follows:
48
+
49
+ ```js
50
+ import { config } from '@dpgradio/creative'
51
+
52
+ config('api_base_url') // or: config().api_base_url
53
+ config('app.default_theme') // or: config().app.default_theme
54
+ ```
55
+
56
+ ### Update Schema
57
+
58
+ Applications can create/modify the configuration schema by creating a script with the following contents:
59
+
60
+ ```js
61
+ import { api, configuration } from '@dpgradio/creative'
62
+
63
+ api.setApiKey('<api-token-here>')
64
+
65
+ await configuration.replaceSchema('greety', [
66
+ {
67
+ name: 'display_language',
68
+ type: 'options',
69
+ default: 'dutch',
70
+ options: ['dutch', 'english'],
71
+ },
72
+ {
73
+ name: 'author_name',
74
+ type: 'string',
75
+ },
76
+ ])
77
+ ```
78
+
79
+ (assuming availablity of top-level await and `fetch`)
80
+
81
+ ## Privacy and Tracking
82
+
83
+ ### Privacy
84
+
85
+ #### Initialization
86
+
87
+ Without [config](#config):
88
+
89
+ ```js
90
+ import { privacy } from '@dpgradio/creative'
91
+
92
+ privacy.initialize(privacyManagerId, websiteUrl, cmpCname)
93
+ ```
94
+
95
+ With config (after [initializing the config](#config)):
96
+
97
+ ```js
98
+ import { privacy } from '@dpgradio/creative'
99
+
100
+ privacy.initialize()
101
+ ```
102
+
103
+ #### Get consent string
104
+
105
+ ```js
106
+ import { privacy } from '@dpgradio/creative'
107
+
108
+ const consent = await privacy.waitForConsent()
109
+
110
+ // Available properties:
111
+ consent.consentString
112
+ consent.purposes
113
+ consent.allowsTargetedAdvertising()
114
+ ```
115
+
116
+ ### Tracking
117
+
118
+ ```js
119
+ import { dataLayer } from '@dpgradio/creative'
120
+
121
+ dataLayer.initialize() // Pushes gtmStart and currently authenticated user
122
+ dataLayer.pushVirtualPageView(brand) // brand is not required when the config is initialized
123
+
124
+ dataLayer.pushEvent(event, data)
125
+ ```
126
+
127
+ ## API
128
+
129
+ With an initialized [configuration](#config):
130
+
131
+ ```js
132
+ import { api } from '@dpgradio/creative'
133
+
134
+ const channels = await api.channels.all()
135
+
136
+ const globalChannels = await api.global().channels.all()
137
+
138
+ api.setRadioToken(token)
139
+ const profile = await api.members.me() // or await api.setRadioToken(token).members.me()
140
+
141
+ api.setApiKey(key)
142
+ await api.global().config.update(appId, schema)
143
+
144
+ const oldChannels = await api.onVersion('1.4').channels.all()
145
+ ```
146
+
147
+ Without an initialized [configuration](#config):
148
+
149
+ ```js
150
+ import { Api } from '@dpgradio/creative'
151
+
152
+ const api = new Api('https://api.qmusic.be')
153
+
154
+ const channels = await api.channels.all()
155
+ ```
156
+
157
+ ## Socket
158
+
159
+ ```js
160
+ import { socket } from '@dpgradio/creative'
161
+
162
+ socket.connect(stationId).subscribe('plays').on('play', () => {
163
+ console.log('play')
164
+ }, { backlog: 3 }})
165
+
166
+ // or
167
+
168
+ socket.join({ station: stationId, entity: 'plays', action: 'play', options: { backlog: 3 } }, (play) => {
169
+ console.log(play)
170
+ })
171
+ ```
172
+
173
+ ## Hybrid
174
+
175
+ ```js
176
+ import { hyrid } from '@dpgradio/creative'
177
+
178
+ hybrid.appInfo
179
+ hybrid.isNativeApp()
180
+ hybrid.isVersion({ iOS, Android })
181
+ hybrid.call(method, options)
182
+ hybrid.on(method, callback, once)
183
+ hybrid.one(method, callback)
184
+ const radioToken = await hybrid.appLoaded()
185
+ hybrid.decodeRadioToken(radioToken)
186
+ ```
187
+
188
+ ## Sharing Generator
189
+
190
+ Example:
191
+
192
+ ```js
193
+ import { Shareable, ImageGeneratorProperties } from 'q-creative/share'
194
+
195
+ const shareable = new Shareable()
196
+ .withTitle(`${this.name} is mijn seventies match!`)
197
+ .withDescription('Ontdek wie jouw seventies match is in de Generation Quiz van Joe!')
198
+ .withMessageText(`Mijn seventies match is ${this.name}, wat is die van jou?`)
199
+ .redirectTo('https://article_url.com')
200
+ .fromDomain('joe.be')
201
+
202
+ // Facebook
203
+ const image = new ImageGeneratorProperties('https://static.qmusic.be/acties/joe-70s-quiz-share-fb/index.html')
204
+ .withDimensions(1200, 630)
205
+ .withPayload({ results: this.matches });
206
+
207
+ (await shareable.generateUsingImage(image)).openFacebookUrl()
208
+
209
+ // Instagram
210
+ const image = new ImageGeneratorProperties('https://static.qmusic.be/acties/joe-70s-quiz-share-fb/index.html')
211
+ .withDimensions(1080, 1920)
212
+ .withPayload({ results: this.matches });
213
+
214
+ (await shareable.generateUsingImage(image)).openInstagramUrl()
215
+
216
+ // Whatsapp
217
+ const image = new ImageGeneratorProperties('https://static.qmusic.be/acties/joe-70s-quiz-share-fb/index.html')
218
+ .withDimensions(1200, 630)
219
+ .withPayload({ results: this.matches });
220
+
221
+ (await shareable.generateUsingImage(image)).openWhatsappUrl()
222
+ ```
223
+
224
+ ## Utilities
225
+
226
+ This package provides a number of utility functions.
227
+
228
+ | Function | Description |
229
+ | ------------------------------- | ----------- |
230
+ | `loadScript(url, { timeout })` | Dynammically loads a JS script. |
231
+ | `openLink(url)` | App-compatible link opener. |
232
+ | `tap(value, callback)` | Invokes `callback` with the `value` and then returns `value`. |
@@ -0,0 +1,27 @@
1
+ import api from '../src/api/api.js'
2
+ import configuration from '../src/config/config.js'
3
+
4
+ // To add support for node <17.5, install node-fetch and include the following line
5
+ // global.fetch = await import('node-fetch').then((module) => module.default)
6
+
7
+ // Make sure you have set the DARIO_API_KEY environment variable
8
+ // Add the following to your .bashrc or .zshrc: `export DARIO_API_KEY=your-api-key`
9
+ // eslint-disable-next-line no-undef
10
+ api.setApiKey(process.env.DARIO_API_KEY)
11
+
12
+ configuration.replaceSchema('greety', [
13
+ {
14
+ name: 'display_language',
15
+ type: 'options',
16
+ default: 'dutch',
17
+ options: ['dutch', 'english'],
18
+ },
19
+ {
20
+ name: 'author_name',
21
+ type: 'string',
22
+ },
23
+ {
24
+ name: 'author_email',
25
+ type: 'string',
26
+ },
27
+ ])
@@ -0,0 +1,16 @@
1
+ import api from '../src/api/api.js'
2
+ import configuration from '../src/config/config.js'
3
+
4
+ const appId = 'greety'
5
+ const stationId = 'qmusic_be'
6
+
7
+ await configuration.retrieveConfig(appId, stationId)
8
+
9
+ const channels = await api.channels.all()
10
+
11
+ console.log(channels)
12
+
13
+ const token = '<radio-token-here>'
14
+ const profile = await api.setRadioToken(token).members.me()
15
+
16
+ console.log(profile)
@@ -0,0 +1,13 @@
1
+ import configuration, { config } from '../src/config/config.js'
2
+
3
+ const appId = 'greety'
4
+ const stationIdA = 'qmusic_be'
5
+ const stationIdB = 'qmusic_nl'
6
+
7
+ await configuration.retrieveConfig(appId, stationIdA, stationIdB)
8
+
9
+ console.log(config('app')) // greety config of qmusic_be
10
+
11
+ configuration.setStation(stationIdB)
12
+
13
+ console.log(config('app')) // greety config of qmusic_nl
@@ -0,0 +1,195 @@
1
+ /*
2
+ * For a detailed explanation regarding each configuration property, visit:
3
+ * https://jestjs.io/docs/configuration
4
+ */
5
+
6
+ module.exports = {
7
+ // All imported modules in your tests should be mocked automatically
8
+ // automock: false,
9
+
10
+ // Stop running tests after `n` failures
11
+ // bail: 0,
12
+
13
+ // The directory where Jest should store its cached dependency information
14
+ // cacheDirectory: "/private/var/folders/lc/cnjbcmm51_z3lcvg0vj8_zdc0000gn/T/jest_dx",
15
+
16
+ // Automatically clear mock calls, instances, contexts and results before every test
17
+ clearMocks: true,
18
+
19
+ // Indicates whether the coverage information should be collected while executing the test
20
+ // collectCoverage: false,
21
+
22
+ // An array of glob patterns indicating a set of files for which coverage information should be collected
23
+ // collectCoverageFrom: undefined,
24
+
25
+ // The directory where Jest should output its coverage files
26
+ // coverageDirectory: undefined,
27
+
28
+ // An array of regexp pattern strings used to skip coverage collection
29
+ // coveragePathIgnorePatterns: [
30
+ // "/node_modules/"
31
+ // ],
32
+
33
+ // Indicates which provider should be used to instrument code for coverage
34
+ // coverageProvider: "babel",
35
+
36
+ // A list of reporter names that Jest uses when writing coverage reports
37
+ // coverageReporters: [
38
+ // "json",
39
+ // "text",
40
+ // "lcov",
41
+ // "clover"
42
+ // ],
43
+
44
+ // An object that configures minimum threshold enforcement for coverage results
45
+ // coverageThreshold: undefined,
46
+
47
+ // A path to a custom dependency extractor
48
+ // dependencyExtractor: undefined,
49
+
50
+ // Make calling deprecated APIs throw helpful error messages
51
+ // errorOnDeprecated: false,
52
+
53
+ // The default configuration for fake timers
54
+ // fakeTimers: {
55
+ // "enableGlobally": false
56
+ // },
57
+
58
+ // Force coverage collection from ignored files using an array of glob patterns
59
+ // forceCoverageMatch: [],
60
+
61
+ // A path to a module which exports an async function that is triggered once before all test suites
62
+ // globalSetup: undefined,
63
+
64
+ // A path to a module which exports an async function that is triggered once after all test suites
65
+ // globalTeardown: undefined,
66
+
67
+ // A set of global variables that need to be available in all test environments
68
+ // globals: {},
69
+
70
+ // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
71
+ // maxWorkers: "50%",
72
+
73
+ // An array of directory names to be searched recursively up from the requiring module's location
74
+ // moduleDirectories: [
75
+ // "node_modules"
76
+ // ],
77
+
78
+ // An array of file extensions your modules use
79
+ // moduleFileExtensions: [
80
+ // "js",
81
+ // "mjs",
82
+ // "cjs",
83
+ // "jsx",
84
+ // "ts",
85
+ // "tsx",
86
+ // "json",
87
+ // "node"
88
+ // ],
89
+
90
+ // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
91
+ // moduleNameMapper: {},
92
+
93
+ // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
94
+ // modulePathIgnorePatterns: [],
95
+
96
+ // Activates notifications for test results
97
+ // notify: false,
98
+
99
+ // An enum that specifies notification mode. Requires { notify: true }
100
+ // notifyMode: "failure-change",
101
+
102
+ // A preset that is used as a base for Jest's configuration
103
+ // preset: undefined,
104
+
105
+ // Run tests from one or more projects
106
+ // projects: undefined,
107
+
108
+ // Use this configuration option to add custom reporters to Jest
109
+ // reporters: undefined,
110
+
111
+ // Automatically reset mock state before every test
112
+ // resetMocks: false,
113
+
114
+ // Reset the module registry before running each individual test
115
+ // resetModules: false,
116
+
117
+ // A path to a custom resolver
118
+ // resolver: undefined,
119
+
120
+ // Automatically restore mock state and implementation before every test
121
+ // restoreMocks: false,
122
+
123
+ // The root directory that Jest should scan for tests and modules within
124
+ rootDir: 'src',
125
+
126
+ // A list of paths to directories that Jest should use to search for files in
127
+ // roots: [
128
+ // "<rootDir>"
129
+ // ],
130
+
131
+ // Allows you to use a custom runner instead of Jest's default test runner
132
+ // runner: "jest-runner",
133
+
134
+ // The paths to modules that run some code to configure or set up the testing environment before each test
135
+ // setupFiles: [],
136
+
137
+ // A list of paths to modules that run some code to configure or set up the testing framework before each test
138
+ // setupFilesAfterEnv: [],
139
+
140
+ // The number of seconds after which a test is considered as slow and reported as such in the results.
141
+ // slowTestThreshold: 5,
142
+
143
+ // A list of paths to snapshot serializer modules Jest should use for snapshot testing
144
+ // snapshotSerializers: [],
145
+
146
+ // The test environment that will be used for testing
147
+ testEnvironment: "jsdom",
148
+
149
+ // Options that will be passed to the testEnvironment
150
+ // testEnvironmentOptions: {},
151
+
152
+ // Adds a location field to test results
153
+ // testLocationInResults: false,
154
+
155
+ // The glob patterns Jest uses to detect test files
156
+ // testMatch: [
157
+ // "**/__tests__/**/*.[jt]s?(x)",
158
+ // "**/?(*.)+(spec|test).[tj]s?(x)"
159
+ // ],
160
+
161
+ // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
162
+ // testPathIgnorePatterns: [
163
+ // "/node_modules/"
164
+ // ],
165
+
166
+ // The regexp pattern or array of patterns that Jest uses to detect test files
167
+ // testRegex: [],
168
+
169
+ // This option allows the use of a custom results processor
170
+ // testResultsProcessor: undefined,
171
+
172
+ // This option allows use of a custom test runner
173
+ // testRunner: "jest-circus/runner",
174
+
175
+ // A map from regular expressions to paths to transformers
176
+ // transform: undefined,
177
+
178
+ // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
179
+ // transformIgnorePatterns: [
180
+ // "/node_modules/",
181
+ // "\\.pnp\\.[^\\/]+$"
182
+ // ],
183
+
184
+ // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
185
+ // unmockedModulePathPatterns: undefined,
186
+
187
+ // Indicates whether each individual test should be reported during the run
188
+ // verbose: undefined,
189
+
190
+ // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
191
+ // watchPathIgnorePatterns: [],
192
+
193
+ // Whether to use watchman for file crawling
194
+ // watchman: true,
195
+ };
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@dpgradio/creative",
3
+ "version": "5.0.0",
4
+ "description": "Support package for standalone Javascript applications",
5
+ "main": "src/index.js",
6
+ "scripts": {
7
+ "test": "jest",
8
+ "lint-check": "eslint --ext .js --ignore-path .gitignore src",
9
+ "lint": "yarn lint-check --fix"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "https://github.com/dpgradio/creative.git"
14
+ },
15
+ "keywords": [
16
+ "qmusic"
17
+ ],
18
+ "type": "module",
19
+ "author": "DPG Media",
20
+ "license": "ISC",
21
+ "dependencies": {
22
+ "jwt-decode": "^3.1.2",
23
+ "sockjs-client": "^1.6.1"
24
+ },
25
+ "devDependencies": {
26
+ "@dpgradio/eslint-config-recommended": "^0.0.1",
27
+ "eslint": "^8.32.0",
28
+ "jest": "^29.4.0",
29
+ "jest-environment-jsdom": "^29.4.0"
30
+ }
31
+ }
@@ -0,0 +1,44 @@
1
+ import { describe, expect, test, jest } from '@jest/globals'
2
+ import hybrid from '../../app/hybrid'
3
+ import openLink from '../../utils/openLink'
4
+
5
+ jest.mock('../../utils/hybrid.js', () => ({
6
+ isNativeApp: jest.fn(),
7
+ call: jest.fn(),
8
+ }))
9
+
10
+ const setUserAgent = (userAgent) => {
11
+ jest.spyOn(window.navigator, 'userAgent', 'get').mockImplementation(() => userAgent)
12
+ }
13
+
14
+ describe('opening a link in the app', () => {
15
+ test('it calls a hybrid method', () => {
16
+ hybrid.isNativeApp.mockImplementation(() => true)
17
+
18
+ openLink('https://www.google.com/')
19
+
20
+ expect(hybrid.call).toHaveBeenCalledWith('navigateTo', { inApp: false, url: 'https://www.google.com/' })
21
+ })
22
+ })
23
+
24
+ describe('opening a link in the browser', () => {
25
+ test('it opens in a new window in non-Safari', () => {
26
+ hybrid.isNativeApp.mockImplementation(() => false)
27
+ setUserAgent('Chrome')
28
+ window.open = jest.fn()
29
+
30
+ openLink('https://www.google.com/')
31
+
32
+ expect(window.open).toHaveBeenCalledWith('https://www.google.com/')
33
+ })
34
+
35
+ test('it redirects to the link in Safari', () => {
36
+ hybrid.isNativeApp.mockImplementation(() => false)
37
+ setUserAgent('Safari')
38
+ delete window.location // allows us to set and read the location object
39
+
40
+ openLink('https://www.google.com/')
41
+
42
+ expect(window.location).toBe('https://www.google.com/')
43
+ })
44
+ })
package/src/api/api.js ADDED
@@ -0,0 +1,60 @@
1
+ import { config } from '../config/config.js'
2
+ import Request from './request.js'
3
+ import tap from '../utils/tap.js'
4
+ import Channels from './endpoints/Channels.js'
5
+ import Config from './endpoints/Config.js'
6
+ import Members from './endpoints/Members.js'
7
+
8
+ const GLOBAL_API_URL = 'https://api.radio.dpgmedia.cloud'
9
+
10
+ export const DEFAULT_VERSION = '2.9'
11
+
12
+ export class Api {
13
+ constructor(baseUrl, version = DEFAULT_VERSION) {
14
+ this.baseUrlOverride = baseUrl
15
+ this.version = version
16
+
17
+ this.requestModifiers = []
18
+
19
+ // Endpoints
20
+ this.channels = new Channels(this)
21
+ this.config = new Config(this)
22
+ this.members = new Members(this)
23
+ }
24
+
25
+ get baseUrl() {
26
+ return this.baseUrlOverride || config('apiBaseUrl')
27
+ }
28
+
29
+ request() {
30
+ return tap(new Request(this.baseUrl, this.version), (request) => {
31
+ this.requestModifiers.forEach((modifier) => modifier(request))
32
+ })
33
+ }
34
+
35
+ setApiKey(apiKey) {
36
+ this.requestModifiers.push((request) => request.withQueryParameters({ api_key: apiKey }))
37
+ return this
38
+ }
39
+
40
+ setRadioToken(token) {
41
+ this.requestModifiers.push((request) => request.withHeader('Authorization', `Bearer ${token}`))
42
+ return this
43
+ }
44
+
45
+ onVersion(version) {
46
+ return tap(this.clone(), (api) => (api.version = version))
47
+ }
48
+
49
+ global() {
50
+ return tap(this.clone(), (api) => (api.baseUrlOverride = GLOBAL_API_URL))
51
+ }
52
+
53
+ clone() {
54
+ return tap(new Api(this.baseUrlOverride, this.version), (api) => {
55
+ api.requestModifiers = this.requestModifiers
56
+ })
57
+ }
58
+ }
59
+
60
+ export default new Api()
@@ -0,0 +1,7 @@
1
+ import Endpoint from './Endpoint.js'
2
+
3
+ export default class Channels extends Endpoint {
4
+ async all() {
5
+ return await this.requestData((r) => r.get('/channels'))
6
+ }
7
+ }
@@ -0,0 +1,15 @@
1
+ import Endpoint from './Endpoint.js'
2
+
3
+ export default class Config extends Endpoint {
4
+ async global() {
5
+ return await this.requestData((r) => r.get('/config'))
6
+ }
7
+
8
+ async app(appId, stationIds) {
9
+ return await this.requestData((r) => r.get(`/config/${appId}`, { station_ids: stationIds }))
10
+ }
11
+
12
+ async updateSchema(appId, schema) {
13
+ await this.api.request().put(`/config/${appId}`, { schema })
14
+ }
15
+ }