aboutsummaryrefslogtreecommitdiffstats
path: root/lib/libbugzilla.js
blob: 14fd67509643f7b6e9ee9d59848ccb8bfc51e2cb (plain) (blame)
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
/*jslint rhino: true, forin: true, onevar: false, browser: true, evil: true, laxbreak: true, undef: true, nomen: true, eqeqeq: false, bitwise: true, maxerr: 1000, immed: false, white: false, plusplus: false, regexp: false, undef: false */
// Released under the MIT/X11 license
// http://www.opensource.org/licenses/mit-license.php
//
"use strict";
var preferences = require("preferences-service");
var prompts = require("prompts");
var clipboard = require("clipboard");
var tabs = require("tabs");
//var logger = require("logger");
var passUtils = require("passwords");
var Request = require("request").Request;
var selfMod = require("self");
var urlMod = require("url");

var JSONURLDefault = "https://fedorahosted.org/released"+
    "/bugzilla-triage-scripts/Config_data.json";
var BTSPrefNS = "bugzilla-triage.setting.";
var BTSPassRealm = "BTSXMLRPCPass";

function Message(cmd, data) {
    console.log("Message: cmd = " + cmd + ", data = " + data);
	this.cmd = cmd;
	this.data = data;
}

function log(msg) {
	postMessage(new Message("LogMessage", msg));
}

/**
 * parse XML object out of string working around various bugs in Gecko implementation
 * see https://developer.mozilla.org/en/E4X for more information
 *
 * @param inStr String with unparsed XML string
 * @return XML object
 */
function parseXMLfromString (inStuff) {
    // if (typeof inStuff !== 'string') In future we should recognize this.response
    // and get just .text property out of it. TODO
    var respStr = inStuff.replace(/^<\?xml\s+version\s*=\s*(["'])[^\1]+\1[^?]*\?>/, ""); // bug 336551
    return new XML(respStr);
}

/**
 * In case URL contains alias, not the real bug number, get the real bug no
 * from the XML representation. Sets correct value to this.bugNo.
 *
 * somewhere in RPC functions which need it, we should have
 * if (isNAN(parseInt(bugNo, 10))) {
 *    getRealBugNo(bugNo, location, callback);
 * }
 * Or not
 */
function getRealBugNo(bugNo, location, callback) {
    console.log("We have to deal with bug aliased as " + this.bugNo);
    // https://bugzilla.redhat.com/show_bug.cgi?ctype=xml&id=serialWacom
    Request({
        url: location.href+"&ctype=xml",
        onComplete: function(response) {
            if (response.status === 200) {
                var xmlRepr = parseXMLfromString(response.text);
                // TODO this probably wrong, both XPath and .text attribute
                var bugID = parseInt(xmlRepr.bug.bug_id.text, 10);
                if (isNaN(bugID)) {
                    throw new Error("Cannot get bug no. even from XML representation!");
                }
                console.log("The real bug no. is " + bugID);
                callback(bugID)
            }
        }
    }).get();
}

exports.getPassword = function getPassword(login, domain, callback) {
    var passPrompt = "Enter your Bugzilla password for fixing MIME attachment types";
    var switchPrompt = "Do you want to switch off features requiring password completely";
    var prefName = BTSPrefNS+"withoutPassowrd";
    var domain = window.location.protocol + "//" + window.location.hostname;

    var pass = passUtils.getPassword(login,
        domain, BTSPassRealm);
    var retObject = {
        password:  null,
        withoutPass: false
    };

    // pass === null means no appropriate password in the storage
    if (!preferences.get(prefName,false) && (pass === null)) {
        passwordText = prompts.promptPassword(passPrompt);
        if (passwordText && passwordText.length > 0) {
            passUtils.setLogin(login, passwordText, domain,
                BTSPassRealm);
            retObject.password = passwordText;
        } else {
            var switchOff = prompts.promptYesNoCancel(switchPrompt);
            if (switchOff) {
                preferences.set(prefName,true);
            }
            retObject.withoutPass = switchOff;
        }
    } else {
        retObject.password = pass;
    }
   callback(new Message("RetPassword", retObject));
};

exports.changeJSONURL = function changeJSONURL() {
    var prfNm = BTSPrefNS+"JSONURL";
    var url = preferences.get(prfNm,"");

    var reply = prompts.prompt("New location of JSON configuration file", url);
    if (reply) {
        preferences.set(prfNm, reply.trim());
        // TODO Restartless add-on needs to resolve this.
        prompts.alert("For now, you should really restart Firefox!");
    }
};

/**
 *
   libbz.getInstalledPackages(msg.data, function (pkgsMsg) {
                worker.postMessage(pkgsMsg);
 */
exports.getInstalledPackages = function getInstalledPackages(location, config, callback) {
    var installedPackages = {};
    var enabledPackages = [];

    if (typeof location == "string") {
        location = new urlMod.URL(location);
    }

    console.log("location = " + location);
    console.log("typeof location = " + typeof location);

    // Collect enabled packages per hostname (plus default ones)
    if (config.gJSONData && ("commentPackages" in config.gJSONData)) {
        if ("enabledPackages" in config.gJSONData.configData) {
            var epObject = config.gJSONData.configData.enabledPackages;
            if (location.host in epObject) {
                enabledPackages = enabledPackages.concat(epObject[location.host].split(/[,\s]+/));
            }
            if ("any" in epObject) {
                enabledPackages = enabledPackages.concat(epObject.any.split(/[,\s]+/));
            }
        }

        var allIdx = null;
        if ((allIdx = enabledPackages.indexOf("all")) != -1) {
            enabledPackages = enabledPackages.splice(allIdx,
                config.gJSONData.commentPackages.keys());
        }

        // TODO To be decided, whether we cannot just eliminate packages in
        // installedPackages and having it just as a plain list of all cmdObjects.
        enabledPackages.forEach(function (pkg, idx, arr) {
            if (pkg in config.gJSONData.commentPackages) {
                installedPackages[pkg] = config.gJSONData.commentPackages[pkg];
            }
        });
    }

    // Expand commentIdx properties into full comments
    var cmdObj = {};
    for (var pkgKey in installedPackages) {
        for (var cmdObjKey in installedPackages[pkgKey]) {
            cmdObj = installedPackages[pkgKey][cmdObjKey];
            if ("commentIdx" in cmdObj) {
                cmdObj.comment = config.gJSONData.commentStrings[cmdObj.commentIdx];
                delete cmdObj.commentIdx;
            }
        }
    }

    callback(new Message("CreateButtons", {
        instPkgs: installedPackages,
        constData: config.constantData,
        kNodes: config.gJSONData.configData.killNodes
    }));
};

exports.getClipboard = function getClipboard(command, cb) {
    cb(new Message("RetClipboard", {
        text: clipboard.get(),
        cmd: command
    }));
};

exports.openURLinNewTab = function openURLinNewTab(urlStr) {
    tabs.open({
        url: urlStr,
        inBackground: true,
        onReady: function (t) {
            t.activate();
        }
    });
};

exports.initialize = function initialize(config, callback) {
    var prefName = BTSPrefNS+"JSONURL";
    var urlStr = "";

    if (preferences.isSet(prefName)) {
        urlStr = preferences.get(prefName);
    } else {
        urlStr = JSONURLDefault;
        preferences.set(prefName, JSONURLDefault);
    }

    // Randomize URL to avoid caching
    // TODO see https://fedorahosted.org/bugzilla-triage-scripts/ticket/21
    // for more thorough discussion and possible further improvement
    urlStr += (urlStr.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();

    Request({
        url: urlStr,
        onComplete: function (response) {
            if (response.status == 200) {
                config.gJSONData = response.json;

                // Get additional tables
                if ("downloadJSON" in config.gJSONData.configData) {
                    var URLsList = config.gJSONData.configData.downloadJSON;
                    var dwnldObj = "";
                    URLsList.forEach(function (arr) {
                        var title = arr[0];
                        var url = arr[1];
                        Request({
                            url: url,
                            onComplete: function(response) {
                                if (response.status == 200) {
                                    config.gJSONData.constantData[title] = response.json;
                                }
                            }
                        }).get();
                    });
                }

                // config.logger = new logger.Logger(JSON.parse(self.data.load("bugzillalabelAbbreviations.json")));

                config.matches = config.gJSONData.configData.matches;
                config.skipMatches = config.matches.map(function(x) {
                    return x.replace("show_bug.cgi.*","((process|post)_bug|attachment)\.cgi$");
                });

                config.objConstructor = {};
                // var bzType = config.gJSONData.configData.objectStyle;
                // if (bzType === "RH") {
                    // config.objConstructor = require("rhbzpage").RHBugzillaPage;
                // } else if (bzType === "MoFo") {
                // }
                    // config.objConstructor = require("mozillabzpage").MozillaBugzilla;

                // callback(config);

                config.constantData = {};
                // TODO this is important and missing
                if ("constantData" in config.gJSONData) {
                    config.constantData = config.gJSONData.constantData;
                    config.constantData.queryUpstreamBug = JSON.parse(
                        selfMod.data.load("queryUpstreamBug.json"));
                    config.constantData.XMLRPCData = JSON.parse(
                        selfMod.data.load("XMLRPCdata.json"));
                }

                if ("CCmaintainer" in config.constantData) {
                    config.defBugzillaMaintainerArr = config.constantData.CCmaintainer;
                }

                if ("suspiciousComponents" in config.gJSONData.configData) {
                    config.suspiciousComponents = config.gJSONData.configData.suspiciousComponents;
                }

                if ("XorgLogAnalysis" in config.gJSONData.configData) {
                    config.xorglogAnalysis = config.gJSONData.configData.XorgLogAnalysis;
                }

                if ("submitsLogging" in config.gJSONData.configData &&
                    config.gJSONData.configData.submitsLogging) {
                    // config.log = config.logger;
                    // FIXME this.setUpLogging();
                }
           }
        callback();
        }
    }).get();
}