<commit_before>var Nohm = null;
exports.setNohm = function (originalNohm) {
  Nohm = originalNohm;
}

var async = require('async'),
    h = require(__dirname + '/helpers');

/**
 * Check if a given id exists in the DB.
 */
exports.exists = function (id, callback) {
  this.getClient().sismember(Nohm.prefix.idsets+this.modelName, id, function (err, found) {
    Nohm.logError(err);
    callback(!!found);
  });
};

/**
 * Retrieves the hash data by id and puts it into the properties.
 */
exports.load = function (id, callback) {
  var self = this;
  id = parseInt(id, 10);
  if (isNaN(id) || id < 1) {
    Nohm.logError('Trying to pass load() a wrong kind of id. Needs to be a number over 0. (still trying to load it though)');
  }
  this.getClient().hgetall(this.getHashKey(id), function (err, values) {
    var p, value,
        keys = Object.keys(values),
        return_props = {};
    if (err) {
      Nohm.logError('loading a hash produced an error: ' + err);
    }
    if (Array.isArray(keys) && keys.length > 0) {
      for (p in values) {
        if (values.hasOwnProperty(p)) {
          value = values[p] !== null ? values[p].toString() : null;
          if (self.properties[p].load_pure) {
            self.properties[p].value = value;
          } else {
            self.p(p, value);
            return_props[p] = self.p(p);
          }
          self.__resetProp(p);
        }
      }
      self.id = id;
      self.__inDB = true;
      self.__loaded = true;
    } else if (!err) {
      err = 'not found';
    }
    if (typeof(callback) === 'function') {
      callback(err, return_props);
    }
  });
}

/**
 * Finds ids of objects by search arguments
 */
exports.find = function find(searches, callback) {
  var self = this, sets = [], zsetKeys = [], s, prop,
  returnFunction = function (err, values) {
    var found = [];
    Nohm.logError(err);
    if (Array.isArray(values) && values.length > 0) {
      values = values.forEach(function (val, i) {
        if (val) {
          var id = parseInt(val.toString(), 10);
          if (id > 0) {
            found.push(id);
          }
        }
      });
    }
    callback(err, found);
  },
  getSets = function (callback) {
    self.getClient().sinter(sets, callback);
  },
  getSingleZSet = function (zSet, callback) {
    var rangeCallback = function (err, values) {
      if (err) {
        callback(err);
      } else {
        values.forEach(function (val, key) {
          values[key] = parseInt(val, 10);
        });
        callback(null, values);
      }
    };
    options = zSet.options;
    if ( ! options.min && options.min !== 0)
      options.min = '-inf';
    if ( ! options.max && options.max !== 0)
      options.max = '+inf';
    if ( ! options.offset && options.offset !== 0)
      options.offset = '+inf';
    if (options.limit) {
      self.getClient().zrangebyscore(zSet.key, options.min, options.max,
                      'LIMIT', options.offset, options.limit,
                      rangeCallback);
    } else {
      self.getClient().zrangebyscore(zSet.key, options.min, options.max,
                      rangeCallback);
    }
  },
  getZSets = function (callback) {
    async.map(zsetKeys, getSingleZSet, function done (err, arr) {
      var test = h.idIntersection.apply(null, arr);
      callback(null, test.sort());
    });
  };

  if (typeof searches === 'function') {
    callback = searches;
    searches = {};
  }
  for (s in searches) {
    if (searches.hasOwnProperty(s) && this.properties.hasOwnProperty(s)) {
      prop = this.properties[s];
      if (prop.unique) {
        return this.getClient().mget(Nohm.prefix.unique + self.modelName + ':' + s +
                         ':' + searches[s],
                         returnFunction);
      }
      var isNum = !isNaN(parseInt(searches[s], 10));
      if (prop.index && ( ! prop.__numericIndex || isNum) ) {
        sets.push(Nohm.prefix.index + self.modelName + ':' + s + ':' + searches[s]);
      } else if (prop.__numericIndex) {
        zsetKeys.push({
          key: Nohm.prefix.scoredindex + self.modelName + ':' + s,
          options: searches[s]
        });
      }
    }
  }
  if (sets.length === 0 && zsetKeys.length === 0) {
    this.getClient().smembers(Nohm.prefix.idsets + this.modelName, function (err, ids) {
      if (Array.isArray(ids)) {
        ids = ids.map(function (val) {
          return parseInt(val.toString(), 10);
        });
      }
      returnFunction(err, ids);
    });
  } else if (zsetKeys.length === 0) {
    getSets(returnFunction);
  } else if (sets.length === 0) {
    getZSets(returnFunction);
  } else {
    getSets(function (err, setids) {
      if (Array.isArray(setids)) {
        setids = setids.map(function (val) {
          return parseInt(val.toString(), 10);
        });
      }
      getZSets(function (err2, zsetids) {
        if (err2) {
          err = [err, err2];
        }
        returnFunction(err, h.idIntersection(setids, zsetids).sort());
      });
    });
  }
}<commit_msg>Fix load callback argument properties to include load_pure properties as well<commit_after>var Nohm = null;
exports.setNohm = function (originalNohm) {
  Nohm = originalNohm;
}

var async = require('async'),
    h = require(__dirname + '/helpers');

/**
 * Check if a given id exists in the DB.
 */
exports.exists = function (id, callback) {
  this.getClient().sismember(Nohm.prefix.idsets+this.modelName, id, function (err, found) {
    Nohm.logError(err);
    callback(!!found);
  });
};

/**
 * Retrieves the hash data by id and puts it into the properties.
 */
exports.load = function (id, callback) {
  var self = this;
  id = parseInt(id, 10);
  if (isNaN(id) || id < 1) {
    Nohm.logError('Trying to pass load() a wrong kind of id. Needs to be a number over 0. (still trying to load it though)');
  }
  this.getClient().hgetall(this.getHashKey(id), function (err, values) {
    var p, value,
        keys = Object.keys(values),
        return_props = {};
    if (err) {
      Nohm.logError('loading a hash produced an error: ' + err);
    }
    if (Array.isArray(keys) && keys.length > 0) {
      for (p in values) {
        if (values.hasOwnProperty(p)) {
          value = values[p] !== null ? values[p].toString() : null;
          if (self.properties[p].load_pure) {
            self.properties[p].value = value;
          } else {
            self.p(p, value);
          }
          return_props[p] = self.p(p);
          self.__resetProp(p);
        }
      }
      self.id = id;
      self.__inDB = true;
      self.__loaded = true;
    } else if (!err) {
      err = 'not found';
    }
    if (typeof(callback) === 'function') {
      callback(err, return_props);
    }
  });
}

/**
 * Finds ids of objects by search arguments
 */
exports.find = function find(searches, callback) {
  var self = this, sets = [], zsetKeys = [], s, prop,
  returnFunction = function (err, values) {
    var found = [];
    Nohm.logError(err);
    if (Array.isArray(values) && values.length > 0) {
      values = values.forEach(function (val, i) {
        if (val) {
          var id = parseInt(val.toString(), 10);
          if (id > 0) {
            found.push(id);
          }
        }
      });
    }
    callback(err, found);
  },
  getSets = function (callback) {
    self.getClient().sinter(sets, callback);
  },
  getSingleZSet = function (zSet, callback) {
    var rangeCallback = function (err, values) {
      if (err) {
        callback(err);
      } else {
        values.forEach(function (val, key) {
          values[key] = parseInt(val, 10);
        });
        callback(null, values);
      }
    };
    options = zSet.options;
    if ( ! options.min && options.min !== 0)
      options.min = '-inf';
    if ( ! options.max && options.max !== 0)
      options.max = '+inf';
    if ( ! options.offset && options.offset !== 0)
      options.offset = '+inf';
    if (options.limit) {
      self.getClient().zrangebyscore(zSet.key, options.min, options.max,
                      'LIMIT', options.offset, options.limit,
                      rangeCallback);
    } else {
      self.getClient().zrangebyscore(zSet.key, options.min, options.max,
                      rangeCallback);
    }
  },
  getZSets = function (callback) {
    async.map(zsetKeys, getSingleZSet, function done (err, arr) {
      var test = h.idIntersection.apply(null, arr);
      callback(null, test.sort());
    });
  };

  if (typeof searches === 'function') {
    callback = searches;
    searches = {};
  }
  for (s in searches) {
    if (searches.hasOwnProperty(s) && this.properties.hasOwnProperty(s)) {
      prop = this.properties[s];
      if (prop.unique) {
        return this.getClient().mget(Nohm.prefix.unique + self.modelName + ':' + s +
                         ':' + searches[s],
                         returnFunction);
      }
      var isNum = !isNaN(parseInt(searches[s], 10));
      if (prop.index && ( ! prop.__numericIndex || isNum) ) {
        sets.push(Nohm.prefix.index + self.modelName + ':' + s + ':' + searches[s]);
      } else if (prop.__numericIndex) {
        zsetKeys.push({
          key: Nohm.prefix.scoredindex + self.modelName + ':' + s,
          options: searches[s]
        });
      }
    }
  }
  if (sets.length === 0 && zsetKeys.length === 0) {
    this.getClient().smembers(Nohm.prefix.idsets + this.modelName, function (err, ids) {
      if (Array.isArray(ids)) {
        ids = ids.map(function (val) {
          return parseInt(val.toString(), 10);
        });
      }
      returnFunction(err, ids);
    });
  } else if (zsetKeys.length === 0) {
    getSets(returnFunction);
  } else if (sets.length === 0) {
    getZSets(returnFunction);
  } else {
    getSets(function (err, setids) {
      if (Array.isArray(setids)) {
        setids = setids.map(function (val) {
          return parseInt(val.toString(), 10);
        });
      }
      getZSets(function (err2, zsetids) {
        if (err2) {
          err = [err, err2];
        }
        returnFunction(err, h.idIntersection(setids, zsetids).sort());
      });
    });
  }
}<|endoftext|>


<commit_before>'use strict';

module.exports = {
  "rulesDirectory": path.join(path.dirname(require.resolve("codelyzer"))),
  "rules": {
    "arrow-return-shorthand": true,
    "callable-types": true,
    "class-name": true,
    "comment-format": [
      true,
      "check-space"
    ],
    "no-irregular-whitespace": true,
    "no-unnecessary-type-assertion": true,
    "number-literal-format": true,
    "curly": true,
    "eofline": true,
    "forin": true,
    "import-blacklist": [
      true,
      "rxjs",
      "rxjs/Rx",
      "lodash"
    ],
    "import-spacing": true,
    "indent": [
      true,
      "spaces"
    ],
    "interface-over-type-literal": true,
    "label-position": true,
    "max-line-length": [
      true,
      140
    ],
    "member-access": false,
    "member-ordering": [
      true,
      {
        "order": [
          "public-static-field",
          "private-static-field",
          "public-instance-field",
          "private-instance-field",
          "constructor",
          "public-instance-method",
          "public-static-method",
          "private-static-method",
          "private-instance-method"
        ]
      }
    ],
    "no-arg": true,
    "no-bitwise": true,
    "no-console": [
      true,
      "debug",
      "info",
      "time",
      "timeEnd",
      "trace"
    ],
    "no-construct": true,
    "no-debugger": true,
    "no-duplicate-super": true,
    "no-empty": true,
    "no-empty-interface": true,
    "no-eval": true,
    "no-inferrable-types": [
      true,
      "ignore-params"
    ],
    "no-misused-new": true,
    "no-non-null-assertion": true,
    "no-shadowed-variable": true,
    "no-string-literal": false,
    "no-string-throw": true,
    "no-sparse-arrays": true,
    "no-invalid-template-strings": true,
    "no-switch-case-fall-through": true,
    "no-trailing-whitespace": true,
    "no-unnecessary-initializer": true,
    "no-unused-expression": true,
    "no-unused-variable": true,
    "no-use-before-declare": true,
    "no-var-keyword": true,
    "object-literal-sort-keys": false,
    "one-line": [
      true,
      "check-open-brace",
      "check-catch",
      "check-else",
      "check-whitespace"
    ],
    "prefer-const": true,
    "quotemark": [
      true,
      "single"
    ],
    "radix": true,
    "semicolon": [
      true,
      "always"
    ],
    "triple-equals": [
      true,
      "allow-null-check"
    ],
    "typedef-whitespace": [
      true,
      {
        "call-signature": "nospace",
        "index-signature": "nospace",
        "parameter": "nospace",
        "property-declaration": "nospace",
        "variable-declaration": "nospace"
      }
    ],
    "typeof-compare": true,
    "unified-signatures": true,
    "variable-name": false,
    "whitespace": [
      true,
      "check-branch",
      "check-decl",
      "check-operator",
      "check-separator",
      "check-type"
    ],
    "directive-selector": [
      true,
      "attribute",
      "pkd",
      "camelCase"
    ],
    "component-selector": [
      true,
      "element",
      "pkd",
      "kebab-case"
    ],
    "use-input-property-decorator": true,
    "use-output-property-decorator": true,
    "use-host-property-decorator": true,
    "no-input-rename": true,
    "no-output-rename": true,
    "use-life-cycle-interface": true,
    "use-pipe-transform-interface": true,
    "component-class-suffix": true,
    "directive-class-suffix": true,
    "no-access-missing-member": true,
    "templates-use-public": true,
    "invoke-injectable": true,
    "prefer-const ": true,
    "trailing-comma": [
      true,
      {
        "multiline": "never",
        "singleline": "never"
      }
    ],
    "no-banned-terms": true,
    "no-delete-expression": true,
    "no-document-domain": true,
    "no-disable-auto-sanitization": true,
    "no-duplicate-parameter-names": true,
    "no-exec-script": true,
    "no-function-constructor-with-string-args": true,
    "no-octal-literal": true,
    "no-reserved-keywords": true,
    "no-string-based-set-immediate": true,
    "no-string-based-set-interval": true,
    "no-string-based-set-timeout": true,
    "no-duplicate-key": true,
    "no-document-write": true,
    "no-http-string": true,
    "no-inner-html": true,
    "cyclomatic-complexity": [
      true,
      10
    ],
    "no-unsafe-finally": true,
    "only-arrow-functions": [
      true,
      "allow-declarations"
    ],
    "no-magic-numbers": true,
    "no-consecutive-blank-lines": [
      true,
      1
    ],
    "object-literal-shorthand": true,
    "arrow-parens": true,
    "no-unnecessary-callback-wrapper": true
  }
}
<commit_msg>import path<commit_after>'use strict';

const path = require('path');

module.exports = {
  "rulesDirectory": path.join(path.dirname(require.resolve("codelyzer"))),
  "rules": {
    "arrow-return-shorthand": true,
    "callable-types": true,
    "class-name": true,
    "comment-format": [
      true,
      "check-space"
    ],
    "no-irregular-whitespace": true,
    "no-unnecessary-type-assertion": true,
    "number-literal-format": true,
    "curly": true,
    "eofline": true,
    "forin": true,
    "import-blacklist": [
      true,
      "rxjs",
      "rxjs/Rx",
      "lodash"
    ],
    "import-spacing": true,
    "indent": [
      true,
      "spaces"
    ],
    "interface-over-type-literal": true,
    "label-position": true,
    "max-line-length": [
      true,
      140
    ],
    "member-access": false,
    "member-ordering": [
      true,
      {
        "order": [
          "public-static-field",
          "private-static-field",
          "public-instance-field",
          "private-instance-field",
          "constructor",
          "public-instance-method",
          "public-static-method",
          "private-static-method",
          "private-instance-method"
        ]
      }
    ],
    "no-arg": true,
    "no-bitwise": true,
    "no-console": [
      true,
      "debug",
      "info",
      "time",
      "timeEnd",
      "trace"
    ],
    "no-construct": true,
    "no-debugger": true,
    "no-duplicate-super": true,
    "no-empty": true,
    "no-empty-interface": true,
    "no-eval": true,
    "no-inferrable-types": [
      true,
      "ignore-params"
    ],
    "no-misused-new": true,
    "no-non-null-assertion": true,
    "no-shadowed-variable": true,
    "no-string-literal": false,
    "no-string-throw": true,
    "no-sparse-arrays": true,
    "no-invalid-template-strings": true,
    "no-switch-case-fall-through": true,
    "no-trailing-whitespace": true,
    "no-unnecessary-initializer": true,
    "no-unused-expression": true,
    "no-unused-variable": true,
    "no-use-before-declare": true,
    "no-var-keyword": true,
    "object-literal-sort-keys": false,
    "one-line": [
      true,
      "check-open-brace",
      "check-catch",
      "check-else",
      "check-whitespace"
    ],
    "prefer-const": true,
    "quotemark": [
      true,
      "single"
    ],
    "radix": true,
    "semicolon": [
      true,
      "always"
    ],
    "triple-equals": [
      true,
      "allow-null-check"
    ],
    "typedef-whitespace": [
      true,
      {
        "call-signature": "nospace",
        "index-signature": "nospace",
        "parameter": "nospace",
        "property-declaration": "nospace",
        "variable-declaration": "nospace"
      }
    ],
    "typeof-compare": true,
    "unified-signatures": true,
    "variable-name": false,
    "whitespace": [
      true,
      "check-branch",
      "check-decl",
      "check-operator",
      "check-separator",
      "check-type"
    ],
    "directive-selector": [
      true,
      "attribute",
      "pkd",
      "camelCase"
    ],
    "component-selector": [
      true,
      "element",
      "pkd",
      "kebab-case"
    ],
    "use-input-property-decorator": true,
    "use-output-property-decorator": true,
    "use-host-property-decorator": true,
    "no-input-rename": true,
    "no-output-rename": true,
    "use-life-cycle-interface": true,
    "use-pipe-transform-interface": true,
    "component-class-suffix": true,
    "directive-class-suffix": true,
    "no-access-missing-member": true,
    "templates-use-public": true,
    "invoke-injectable": true,
    "prefer-const ": true,
    "trailing-comma": [
      true,
      {
        "multiline": "never",
        "singleline": "never"
      }
    ],
    "no-banned-terms": true,
    "no-delete-expression": true,
    "no-document-domain": true,
    "no-disable-auto-sanitization": true,
    "no-duplicate-parameter-names": true,
    "no-exec-script": true,
    "no-function-constructor-with-string-args": true,
    "no-octal-literal": true,
    "no-reserved-keywords": true,
    "no-string-based-set-immediate": true,
    "no-string-based-set-interval": true,
    "no-string-based-set-timeout": true,
    "no-duplicate-key": true,
    "no-document-write": true,
    "no-http-string": true,
    "no-inner-html": true,
    "cyclomatic-complexity": [
      true,
      10
    ],
    "no-unsafe-finally": true,
    "only-arrow-functions": [
      true,
      "allow-declarations"
    ],
    "no-magic-numbers": true,
    "no-consecutive-blank-lines": [
      true,
      1
    ],
    "object-literal-shorthand": true,
    "arrow-parens": true,
    "no-unnecessary-callback-wrapper": true
  }
}
<|endoftext|>


<commit_before>/*
	This program is Copyright (c) 2003-2005 Andrew Dolgov <cthulhoo@gmail.com>
	Licensed under GPL v.2 or (at your preference) any later version.
*/

var xmlhttp = false;

var total_unread = 0;
var first_run = true;

var search_query = "";

/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
	try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (E) {
		xmlhttp = false;
	}
}
@end @*/

if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	xmlhttp = new XMLHttpRequest();
}

/*
function feedlist_callback() {
	var container = document.getElementById('feeds');
	if (xmlhttp.readyState == 4) {
		container.innerHTML=xmlhttp.responseText;

		if (first_run) {
			scheduleFeedUpdate(false);
			if (getCookie("ttrss_vf_actfeed")) {
				viewfeed(getCookie("ttrss_vf_actfeed"), 0, "");
			}
			first_run = false;
		} else {
			notify("");
		}
	}
}
*/

function refetch_callback() {

	if (xmlhttp.readyState == 4) {

		document.title = "Tiny Tiny RSS";
		notify("All feeds updated.");

		updateFeedList();

	}
}

function updateFeed(feed_id) {

	var query_str = "backend.php?op=rpc&subop=updateFeed&feed=" + feed_id;

	if (xmlhttp_ready(xmlhttp)) {
		xmlhttp.open("GET", query_str, true);
		xmlhttp.onreadystatechange=feed_update_callback;
		xmlhttp.send(null);
	} else {
		printLockingError();
	}

}

function scheduleFeedUpdate(force) {

	notify("Updating feeds in background...");

	document.title = "Tiny Tiny RSS - Updating...";

	var query_str = "backend.php?op=rpc&subop=";

	if (force) {
		query_str = query_str + "forceUpdateAllFeeds";
	} else {
		query_str = query_str + "updateAllFeeds";
	}

	if (xmlhttp_ready(xmlhttp)) {
		xmlhttp.open("GET", query_str, true);
		xmlhttp.onreadystatechange=refetch_callback;
		xmlhttp.send(null);
	} else {
		printLockingError();
	}
}

function updateFeedList(silent, fetch) {

//	if (silent != true) {
//		notify("Loading feed list...");
//	}

	var query_str = "backend.php?op=feeds";

	if (getActiveFeedId()) {
		query_str = query_str + "&actid=" + getActiveFeedId();
	}

	if (fetch) query_str = query_str + "&fetch=yes";

	var feeds_frame = document.getElementById("feeds-frame");

	feeds_frame.src = query_str;
}

function catchupAllFeeds() {

	var query_str = "backend.php?op=feeds&subop=catchupAll";

	notify("Marking all feeds as read...");

	var feeds_frame = document.getElementById("feeds-frame");

	feeds_frame.src = query_str;

}

function viewCurrentFeed(skip, subop) {

	if (getActiveFeedId()) {
		viewfeed(getActiveFeedId(), skip, subop);
	}
}

function viewfeed(feed, skip, subop) {

//	notify("Loading headlines...");

	enableHotkeys();

	var searchbox = document.getElementById("searchbox");

	if (searchbox) {
		search_query = searchbox.value;
	} else {
		search_query = "";
	}

	var viewbox = document.getElementById("viewbox");

	var view_mode;

	if (viewbox) {
		view_mode = viewbox[viewbox.selectedIndex].text;
	} else {
		view_mode = "All Posts";
	}

	setCookie("ttrss_vf_vmode", view_mode);

	var limitbox = document.getElementById("limitbox");

	var limit;

	if (limitbox) {
		limit = limitbox[limitbox.selectedIndex].text;
		setCookie("ttrss_vf_limit", limit);
	} else {
		limit = "All";
	}

	setActiveFeedId(feed);

	var f_doc = frames["feeds-frame"].document;

//	f_doc.getElementById("ACTFEEDID").innerHTML = feed;

	if (subop == "MarkAllRead") {

		var feedr = f_doc.getElementById("FEEDR-" + feed);
		var feedctr = f_doc.getElementById("FEEDCTR-" + feed);

		feedctr.className = "invisible";

		if (feedr.className.match("Unread")) {
			feedr.className = feedr.className.replace("Unread", "");
		}
	}

	var query = "backend.php?op=viewfeed&feed=" + param_escape(feed) +
		"&skip=" + param_escape(skip) + "&subop=" + param_escape(subop) +
		"&view=" + param_escape(view_mode) + "&limit=" + limit;

	if (search_query != "") {
		query = query + "&search=" + param_escape(search_query);
	}

	var headlines_frame = parent.frames["headlines-frame"];

	headlines_frame.location.href = query + "&addheader=true";

	cleanSelected("feedsList");
	var feedr = document.getElementById("FEEDR-" + feed);
	if (feedr) {
		feedr.className = feedr.className + "Selected";
	}

	disableContainerChildren("headlinesToolbar", false, doc);

//	notify("");

}

function timeout() {
	scheduleFeedUpdate(true);
	setTimeout("timeout()", 1800*1000);
}

function resetSearch() {
	var searchbox = document.getElementById("searchbox")

	if (searchbox.value != "" && getActiveFeedId()) {
		searchbox.value = "";
		viewfeed(getActiveFeedId(), 0, "");
	}
}

function search() {
	checkActiveFeedId();
	if (getActiveFeedId()) {
		viewfeed(getActiveFeedId(), 0, "");
	} else {
		notify("Please select some feed first.");
	}
}

function localPiggieFunction(enable) {
	if (enable) {
		var query_str = "backend.php?op=feeds&subop=piggie";

		if (xmlhttp_ready(xmlhttp)) {

			xmlhttp.open("GET", query_str, true);
			xmlhttp.onreadystatechange=feedlist_callback;
			xmlhttp.send(null);
		}
	}
}

function localHotkeyHandler(keycode) {

/*	if (keycode == 78) {
		return moveToPost('next');
	}

	if (keycode == 80) {
		return moveToPost('prev');
	} */

	if (keycode == 82) {
		return scheduleFeedUpdate(true);
	}

	if (keycode == 85) {
		return viewfeed(getActiveFeedId(), 0, "ForceUpdate");
	}

//	notify("KC: " + keycode);

}

function init() {

	disableContainerChildren("headlinesToolbar", true);

	if (!xmlhttp) {
		document.getElementById("headlines").innerHTML =
			"Fatal error: This program requires XmlHttpRequest " +
			"to function properly. Your browser doesn't seem to support it.";
		return;
	}

	updateFeedList(false, false);
	document.onkeydown = hotkey_handler;

	setTimeout("timeout()", 1800*1000);
	scheduleFeedUpdate(true);

	var content = document.getElementById("content");

	if (getCookie("ttrss_vf_vmode")) {
		var viewbox = document.getElementById("viewbox");
		viewbox.value = getCookie("ttrss_vf_vmode");
	}

	if (getCookie("ttrss_vf_limit")) {
		var limitbox = document.getElementById("limitbox");
		limitbox.value = getCookie("ttrss_vf_limit");
	}

//	if (getCookie("ttrss_vf_actfeed")) {
//		viewfeed(getCookie("ttrss_vf_actfeed"), 0, '');
//	}

	setCookie("ttrss_vf_actfeed", "");

}

<commit_msg>more cookie magic, basic sanity checks on init()<commit_after>/*
	This program is Copyright (c) 2003-2005 Andrew Dolgov <cthulhoo@gmail.com>
	Licensed under GPL v.2 or (at your preference) any later version.
*/

var xmlhttp = false;

var total_unread = 0;
var first_run = true;

var search_query = "";

/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
	try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (E) {
		xmlhttp = false;
	}
}
@end @*/

if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	xmlhttp = new XMLHttpRequest();
}

/*
function feedlist_callback() {
	var container = document.getElementById('feeds');
	if (xmlhttp.readyState == 4) {
		container.innerHTML=xmlhttp.responseText;

		if (first_run) {
			scheduleFeedUpdate(false);
			if (getCookie("ttrss_vf_actfeed")) {
				viewfeed(getCookie("ttrss_vf_actfeed"), 0, "");
			}
			first_run = false;
		} else {
			notify("");
		}
	}
}
*/

function refetch_callback() {

	if (xmlhttp.readyState == 4) {

		document.title = "Tiny Tiny RSS";
		notify("All feeds updated.");

		updateFeedList();

	}
}

function updateFeed(feed_id) {

	var query_str = "backend.php?op=rpc&subop=updateFeed&feed=" + feed_id;

	if (xmlhttp_ready(xmlhttp)) {
		xmlhttp.open("GET", query_str, true);
		xmlhttp.onreadystatechange=feed_update_callback;
		xmlhttp.send(null);
	} else {
		printLockingError();
	}

}

function scheduleFeedUpdate(force) {

	notify("Updating feeds in background...");

	document.title = "Tiny Tiny RSS - Updating...";

	var query_str = "backend.php?op=rpc&subop=";

	if (force) {
		query_str = query_str + "forceUpdateAllFeeds";
	} else {
		query_str = query_str + "updateAllFeeds";
	}

	if (xmlhttp_ready(xmlhttp)) {
		xmlhttp.open("GET", query_str, true);
		xmlhttp.onreadystatechange=refetch_callback;
		xmlhttp.send(null);
	} else {
		printLockingError();
	}
}

function updateFeedList(silent, fetch) {

//	if (silent != true) {
//		notify("Loading feed list...");
//	}

	var query_str = "backend.php?op=feeds";

	if (getActiveFeedId()) {
		query_str = query_str + "&actid=" + getActiveFeedId();
	}

	if (fetch) query_str = query_str + "&fetch=yes";

	var feeds_frame = document.getElementById("feeds-frame");

	feeds_frame.src = query_str;
}

function catchupAllFeeds() {

	var query_str = "backend.php?op=feeds&subop=catchupAll";

	notify("Marking all feeds as read...");

	var feeds_frame = document.getElementById("feeds-frame");

	feeds_frame.src = query_str;

}

function viewCurrentFeed(skip, subop) {

	if (getActiveFeedId()) {
		viewfeed(getActiveFeedId(), skip, subop);
	}
}

function viewfeed(feed, skip, subop) {

//	notify("Loading headlines...");

	enableHotkeys();

	var searchbox = document.getElementById("searchbox");

	if (searchbox) {
		search_query = searchbox.value;
	} else {
		search_query = "";
	}

	var viewbox = document.getElementById("viewbox");

	var view_mode;

	if (viewbox) {
		view_mode = viewbox[viewbox.selectedIndex].text;
	} else {
		view_mode = "All Posts";
	}

	setCookie("ttrss_vf_vmode", view_mode);

	var limitbox = document.getElementById("limitbox");

	var limit;

	if (limitbox) {
		limit = limitbox[limitbox.selectedIndex].text;
		setCookie("ttrss_vf_limit", limit);
	} else {
		limit = "All";
	}

	setActiveFeedId(feed);

	var f_doc = frames["feeds-frame"].document;

//	f_doc.getElementById("ACTFEEDID").innerHTML = feed;

	if (subop == "MarkAllRead") {

		var feedr = f_doc.getElementById("FEEDR-" + feed);
		var feedctr = f_doc.getElementById("FEEDCTR-" + feed);

		feedctr.className = "invisible";

		if (feedr.className.match("Unread")) {
			feedr.className = feedr.className.replace("Unread", "");
		}
	}

	var query = "backend.php?op=viewfeed&feed=" + param_escape(feed) +
		"&skip=" + param_escape(skip) + "&subop=" + param_escape(subop) +
		"&view=" + param_escape(view_mode) + "&limit=" + limit;

	if (search_query != "") {
		query = query + "&search=" + param_escape(search_query);
	}

	var headlines_frame = parent.frames["headlines-frame"];

	headlines_frame.location.href = query + "&addheader=true";

	cleanSelected("feedsList");
	var feedr = document.getElementById("FEEDR-" + feed);
	if (feedr) {
		feedr.className = feedr.className + "Selected";
	}

	disableContainerChildren("headlinesToolbar", false, doc);

//	notify("");

}

function timeout() {
	scheduleFeedUpdate(true);
	setTimeout("timeout()", 1800*1000);
}

function resetSearch() {
	var searchbox = document.getElementById("searchbox")

	if (searchbox.value != "" && getActiveFeedId()) {
		searchbox.value = "";
		viewfeed(getActiveFeedId(), 0, "");
	}
}

function search() {
	checkActiveFeedId();
	if (getActiveFeedId()) {
		viewfeed(getActiveFeedId(), 0, "");
	} else {
		notify("Please select some feed first.");
	}
}

function localPiggieFunction(enable) {
	if (enable) {
		var query_str = "backend.php?op=feeds&subop=piggie";

		if (xmlhttp_ready(xmlhttp)) {

			xmlhttp.open("GET", query_str, true);
			xmlhttp.onreadystatechange=feedlist_callback;
			xmlhttp.send(null);
		}
	}
}

function localHotkeyHandler(keycode) {

/*	if (keycode == 78) {
		return moveToPost('next');
	}

	if (keycode == 80) {
		return moveToPost('prev');
	} */

	if (keycode == 82) {
		return scheduleFeedUpdate(true);
	}

	if (keycode == 85) {
		return viewfeed(getActiveFeedId(), 0, "ForceUpdate");
	}

//	notify("KC: " + keycode);

}

function genericSanityCheck() {

	if (!xmlhttp) {
		document.getElementById("headlines").innerHTML =
			"Fatal error: This program requires XmlHttpRequest " +
			"to function properly. Your browser doesn't seem to support it.";
		return false;
	}

	setCookie("ttrss_vf_test", "TEST");
	if (getCookie("ttrss_vf_test") != "TEST") {

		document.getElementById("headlines").innerHTML =
			"Fatal error: This program requires cookies " +
			"to function properly. Your browser doesn't seem to support them.";

		return false;
	}

	return true;
}

function init() {

	disableContainerChildren("headlinesToolbar", true);

	if (!genericSanityCheck())
		return;

	updateFeedList(false, false);
	document.onkeydown = hotkey_handler;

	setTimeout("timeout()", 1800*1000);
	scheduleFeedUpdate(true);

	var content = document.getElementById("content");

	if (getCookie("ttrss_vf_vmode")) {
		var viewbox = document.getElementById("viewbox");
		viewbox.value = getCookie("ttrss_vf_vmode");
	}

	if (getCookie("ttrss_vf_limit")) {
		var limitbox = document.getElementById("limitbox");
		limitbox.value = getCookie("ttrss_vf_limit");
	}

//	if (getCookie("ttrss_vf_actfeed")) {
//		viewfeed(getCookie("ttrss_vf_actfeed"), 0, '');
//	}

	setCookie("ttrss_vf_actfeed", "");

}

<|endoftext|>


<commit_before>var request = require('request')
  , _ = require('underscore');

var resources = {
  Track: require('./resources/track')
, Route: require('./resources/route')
, OptimizationProblem: require('./resources/optimization_problem')
};

function Route4me(api_key) {
  if (!(this instanceof Route4me)) {
    return new Route4me(api_key);
  }

  this._useResources();
  this.setBaseUrl('http://route4me.com');
  this.api_key = api_key;
}

Route4me.prototype.setBaseUrl = function(base_url) {
  this.url_base = base_url;
}

Route4me.prototype._useResources = function() {
  for (var name in resources) {
    this[name] = resources[name](this);
  }
}

Route4me.prototype.getApiKey = function () {
  return this.api_key;
};

Route4me.prototype._generateUrl = function(url) {
  return this.url_base + url;
}

Route4me.prototype._makeRequest = function(options, callback) {
  var qs = _.extend({
    api_key: this.getApiKey()
  }, options['qs'] || {});
  delete options['qs'];

  var body = JSON.stringify(options['body']);
  delete options['body'];

  options = _.extend({
    json: true
  , qs: qs
  , body: body
  , headers:  { 'User-Agent': 'Route4me nodejs sdk' }
  }, options);

  request(options, function(err, res, body) {
    if (err) {
      console.log(err);
      return callback(err);
    }

    if (404 === res.statusCode) {
      console.log(body);
      callback('Page not found');
    } else {
      callback(null, body);
    }
  });
};

Route4me.version = require('../package.json').version;
module.exports = Route4me;
<commit_msg>allow redirects<commit_after>var request = require('request')
  , _ = require('underscore');

var resources = {
  Track: require('./resources/track')
, Route: require('./resources/route')
, OptimizationProblem: require('./resources/optimization_problem')
};

function Route4me(api_key) {
  if (!(this instanceof Route4me)) {
    return new Route4me(api_key);
  }

  this._useResources();
  this.setBaseUrl('http://route4me.com');
  this.api_key = api_key;
}

Route4me.prototype.setBaseUrl = function(base_url) {
  this.url_base = base_url;
}

Route4me.prototype._useResources = function() {
  for (var name in resources) {
    this[name] = resources[name](this);
  }
}

Route4me.prototype.getApiKey = function () {
  return this.api_key;
};

Route4me.prototype._generateUrl = function(url) {
  return this.url_base + url;
}

Route4me.prototype._makeRequest = function(options, callback) {
  var qs = _.extend({
    api_key: this.getApiKey()
  }, options['qs'] || {});
  delete options['qs'];

  var body = JSON.stringify(options['body']);
  delete options['body'];

  options = _.extend({
    json: true
  , qs: qs
  , body: body
  , headers:  { 'User-Agent': 'Route4me nodejs sdk' }
  , followAllRedirects: true
  }, options);

  request(options, function(err, res, body) {
    if (err) {
      console.log(err);
      return callback(err);
    }

    if (404 === res.statusCode) {
      console.log(body);
      callback('Page not found');
    } else {
      callback(null, body);
    }
  });
};

Route4me.version = require('../package.json').version;
module.exports = Route4me;
<|endoftext|>


<commit_before>var sys = require('sys'),
	fs = require('fs'),
	request = require('request'),
	htmlparser = require("htmlparser");

process.addListener('uncaughtException', function (err, stack) {
	console.log('Caught exception: ' + err);
	console.log(err.stack);
});

function BotRSS(rssFeed) {
	process.EventEmitter.call(this);
	var self = this;

	var handler = new htmlparser.RssHandler(function (error, dom) {
		if (error)
			sys.puts(error);
		//else
		//   sys.puts(dom);
	});

	setInterval(function() {
		if(typeof(rssFeed.lastCheck) == 'undefined')
			rssFeed.lastCheck = new Date().getTime();
		now = new Date().getTime();
		if(now > rssFeed.lastCheck + rssFeed.interval) {
			console.log("Checking feed: " + JSON.stringify(rssFeed));
			request({'uri': rssFeed.url}, function(err, res, body) {
				var parser = new htmlparser.Parser(handler);
				parser.parseComplete(body);
				//sys.puts(sys.inspect(handler.dom, false, null));
				if(typeof(handler.dom.items) == 'undefined') {
					console.log('%s; had trouble fetching/parsing', rssFeed.name);
				} else {
					Object.keys(handler.dom.items).reverse().forEach(function(item) {
						//console.log('emitting' + handler.dom.items[item]);
						self.emit('rssitem', handler.dom.items[item]);
					});
				}
			});
			rssFeed.lastCheck = now;
		}
	}, 10*1000, this);
}

sys.inherits(BotRSS, process.EventEmitter);

module.exports = BotRSS;

<commit_msg>moretest<commit_after>var sys = require('sys'),
	fs = require('fs'),
	request = require('request'),
	htmlparser = require("htmlparser");

process.addListener('uncaughtException', function (err, stack) {
	console.log('Caught exception: ' + err);
	console.log(err.stack);
});

function BotRSS(rssFeed) {
	process.EventEmitter.call(this);
	var self = this;

	var handler = new htmlparser.RssHandler(function (error, dom) {
		if (error)
			sys.puts(error);
		//else
		//   sys.puts(dom);
	});

	setInterval(function() {
		if(typeof(rssFeed.lastCheck) == 'undefined')
			rssFeed.lastCheck = new Date().getTime();
		now = new Date().getTime();
		if(now > rssFeed.lastCheck + rssFeed.interval) {
			request({'uri': rssFeed.url}, function(err, res, body) {
				var parser = new htmlparser.Parser(handler);
				parser.parseComplete(body);
				//sys.puts(sys.inspect(handler.dom, false, null));
				if(typeof(handler.dom.items) == 'undefined') {
					console.log('%s; had trouble fetching/parsing', rssFeed.name);
				} else {
					Object.keys(handler.dom.items).reverse().forEach(function(item) {
						//console.log('emitting' + handler.dom.items[item]);
						self.emit('rssitem', handler.dom.items[item]);
					});
				}
			});
			rssFeed.lastCheck = now;
		}
	}, 10*1000, this);
}

sys.inherits(BotRSS, process.EventEmitter);

module.exports = BotRSS;

<|endoftext|>