-
Notifications
You must be signed in to change notification settings - Fork 6
/
MMM-NewsAPI.js
182 lines (166 loc) · 5.8 KB
/
MMM-NewsAPI.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/* global Log Module QRious */
Module.register("MMM-NewsAPI", {
// Declare default inputs
defaults: {
apiKey: "",
type: "horizontal",
choice: "headlines",
pageSize: 20,
sortBy: "publishedAt",
timeFormat: "relative",
// className: "NEWSAPI",
templateFile: "template.html",
drawInterval: 1000 * 30,
fetchInterval: 1000 * 60 * 60,
debug: false,
QRCode: false,
query: {
country: "us",
category: "",
q: "",
qInTitle: "",
sources: "",
domains: "",
excludeDomains: "",
language: "en"
}
},
// Get the Stylesheet
getStyles () {
return [this.file("MMM-NewsAPI.css")]
},
// Import QR code script file
getScripts () {
return [this.file("node_modules/qrious/dist/qrious.min.js")]
},
// Start process
start () {
this.firstUpdate = 0
this.index = 0
this.timer = null
this.template = ""
this.newsArticles = []
if (this.config.debug) { Log.log("config: ", JSON.stringify(this.config)) }
// Start function call to node_helper
this.getInfo()
// Schedule the next update
this.scheduleUpdate()
},
stop () {
Log.info(`Stopping module ${this.name}`)
},
getDom () {
const wrapper = document.createElement("div")
wrapper.id = "NEWSAPI"
wrapper.className = this.config.type
const newsContent = document.createElement("div")
newsContent.id = "NEWS_CONTENT"
wrapper.appendChild(newsContent)
wrapper.classList.add("untouchable")
return wrapper
},
notificationReceived (notification) {
switch (notification) {
case "DOM_OBJECTS_CREATED":
this.readTemplate()
this.sendSocketNotification("START")
break
}
},
// Schedule the next update
scheduleUpdate (delay) {
if (this.config.debug) { Log.log("Fetch Interval: ", this.config.fetchInterval) }
let nextLoad = this.config.fetchInterval
if (typeof delay !== "undefined" && delay >= 0) {
nextLoad = delay
}
const self = this
setInterval(() => {
Log.debug("getting the next batch of data")
self.getInfo()
}, nextLoad)
},
// Send Socket Notification and start node_helper
getInfo () {
if (this.config.debug) { Log.log("selected choice: ", this.config.choice) }
if (this.config.choice === "headlines") {
this.sendSocketNotification("headlines", this.config)
} else if (this.config.choice === "everything") {
this.sendSocketNotification("everything", this.config)
} else {
Log.log("NewsAPI: Invalid choice defined in config/config.js. Use 'headlines' or 'everything'")
return true
}
},
// Receive Socket Notification
socketNotificationReceived (notification, payload) {
if (this.config.debug) { Log.log("payload received: ", JSON.stringify(payload)) }
if (notification === "NEWSAPI_UPDATE") {
this.newsArticles = payload
if (this.firstUpdate === 0) {
this.firstUpdate = 1
this.index = 0
this.draw()
}
}
},
async readTemplate () {
const file = this.config.templateFile
const url = `modules/MMM-NewsAPI/${file}`
try {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`A Problem has been encountered retrieving the Template File (${response.statusText})`)
}
this.template = await response.text()
} catch (error) {
Log.error(error.message)
}
},
draw () {
clearTimeout(this.timer)
this.timer = null
const tag = [
"sourceId", "author", "content", "description", "articleId",
"sourceName", "title", "url", "urlToImage", "publishedAt"
]
const article = this.newsArticles[this.index]
let template = this.template
for (const i in tag) {
const t = tag[i]
const tu = `%${t.toUpperCase()}%`
template = template.replace(tu, article[t])
}
const imgtag = article.urlToImage ? `<img class="articleImage" src="${article.urlToImage}"/>` : ""
template = template.replace("%ARTICLEIMAGE%", imgtag)
template = template.replace("%CLASSNAME%", "NEWSAPI") // "NEWS"
template = template.replace("%AUTHOR%", article.author)
const news = document.getElementById("NEWSAPI")
const newsContent = document.getElementById("NEWS_CONTENT")
news.classList.add("hideArticle")
news.classList.remove("showArticle")
for (const j in article) { news.dataset[j] = article[j] }
setTimeout(() => {
newsContent.innerHTML = ""
news.classList.remove("hideArticle")
news.classList.add("showArticle")
newsContent.innerHTML = template
if (this.config.QRCode) {
const qr = new QRious({
element: document.getElementById("NEWSAPI_QRCODE"),
value: article.url
})
} else {
const qrCodeElement = document.getElementById("NEWSAPI_QRCODE")
if (qrCodeElement) {
qrCodeElement.parentNode.removeChild(qrCodeElement)
}
}
}, 900)
this.timer = setTimeout(() => {
this.index++
if (this.index >= this.newsArticles.length) { this.index = 0 }
this.draw()
}, this.config.drawInterval)
}
})