dh_ackergaul
vor 3 Tagen bb80cdf5a6157ca1f3a276e12e9faae9a4739cb7
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
const https = require("https");
const http = require("http");
 
const { decode } = FurncloudSecurity;
const WebviewerError = require("furncloud-library").Errors.WebviewerError;
const FurnplanInstanceHistoryService = require("../services/FurnplanInstaceHistoryService.js");
 
function requestPDF(server, sessionID, pdfGuid, cloudId) {
    return new Promise(function (resolve, reject) {
        const httpRequest = server.split("https://").length > 1 ? https : http;
        server = server.replace("https://", "");
        server = server.replace("http://", "");
        const split = server.split(":");
        const options = {
            port: split[1],
            hostname: split[0],
            path: "/getPDF/" + sessionID + "/" + pdfGuid + "/" + cloudId
        };
 
        const callback = function (response) {
            let str = new Buffer("", "utf8");
 
            //another chunk of data has been recieved, so append it to `str`
            response.on("data", function (chunk) {
                const chunkBuffer = new Buffer(chunk, "utf8");
                const length = str.length + chunkBuffer.length;
                str = Buffer.concat([str, chunkBuffer], length);
            });
 
            response.on("error", function () {
                reject();
            });
 
            //the whole response has been recieved, so we just print it out here
            response.on("end", function () {
                resolve(str);
            });
        };
        httpRequest.request(options, callback).end();
    });
}
 
module.exports = {
 
    /**
     * Article viewer page by manufacturer, program and article number.
     */
    view: function (req, res) {
        const token = req.query.token;
        const configurationId = req.query.a;
        const encodedArticle = req.query.b;
 
        const emptyArticle = {
            manu: "",
            level1: "",
            level2: "",
            prog: "",
            artno: "",
            entityType: "a"
        };
 
        try {
            var decodedArticle = JSON.parse(RB64.decode(encodedArticle));
        }
        catch (e) {
            Winston.warn("Invalid article specified: " + encodedArticle);
 
            var decodedArticle = emptyArticle;
        }
 
        // if article number is specified, use regex, else use empty string
        const wantedArticleNo = decodedArticle.artno.length > 0 ? new RegExp(decodedArticle.artno, "i") : "";
 
        const wantedArticle = {
            manu: decodedArticle.manu,
            mprog: decodedArticle.prog,
            artno: wantedArticleNo
        };
 
        const isWantedArticleEmpty = (wantedArticle.manu + wantedArticle.mprog + wantedArticle.artno).length === 0;
 
        Promise.all([
            req.user || Opus.login(token, "webshopViewer", "webshopViewer"),
            FurncloudCredential.findOne({ token: token })
        ])
            .then(async function ([user, credential]) {
 
                user.customerNo = credential.customerNo;
                user.userAgent = req.get("user-agent");
 
                await FurnplanInstanceHistoryService.writeDocument(user.opusSessionId, user.customerNo, req.originalUrl, configurationId, "Configuration", req.headers["user-agent"] || req.headers["User-Agent"] || "");
 
                if (req.query.land && req.query.schiene) {
                    user.data.tenant = (`${req.query.land}-${req.query.schiene}`) || "";
                }
                else if (req.query.tenant) {
                    user.data.tenant = req.query.tenant;
                }
                else {
                    user.data.tenant = "";
                }
 
                let query = {
                    _id: Mongoose.Types.ObjectId(configurationId),
                    customerNo: user.customerNo,
                    externalConf: false
                };
 
                query = await UseCaseConfigurationStorePermissionService.addStorePermission(query, user.customerNo);
 
                return await UseCaseConfiguration
                    .findOne(query)
                    .populate("hrThemeSettings")
                    .populate("dynamicSettings")
                    .populate("accessListSettings")
                    .populate("propertyOrderLists")
                    .populate("defaultArticleList")
                    ////////////////https://joope.de/issues/46324 Kamera Zoom Tisch Stuhl FS / JM
                    .populate({ path: "autoZoomConfig.ignoreBox", model: "AccessListSetting" })
                    .populate({ path: "autoZoomConfig.ignoreAngle", model: "AccessListSetting" })
                    ////////////////
                    .then(function (configuration) {
                        if (configuration) user.data.config = configuration.id;
 
                        return Promise.all([
                            user,
                            configuration,
                            true, // Für Messe
                            Article.findOne(wantedArticle),
                            Helper.isLocalRequest(req.connection.remoteAddress),
                            Session.update({ _id: req.session._id }, { $addToSet: { users: user } }).exec()
                        ]);
                    });
            })
            .then(async function ([user, configuration, hasAccess, article, isLocalRequest]) {
 
                if (!configuration) throw new WebviewerError.InvalidConfigurationId(configurationId);
 
                if (configuration.configuration.webui_mode === true && req.query["is-webui-embedded"] !== "1") {
                    return res.redirect(req.originalUrl.replace("/webviewer", "/webui"));
                }
 
                if (!(isWantedArticleEmpty || hasAccess)) throw new WebviewerError.NoPermission(wantedArticle.manu, wantedArticle.mprog, wantedArticle.artno);
                if (!article) {
                    article = decodedArticle;
                    article.mprog = article.prog;
                    article.entityType = "a";
                }
 
                // globally disable logout and pick mode button in webviewer
                configuration.get("configuration").toolbar_button_logout = false;
                configuration.get("configuration").toolbar_button_pickMode = false;
 
                const newConfiguration = await ConfigurationManager.newConfiguration();
 
                ConfigurationManager.merge(newConfiguration, configuration);
                // newConfiguration.load_initial_article = true;
                // dynamic settings are optional
                if (configuration.dynamicSettings) {
                    const logoImage = configuration.dynamicSettings.properties.filter(function (child) {
                        return child._id === "manu_logo";
                    });
 
                    if (logoImage.length > 0) {
                        newConfiguration.manu_logo = logoImage[0].value;
                    }
                }
 
                if (DevConfigService.get("fv_developer") === true || newConfiguration.furnview_developer_key === "4cfb8ed4d8988dc2c2acf7fdb4c28999601c7644") {
                    newConfiguration.panel_left_show = true;
                }
                newConfiguration.furnview_developer_key = undefined;
 
 
                //Switch between furnview and furnview in wizard mode
                let path = "webviewer/view";
                if (newConfiguration.enable_wizard) {
                    path = "wizard/view";
                }
                if (newConfiguration.enable_wizard_generic) {
                    path = "wizard-generic/view";
                }
 
                if (article && article.prog) {
                    article.prog = article.prog.toUpperCase();
                }
 
                const url = new URL(req.baseUrl + req.originalUrl);
                let encodedArticleCategoryString = url.searchParams.get("articleCategory") || "";
                let decodedArticleCategory = [];
                if (encodedArticleCategoryString) {
                    encodedArticleCategoryString = RB64.decode(encodedArticleCategoryString);
                    decodedArticleCategory = encodedArticleCategoryString.split(",").map(x => x.trim());
                }
 
                return res.view(path, {
                    g_token: token,
                    g_auth_id: req.auth_cookie.id,
                    g_configuration: newConfiguration,
                    g_article: article,
                    g_manufacturer: newConfiguration.selectedManufacturer || "",
                    g_sessionId: user.opusSessionId,
                    g_language: req.query.lang || req.getLocale(),
                    g_reCaptcha: Config.furnview.reCaptchaSiteKey || "",
                    g_article_categories: decodedArticleCategory
                });
            })
            .catch(function (error) {
                if (error instanceof WebviewerError.InvalidConfigurationId || error instanceof WebviewerError.NoPermission) {
                    Winston.warn("Webviewer: " + error.getMessage(), error);
                    return res.send(422, error.getMessage());
                }
                Winston.warn("Unable to open webviewer. ", error);
                return res.send(500, "internal server error");
            });
    },
 
    shareByMail: async function (req, res) {
        const user = req.user;
 
        if (!user) {
            return res.status(403).json({ status: "forbidden" });
        }
 
        try {
            const pdfData = req.body.pdfData;
            const configurationId = await user.data.config;
            let query = { _id: Mongoose.Types.ObjectId(configurationId) };
 
            query = await UseCaseConfigurationStorePermissionService.addStorePermission(query, user.customerNo);
 
            const configuration = await UseCaseConfiguration.findOne(query);
            const shareMailConfigurationId = configuration.get("dynamicSettingsShareMail");
            const shareMailConfiguration = await DynamicSetting.findOne({ _id: shareMailConfigurationId });
 
            if (shareMailConfiguration) {
                const mailSettings = shareMailConfiguration.properties.id(req.body.language || "de");
 
                let mailServerDecoded = "";
                let mailServer = null;
 
                try {
                    mailServerDecoded = decode(shareMailConfiguration.get("mailServer"), sails.config.furnview.symmetricKey);
                    mailServer = JSON.parse(mailServerDecoded);
                }
                catch (e) {
                    console.error("Unable to decode mail server");
 
                    mailServer = null;
                }
 
                const options = {
                    to: req.body.to,
                    cc: mailSettings.get("cc") || "",
                    bcc: mailSettings.get("bcc") || "",
                    subject: mailSettings.get("value"),
                    html: mailSettings.get("value2"),
                    encoding: "quoted-printable",
                    attachments: []
                };
 
                if (mailServer) {
                    options.from = mailSettings.get("sender");
                }
                else {
                    options.from = "cloud@furnview.de";
                    options.replyTo = mailSettings.get("sender");
                }
 
                const values = [{ key: "url", value: req.body.url }, { key: "message", value: req.body.message }];
 
                if (pdfData) {
                    const pdfBinary = await requestPDF(pdfData.server, pdfData.sessionId, pdfData.pdf, pdfData.cloudId);
 
                    options.attachments.push({
                        filename: mailSettings.pdfFilename.replace("{{cloudId}}", pdfData.cloudId),
                        path: "data:application/pdf;base64," + pdfBinary.toString("base64"),
                        contentType: "application/pdf"
                    });
 
                    values.push({ key: "cloudId", value: pdfData.cloudId });
                }
 
                values.forEach((customValue) => {
                    const key = customValue.key;
                    const value = customValue.value;
                    const regEx = new RegExp(`{{ ?${key} ?}}`, "g");
 
                    options.html = options.html.replace(regEx, value);
                });
 
                mailSettings.images.forEach((image) => {
                    options.attachments.push({
                        filename: image.filename,
                        path: image.data,
                        cid: image.cid
                    });
                });
 
                Mailer.sendHtmlMail(options, mailServer);
            }
            else {
                const recipient = req.body.to;
                const message = req.body.message;
                const url = req.body.url;
 
                const subject = req.__({ phrase: "fv.email.homeviewer.share_by_mail.subject", locale: req.getLocale() });
 
                const attachments = [{
                    filename: "furnview.png",
                    path: "assets/images/furnview-mail.png",
                    cid: "furnview-logo"
                }];
 
                let template = req.__("fv.email.webviewer.share_by_mail.template");
 
                template = Mailer.renderHtmlTemplate(template, { url, message });
 
                Mailer.sendHtmlMail(recipient, "furnview@dh-software.de", subject, template, attachments);
            }
 
            return res.json({ status: "ok" });
        }
        catch (e) {
            console.error("unable to share by mail", e);
 
            return res.status(404).json({ status: "not found" });
        }
    }
};